diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java index 1565534f..3258c509 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java @@ -1,4207 +1,4233 @@ package com.redhat.ceylon.compiler.js; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisWarning; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.ImportableScope; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.InterfaceAlias; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.Specification; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.*; import com.redhat.ceylon.compiler.typechecker.tree.Tree.*; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Stack<Continuation> continues = new Stack<Continuation>(); private final EnclosingFunctionVisitor encloser = new EnclosingFunctionVisitor(); private final JsIdentifierNames names; private final Set<Declaration> directAccess = new HashSet<Declaration>(); private final RetainedVars retainedVars = new RetainedVars(); final ConditionGenerator conds; private final InvocationGenerator invoker; private final List<CommonToken> tokens; private int dynblock; private final class SuperVisitor extends Visitor { private final List<Declaration> decs; private SuperVisitor(List<Declaration> decs) { this.decs = decs; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { Term primary = eliminateParensAndWidening(qe.getPrimary()); if (primary instanceof Super) { decs.add(qe.getDeclaration()); } super.visit(qe); } @Override public void visit(QualifiedType that) { if (that.getOuterType() instanceof SuperType) { decs.add(that.getDeclarationModel()); } super.visit(that); } public void visit(Tree.ClassOrInterface qe) { //don't recurse if (qe instanceof ClassDefinition) { ExtendedType extType = ((ClassDefinition) qe).getExtendedType(); if (extType != null) { super.visit(extType); } } } } private final class OuterVisitor extends Visitor { boolean found = false; private Declaration dec; private OuterVisitor(Declaration dec) { this.dec = dec; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { if (qe.getPrimary() instanceof Outer || qe.getPrimary() instanceof This) { if ( qe.getDeclaration().equals(dec) ) { found = true; } } super.visit(qe); } } private List<? extends Statement> currentStatements = null; private final TypeUtils types; private Writer out; private final Writer originalOut; final Options opts; private CompilationUnit root; private static String clAlias=""; private static final String function="function "; private boolean needIndent = true; private int indentLevel = 0; Package getCurrentPackage() { return root.getUnit().getPackage(); } private static void setCLAlias(String alias) { clAlias = alias + "."; } /** Returns the module name for the language module. */ static String getClAlias() { return clAlias; } @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } private final JsOutput jsout; public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names, List<CommonToken> tokens, TypeUtils typeUtils) throws IOException { this.jsout = out; this.opts = options; this.out = out.getWriter(); originalOut = out.getWriter(); this.names = names; conds = new ConditionGenerator(this, names, directAccess); this.tokens = tokens; types = typeUtils; invoker = new InvocationGenerator(this, names, retainedVars); } TypeUtils getTypeUtils() { return types; } InvocationGenerator getInvoker() { return invoker; } /** Returns the helper component to handle naming. */ JsIdentifierNames getNames() { return names; } private static interface GenerateCallback { public void generateValue(); } /** Print generated code to the Writer specified at creation time. * Automatically prints indentation first if necessary. * @param code The main code * @param codez Optional additional strings to print after the main code. */ void out(String code, String... codez) { try { if (opts.isIndent() && needIndent) { for (int i=0;i<indentLevel;i++) { out.write(" "); } } needIndent = false; out.write(code); for (String s : codez) { out.write(s); } if (opts.isVerbose() && out == originalOut) { //Print code to console (when printing to REAL output) System.out.print(code); for (String s : codez) { System.out.print(s); } } } catch (IOException ioe) { throw new RuntimeException("Generating JS code", ioe); } } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. */ void endLine() { endLine(false); } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. * @param semicolon if <code>true</code> then a semicolon is printed at the end * of the previous line*/ void endLine(boolean semicolon) { if (semicolon) { out(";"); } out("\n"); needIndent = true; } /** Calls {@link #endLine()} if the current position is not already the beginning * of a line. */ void beginNewLine() { if (!needIndent) { endLine(); } } /** Increases indentation level, prints opening brace and newline. Indentation will * automatically be printed by {@link #out(String, String...)} when the next line is started. */ void beginBlock() { indentLevel++; out("{"); endLine(); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. */ void endBlockNewLine() { endBlock(false, true); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. * @param semicolon if <code>true</code> then prints a semicolon after the brace*/ void endBlockNewLine(boolean semicolon) { endBlock(semicolon, true); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). */ void endBlock() { endBlock(false, false); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). * @param semicolon if <code>true</code> then prints a semicolon after the brace * @param newline if <code>true</code> then additionally calls {@link #endLine()} */ void endBlock(boolean semicolon, boolean newline) { indentLevel--; beginNewLine(); out(semicolon ? "};" : "}"); if (newline) { endLine(); } } /** Prints source code location in the form "at [filename] ([location])" */ void location(Node node) { out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")"); } private String generateToString(final GenerateCallback callback) { final Writer oldWriter = out; out = new StringWriter(); callback.generateValue(); final String str = out.toString(); out = oldWriter; return str; } @Override public void visit(CompilationUnit that) { root = that; Module clm = that.getUnit().getPackage().getModule() .getLanguageModule(); if (!JsCompiler.compilingLanguageModule) { require(clm); setCLAlias(names.moduleAlias(clm)); } for (CompilerAnnotation ca: that.getCompilerAnnotations()) { ca.visit(this); } if (that.getImportList() != null) { that.getImportList().visit(this); } visitStatements(that.getDeclarations()); } public void visit(Import that) { ImportableScope scope = that.getImportMemberOrTypeList().getImportList().getImportedScope(); if (scope instanceof Package) { require(((Package) scope).getModule()); } } private void require(Module mod) { final String path = scriptPath(mod); final String modAlias = names.moduleAlias(mod); if (jsout.requires.put(path, modAlias) == null) { out("var ", modAlias, "=require('", path, "');"); endLine(); } } private String scriptPath(Module mod) { StringBuilder path = new StringBuilder(mod.getNameAsString().replace('.', '/')).append('/'); if (!mod.isDefault()) { path.append(mod.getVersion()).append('/'); } path.append(mod.getNameAsString()); if (!mod.isDefault()) { path.append('-').append(mod.getVersion()); } return path.toString(); } @Override public void visit(Parameter that) { out(names.name(that.getParameterModel())); } @Override public void visit(ParameterList that) { out("("); boolean first=true; boolean ptypes = false; //Check if this is the first parameter list if (that.getScope() instanceof Method && that.getModel().isFirst()) { ptypes = ((Method)that.getScope()).getTypeParameters() != null && !((Method)that.getScope()).getTypeParameters().isEmpty(); } for (Parameter param: that.getParameters()) { if (!first) out(","); out(names.name(param.getParameterModel())); first = false; } if (ptypes) { if (!first) out(","); out("$$$mptypes"); } out(")"); } private void visitStatements(List<? extends Statement> statements) { List<String> oldRetainedVars = retainedVars.reset(null); final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; for (int i=0; i<statements.size(); i++) { Statement s = statements.get(i); s.visit(this); beginNewLine(); retainedVars.emitRetainedVars(this); } retainedVars.reset(oldRetainedVars); currentStatements = prevStatements; } @Override public void visit(Body that) { visitStatements(that.getStatements()); } @Override public void visit(Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); } else { beginBlock(); initSelf(that); visitStatements(stmnts); endBlock(); } } private void initSelf(Block block) { initSelf(block.getScope()); } private void initSelf(Scope scope) { if ((prototypeOwner != null) && ((scope instanceof MethodOrValue) || (scope instanceof TypeDeclaration) || (scope instanceof Specification))) { out("var "); self(prototypeOwner); out("=this;"); endLine(); } } private void comment(Tree.Declaration that) { if (!opts.isComment()) return; endLine(); out("//", that.getNodeType(), " ", that.getDeclarationModel().getName()); location(that); endLine(); } private void var(Declaration d) { out("var ", names.name(d), "="); } private boolean share(Declaration d) { return share(d, true); } private boolean share(Declaration d, boolean excludeProtoMembers) { boolean shared = false; if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember()) && isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.name(d), "=", names.name(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(ClassDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) { //But warnings are ok for (Message err : that.getErrors()) { if (!(err instanceof AnalysisWarning)) { return; } } } Class d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; comment(that); Tree.ClassSpecifier ext = that.getClassSpecifier(); out(function, names.name(d), "("); //Generate each parameter because we need to append one at the end for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } TypeArgumentList targs = ext.getType().getTypeArgumentList(); if (targs != null && !targs.getTypes().isEmpty()) { out("$$targs$$,"); } self(d); out(")"); TypeDeclaration aliased = ext.getType().getDeclarationModel(); out("{return "); qualify(ext.getType(), aliased); out(names.name(aliased), "("); if (ext.getInvocationExpression().getPositionalArgumentList() != null) { ext.getInvocationExpression().getPositionalArgumentList().visit(this); if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) { out(","); } } else { out("/*PENDIENTE NAMED ARG CLASS DECL */"); } if (targs != null && !targs.getTypes().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( aliased.getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(that, invargs, this); } else { out("/*TARGS != TPARAMS!!!! WTF?????*/"); } out(","); } self(d); out(");}"); endLine(); out(names.name(d), ".$$="); qualify(ext, aliased); out(names.name(aliased), ".$$;"); endLine(); share(d); } private void addClassDeclarationToPrototype(TypeDeclaration outer, ClassDeclaration that) { comment(that); TypeDeclaration dec = that.getClassSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } @Override public void visit(InterfaceDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Interface d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; //It's pointless declaring interface aliases outside of classes/interfaces Scope scope = that.getScope(); if (scope instanceof InterfaceAlias) { scope = scope.getContainer(); if (!(scope instanceof ClassOrInterface)) return; } comment(that); var(d); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel() .getDeclaration(); qualify(that,dec); out(names.name(dec), ";"); endLine(); share(d); } private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, InterfaceDeclaration that) { comment(that); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } private void addInterfaceToPrototype(ClassOrInterface type, InterfaceDefinition interfaceDef) { interfaceDefinition(interfaceDef); Interface d = interfaceDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(InterfaceDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { interfaceDefinition(that); } } private void interfaceDefinition(InterfaceDefinition that) { Interface d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); final List<TypeParameterDeclaration> tparms = that.getTypeParameterList() == null ? null : that.getTypeParameterList().getTypeParameterDeclarations(); if (tparms != null && !tparms.isEmpty()) { out("$$targs$$,"); } self(d); out(")"); beginBlock(); //declareSelf(d); referenceOuter(d); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getInterfaceBody()); } callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); if (tparms != null && !tparms.isEmpty()) { out(clAlias, "set_type_args("); self(d); out(",$$targs$$)"); endLine(true); } that.getInterfaceBody().visit(this); //returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void addClassToPrototype(ClassOrInterface type, ClassDefinition classDef) { classDefinition(classDef); Class d = classDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(ClassDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { classDefinition(that); } } private void classDefinition(ClassDefinition that) { Class d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } boolean withTargs = that.getTypeParameterList() != null && !that.getTypeParameterList().getTypeParameterDeclarations().isEmpty(); if (withTargs) { out("$$targs$$,"); } self(d); out(")"); beginBlock(); //This takes care of top-level attributes defined before the class definition out("$init$", names.name(d), "();"); endLine(); declareSelf(d); if (withTargs) { out(clAlias, "set_type_args("); self(d); out(",$$targs$$);"); endLine(); } else { //Check if any of the satisfied types have type arguments if (that.getSatisfiedTypes() != null) { for(Tree.StaticType sat : that.getSatisfiedTypes().getTypes()) { boolean first = true; Map<TypeParameter,ProducedType> targs = sat.getTypeModel().getTypeArguments(); if (targs != null && !targs.isEmpty()) { if (first) { self(d); out(".$$targs$$="); TypeUtils.printTypeArguments(that, targs, this); endLine(true); } else { out("/*TODO: more type arguments*/"); endLine(); } } } } } referenceOuter(d); initParameters(that.getParameterList(), d, null); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(that.getExtendedType(), d, that, superDecs); callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); that.getClassBody().visit(this); returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void referenceOuter(TypeDeclaration d) { if (d.isClassOrInterfaceMember()) { self(d); out("."); out("$$outer"); //outerSelf(d); out("=this;"); endLine(); } } private void copySuperMembers(TypeDeclaration typeDecl, final List<Declaration> decs, ClassOrInterface d) { if (!opts.isOptimize()) { for (Declaration dec: decs) { if (!typeDecl.isMember(dec)) { continue; } String suffix = names.scopeSuffix(dec.getContainer()); if (dec instanceof Value && ((Value)dec).isTransient()) { superGetterRef(dec,d,suffix); if (((Value) dec).isVariable()) { superSetterRef(dec,d,suffix); } } else { superRef(dec,d,suffix); } } } } private void callSuperclass(ExtendedType extendedType, Class d, Node that, final List<Declaration> superDecs) { if (extendedType!=null) { PositionalArgumentList argList = extendedType.getInvocationExpression() .getPositionalArgumentList(); TypeDeclaration typeDecl = extendedType.getType().getDeclarationModel(); out(memberAccessBase(extendedType.getType(), typeDecl, false, qualifiedPath(that, typeDecl)), (opts.isOptimize() && (getSuperMemberScope(extendedType.getType()) != null)) ? ".call(this," : "("); invoker.generatePositionalArguments(argList, argList.getPositionalArguments(), false, false); if (argList.getPositionalArguments().size() > 0) { out(","); } //There may be defaulted args we must pass as undefined if (d.getExtendedTypeDeclaration().getParameterList().getParameters().size() > argList.getPositionalArguments().size()) { List<com.redhat.ceylon.compiler.typechecker.model.Parameter> superParams = d.getExtendedTypeDeclaration().getParameterList().getParameters(); for (int i = argList.getPositionalArguments().size(); i < superParams.size(); i++) { com.redhat.ceylon.compiler.typechecker.model.Parameter p = superParams.get(i); if (p.isSequenced()) { out(clAlias, "getEmpty(),"); } else { out("undefined,"); } } } //If the supertype has type arguments, add them to the call if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { extendedType.getType().getTypeArgumentList().getTypeModels(); TypeUtils.printTypeArguments(that, TypeUtils.matchTypeParametersWithArguments(typeDecl.getTypeParameters(), extendedType.getType().getTypeArgumentList().getTypeModels()), this); out(","); } self(d); out(");"); endLine(); copySuperMembers(typeDecl, superDecs, d); } } private void callInterfaces(SatisfiedTypes satisfiedTypes, ClassOrInterface d, Tree.StatementOrArgument that, final List<Declaration> superDecs) { if (satisfiedTypes!=null) { for (StaticType st: satisfiedTypes.getTypes()) { TypeDeclaration typeDecl = st.getTypeModel().getDeclaration(); if (typeDecl.isAlias()) { typeDecl = typeDecl.getExtendedTypeDeclaration(); } qualify(that, typeDecl); out(names.name((ClassOrInterface)typeDecl), "("); if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { self(d); out(".$$targs$$===undefined?$$targs$$:"); } TypeUtils.printTypeArguments(that, st.getTypeModel().getTypeArguments(), this); out(","); } self(d); out(");"); endLine(); //Set the reified types from interfaces Map<TypeParameter, ProducedType> reifs = st.getTypeModel().getTypeArguments(); if (reifs != null && !reifs.isEmpty()) { for (Map.Entry<TypeParameter, ProducedType> e : reifs.entrySet()) { if (e.getValue().getDeclaration() instanceof ClassOrInterface) { out(clAlias, "add_type_arg("); self(d); out(",'", e.getKey().getName(), "',"); TypeUtils.typeNameOrList(that, e.getValue(), this, true); out(");"); endLine(); } } } copySuperMembers(typeDecl, superDecs, d); } } } /** Generates a function to initialize the specified type. */ private void typeInitialization(final Tree.Declaration type) { ExtendedType extendedType = null; SatisfiedTypes satisfiedTypes = null; boolean isInterface = false; ClassOrInterface decl = null; if (type instanceof ClassDefinition) { ClassDefinition classDef = (ClassDefinition) type; extendedType = classDef.getExtendedType(); satisfiedTypes = classDef.getSatisfiedTypes(); decl = classDef.getDeclarationModel(); } else if (type instanceof InterfaceDefinition) { satisfiedTypes = ((InterfaceDefinition) type).getSatisfiedTypes(); isInterface = true; decl = ((InterfaceDefinition) type).getDeclarationModel(); } else if (type instanceof ObjectDefinition) { ObjectDefinition objectDef = (ObjectDefinition) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getDeclarationModel().getTypeDeclaration(); } final PrototypeInitCallback callback = new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { if (type instanceof ClassDefinition) { addToPrototype(((ClassDefinition)type).getDeclarationModel(), ((ClassDefinition)type).getClassBody().getStatements()); } else if (type instanceof InterfaceDefinition) { addToPrototype(((InterfaceDefinition)type).getDeclarationModel(), ((InterfaceDefinition)type).getInterfaceBody().getStatements()); } } }; typeInitialization(extendedType, satisfiedTypes, isInterface, decl, callback); } /** This is now the main method to generate the type initialization code. * @param extendedType The type that is being extended. * @param satisfiedTypes The types satisfied by the type being initialized. * @param isInterface Tells whether the type being initialized is an interface * @param d The declaration for the type being initialized * @param callback A callback to add something more to the type initializer in prototype style. */ private void typeInitialization(ExtendedType extendedType, SatisfiedTypes satisfiedTypes, boolean isInterface, final ClassOrInterface d, PrototypeInitCallback callback) { //Let's always use initTypeProto to avoid #113 String initFuncName = "initTypeProto"; out("function $init$", names.name(d), "()"); beginBlock(); out("if (", names.name(d), ".$$===undefined)"); beginBlock(); String qns = d.getQualifiedNameString(); if (JsCompiler.compilingLanguageModule && qns.indexOf("::") < 0) { //Language module files get compiled in default module //so they need to have this added to their qualified name qns = "ceylon.language::" + qns; } out(clAlias, initFuncName, "(", names.name(d), ",'", qns, "'"); if (extendedType != null) { String fname = typeFunctionName(extendedType.getType(), false); out(",", fname); } else if (!isInterface) { out(",", clAlias, "Basic"); } if (satisfiedTypes != null) { for (StaticType satType : satisfiedTypes.getTypes()) { TypeDeclaration tdec = satType.getTypeModel().getDeclaration(); if (tdec.isAlias()) { tdec = tdec.getExtendedTypeDeclaration(); } String fname = typeFunctionName(satType, true); //Actually it could be "if not in same module" if (!JsCompiler.compilingLanguageModule && declaredInCL(tdec)) { out(",", fname); } else { int idx = fname.lastIndexOf('.'); if (idx > 0) { fname = fname.substring(0, idx+1) + "$init$" + fname.substring(idx+1); } else { fname = "$init$" + fname; } out(",", fname, "()"); } } } out(");"); //Add ref to outer type if (d.isMember()) { StringBuilder containers = new StringBuilder(); Scope _d2 = d; while (_d2 instanceof ClassOrInterface) { if (containers.length() > 0) { containers.insert(0, '.'); } containers.insert(0, names.name((Declaration)_d2)); _d2 = _d2.getScope(); } endLine(); out(containers.toString(), "=", names.name(d), ";"); } //The class definition needs to be inside the init function if we want forwards decls to work in prototype style if (opts.isOptimize()) { endLine(); callback.addToPrototypeCallback(); } endBlockNewLine(); out("return ", names.name(d), ";"); endBlockNewLine(); //If it's nested, share the init function if (outerSelf(d)) { out(".$init$", names.name(d), "=$init$", names.name(d), ";"); endLine(); } out("$init$", names.name(d), "();"); endLine(); } private String typeFunctionName(StaticType type, boolean removeAlias) { TypeDeclaration d = type.getTypeModel().getDeclaration(); if (removeAlias && d.isAlias()) { d = d.getExtendedTypeDeclaration(); } boolean inProto = opts.isOptimize() && (type.getScope().getContainer() instanceof TypeDeclaration); return memberAccessBase(type, d, false, qualifiedPath(type, d, inProto)); } private void addToPrototype(ClassOrInterface d, List<Statement> statements) { if (opts.isOptimize() && !statements.isEmpty()) { final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; out("(function(", names.self(d), ")"); beginBlock(); for (Statement s: statements) { addToPrototype(d, s); } endBlock(); out(")(", names.name(d), ".$$.prototype);"); endLine(); currentStatements = prevStatements; } } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, Statement s) { ClassOrInterface oldPrototypeOwner = prototypeOwner; prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } else if (s instanceof MethodDeclaration) { methodDeclaration(d, (MethodDeclaration) s); } else if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } else if (s instanceof AttributeDeclaration) { addGetterAndSetterToPrototype(d, (AttributeDeclaration) s); } else if (s instanceof ClassDefinition) { addClassToPrototype(d, (ClassDefinition) s); } else if (s instanceof InterfaceDefinition) { addInterfaceToPrototype(d, (InterfaceDefinition) s); } else if (s instanceof ObjectDefinition) { addObjectToPrototype(d, (ObjectDefinition) s); } else if (s instanceof ClassDeclaration) { addClassDeclarationToPrototype(d, (ClassDeclaration) s); } else if (s instanceof InterfaceDeclaration) { addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s); } else if (s instanceof SpecifierStatement) { addSpecifierToPrototype(d, (SpecifierStatement) s); } prototypeOwner = oldPrototypeOwner; } private void declareSelf(ClassOrInterface d) { out("if ("); self(d); out("===undefined)"); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); /*out("var "); self(d); out("="); self(); out(";"); endLine();*/ } private void instantiateSelf(ClassOrInterface d) { out("var "); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); } private void returnSelf(ClassOrInterface d) { out("return "); self(d); out(";"); } private void addObjectToPrototype(ClassOrInterface type, ObjectDefinition objDef) { objectDefinition(objDef); Value d = objDef.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); out(names.self(type), ".", names.name(c), "=", names.name(c), ";"); endLine(); } @Override public void visit(ObjectDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Value d = that.getDeclarationModel(); if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) { objectDefinition(that); } else { Class c = (Class) d.getTypeDeclaration(); comment(that); outerSelf(d); out(".", names.privateName(d), "="); outerSelf(d); out(".", names.name(c), "();"); endLine(); } } private void objectDefinition(ObjectDefinition that) { comment(that); Value d = that.getDeclarationModel(); boolean addToPrototype = opts.isOptimize() && d.isClassOrInterfaceMember(); Class c = (Class) d.getTypeDeclaration(); out(function, names.name(c)); Map<TypeParameter, ProducedType> targs=new HashMap<TypeParameter, ProducedType>(); if (that.getSatisfiedTypes() != null) { for (StaticType st : that.getSatisfiedTypes().getTypes()) { Map<TypeParameter, ProducedType> stargs = st.getTypeModel().getTypeArguments(); if (stargs != null && !stargs.isEmpty()) { targs.putAll(stargs); } } } out(targs.isEmpty()?"()":"($$targs$$)"); beginBlock(); instantiateSelf(c); referenceOuter(c); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } if (!targs.isEmpty()) { self(c); out(".$$targs$$=$$targs$$;"); endLine(); } callSuperclass(that.getExtendedType(), c, that, superDecs); callInterfaces(that.getSatisfiedTypes(), c, that, superDecs); that.getClassBody().visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); typeInitialization(that); addToPrototype(c, that.getClassBody().getStatements()); if (!addToPrototype) { out("var ", names.name(d), "=", names.name(c), "("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, this); } out(");"); endLine(); } if (!defineAsProperty(d)) { out("var ", names.getter(d), "=function()"); beginBlock(); out("return "); if (addToPrototype) { out("this."); } out(names.name(d), ";"); endBlockNewLine(); if (addToPrototype || d.isShared()) { outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); } } else { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); if (addToPrototype) { out("this.", names.privateName(d)); } else { out(names.name(d)); } out(";},undefined,"); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } } private void superRef(Declaration d, ClassOrInterface sub, String parentSuffix) { //if (d.isActual()) { self(sub); out(".", names.name(d), parentSuffix, "="); self(sub); out(".", names.name(d), ";"); endLine(); //} } private void superGetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (defineAsProperty(d)) { out(clAlias, "copySuperAttr(", names.self(sub), ",'", names.name(d), "','", parentSuffix, "');"); } else { self(sub); out(".", names.getter(d), parentSuffix, "="); self(sub); out(".", names.getter(d), ";"); } endLine(); } private void superSetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (!defineAsProperty(d)) { self(sub); out(".", names.setter(d), parentSuffix, "="); self(sub); out(".", names.setter(d), ";"); endLine(); } } @Override public void visit(MethodDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; methodDeclaration(null, that); } private void methodDeclaration(TypeDeclaration outer, MethodDeclaration that) { Method m = that.getDeclarationModel(); if (that.getSpecifierExpression() != null) { // method(params) => expr if (outer == null) { // Not in a prototype definition. Null to do here if it's a // member in prototype style. if (opts.isOptimize() && m.isMember()) { return; } comment(that); initDefaultedParameters(that.getParameterLists().get(0), m); out("var "); } else { // prototype definition comment(that); initDefaultedParameters(that.getParameterLists().get(0), m); out(names.self(outer), "."); } out(names.name(m), "="); singleExprFunction(that.getParameterLists(), that.getSpecifierExpression().getExpression(), that.getScope()); endLine(true); if (outer != null) { out(names.self(outer), "."); } out(names.name(m), ".$$metamodel$$="); TypeUtils.encodeForRuntime(m, that.getAnnotationList(), this); endLine(true); share(m); } else if (outer == null) { // don't do the following in a prototype definition //Check for refinement of simple param declaration if (m == that.getScope()) { if (m.getContainer() instanceof Class && m.isClassOrInterfaceMember()) { //Declare the method just by pointing to the param function final String name = names.name(((Class)m.getContainer()).getParameter(m.getName())); if (name != null) { self((Class)m.getContainer()); out(".", names.name(m), "=", name, ";"); endLine(); } } else if (m.getContainer() instanceof Method) { //Declare the function just by forcing the name we used in the param list final String name = names.name(((Method)m.getContainer()).getParameter(m.getName())); if (names != null) { names.forceName(m, name); } } //Only the first paramlist can have defaults initDefaultedParameters(that.getParameterLists().get(0), m); } } } @Override public void visit(MethodDefinition that) { Method d = that.getDeclarationModel(); //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!((opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) || isNative(d))) { comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); methodDefinition(that); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } } private void methodDefinition(MethodDefinition that) { Method d = that.getDeclarationModel(); if (that.getParameterLists().size() == 1) { out(function, names.name(d)); ParameterList paramList = that.getParameterLists().get(0); paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, null, d); visitStatements(that.getBlock().getStatements()); endBlock(); } else { int count=0; for (ParameterList paramList : that.getParameterLists()) { if (count==0) { out(function, names.name(d)); } else { out("return function"); } paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, d.getTypeDeclaration(), d); count++; } visitStatements(that.getBlock().getStatements()); for (int i=0; i < count; i++) { endBlock(); } } if (!share(d)) { out(";"); } } /** Get the specifier expression for a Parameter, if one is available. */ private SpecifierOrInitializerExpression getDefaultExpression(Parameter param) { final SpecifierOrInitializerExpression expr; if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) { MethodDeclaration md = null; if (param instanceof ParameterDeclaration) { TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration(); if (td instanceof AttributeDeclaration) { expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression(); } else if (td instanceof MethodDeclaration) { md = (MethodDeclaration)td; expr = md.getSpecifierExpression(); } else { param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName()); expr = null; } } else { expr = ((InitializerParameter) param).getSpecifierExpression(); } } else { param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param); expr = null; } return expr; } /** Create special functions with the expressions for defaulted parameters in a parameter list. */ private void initDefaultedParameters(ParameterList params, Method container) { if (!container.isMember())return; for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); if (pd.isDefaulted()) { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { continue; } qualify(params, container); out(names.name(container), "$defs$", pd.getName(), "=function"); params.visit(this); out("{"); initSelf(container); out("return "); if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), null); } else { expr.visit(this); } out(";}"); endLine(true); } } } /** Initialize the sequenced, defaulted and captured parameters in a type declaration. */ private void initParameters(ParameterList params, TypeDeclaration typeDecl, Method m) { for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); final String paramName = names.name(pd); if (pd.isDefaulted() || pd.isSequenced()) { out("if(", paramName, "===undefined){", paramName, "="); if (pd.isDefaulted()) { if (m !=null && m.isMember()) { qualify(params, m); out(names.name(m), "$defs$", pd.getName(), "("); boolean firstParam=true; for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) { if (firstParam){firstParam=false;}else out(","); out(names.name(p)); } out(")"); } else { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { param.addUnexpectedError("Default expression missing for " + pd.getName()); out("null"); } else if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), m.getContainer()); } else { expr.visit(this); } } } else { out(clAlias, "getEmpty()"); } out(";}"); endLine(); } if ((typeDecl != null) && pd.getModel().isCaptured()) { self(typeDecl); out(".", paramName, "=", paramName, ";"); endLine(); } } } private void addMethodToPrototype(TypeDeclaration outer, MethodDefinition that) { Method d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); out(names.self(outer), ".", names.name(d), "="); methodDefinition(that); //Add reference to metamodel out(names.self(outer), ".", names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(";"); } @Override public void visit(AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return; comment(that); if (defineAsProperty(d)) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); } else { out("var ", names.getter(d), "=function()"); super.visit(that); if (!shareGetter(d)) { out(";"); } } } private void addGetterToPrototype(TypeDeclaration outer, AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); } private AttributeSetterDefinition associatedSetterDefinition( Value valueDecl) { final Setter setter = valueDecl.getSetter(); if ((setter != null) && (currentStatements != null)) { for (Statement stmt : currentStatements) { if (stmt instanceof AttributeSetterDefinition) { final AttributeSetterDefinition setterDef = (AttributeSetterDefinition) stmt; if (setterDef.getDeclarationModel() == setter) { return setterDef; } } } } return null; } /** Exports a getter function; useful in non-prototype style. */ private boolean shareGetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return; comment(that); out("var ", names.setter(d.getGetter()), "=function(", names.name(d.getParameter()), ")"); if (that.getSpecifierExpression() == null) { that.getBlock().visit(this); } else { out("{return "); that.getSpecifierExpression().visit(this); out(";}"); } if (!shareSetter(d)) { out(";"); } } private boolean isCaptured(Declaration d) { if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures if (d.isShared() || d.isCaptured() ) { return true; } else { OuterVisitor ov = new OuterVisitor(d); ov.visit(root); return ov.found; } } else { return false; } } private boolean shareSetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.setter(d), "=", names.setter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeDeclaration that) { Value d = that.getDeclarationModel(); //Check if the attribute corresponds to a class parameter //This is because of the new initializer syntax String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } if (!d.isFormal()) { comment(that); final boolean isLate = d.isLate(); SpecifierOrInitializerExpression specInitExpr = that.getSpecifierOrInitializerExpression(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { if ((specInitExpr != null && !(specInitExpr instanceof LazySpecifierExpression)) || isLate) { outerSelf(d); out(".", names.privateName(d), "="); if (isLate) { out("undefined"); } else { super.visit(that); } endLine(true); } else if (classParam != null) { outerSelf(d); out(".", names.privateName(d), "=", classParam); endLine(true); } //TODO generate for => expr when no classParam is available } else if (specInitExpr instanceof LazySpecifierExpression) { final boolean property = defineAsProperty(d); if (property) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); } else { out("var ", names.getter(d), "=function(){return "); } int boxType = boxStart(specInitExpr.getExpression().getTerm()); specInitExpr.getExpression().visit(this); if (boxType == 4) out("/*TODO: callable targs 1*/"); boxUnboxEnd(boxType); out(";}"); if (property) { boolean hasSetter = false; if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { hasSetter = true; out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } if (!hasSetter) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } else { endLine(true); shareGetter(d); } } else { if ((specInitExpr != null) || (classParam != null) || !d.isMember() || d.isVariable() || isLate) { generateAttributeGetter(that, d, specInitExpr, classParam); } if ((d.isVariable() || isLate) && !defineAsProperty(d)) { final String varName = names.name(d); String paramVarName = names.createTempVariable(d.getName()); out("var ", names.setter(d), "=function(", paramVarName, "){"); if (isLate) { generateImmutableAttributeReassignmentCheck(varName, names.name(d)); } out("return ", varName, "=", paramVarName, ";};"); endLine(); shareSetter(d); } } } } private void generateAttributeGetter(AnyAttribute attributeNode, MethodOrValue decl, SpecifierOrInitializerExpression expr, String param) { final String varName = names.name(decl); out("var ", varName); if (expr != null) { out("="); int boxType = boxStart(expr.getExpression().getTerm()); if (dynblock > 0 && TypeUtils.isUnknown(expr.getExpression().getTypeModel()) && !TypeUtils.isUnknown(decl.getType())) { TypeUtils.generateDynamicCheck(expr.getExpression(), decl.getType(), this); } else { expr.visit(this); } if (boxType == 4) { //Pass Callable argument types out(","); if (decl instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)decl).getParameterLists().get(0), GenerateJsVisitor.this); } else { //Type of value must be Callable //And the Args Type Parameters is a Tuple types.encodeTupleAsParameterListForRuntime(decl.getType(), this); } out(","); TypeUtils.printTypeArguments(expr, expr.getExpression().getTypeModel().getTypeArguments(), this); } boxUnboxEnd(boxType); } else if (param != null) { out("=", param); } endLine(true); if (decl instanceof Method) { if (decl.isClassOrInterfaceMember() && isCaptured(decl)) { beginNewLine(); outerSelf(decl); out(".", names.name(decl), "=", names.name(decl), ";"); endLine(); } } else { if (isCaptured(decl)) { final boolean isLate = decl.isLate(); if (defineAsProperty(decl)) { out(clAlias, "defineAttr("); outerSelf(decl); out(",'", varName, "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck(varName, names.name(decl)); } out("return ", varName, ";}"); if (decl.isVariable() || isLate) { final String par = names.createTempVariable(decl.getName()); out(",function(", par, "){"); if (isLate && !decl.isVariable()) { generateImmutableAttributeReassignmentCheck(varName, names.name(decl)); } out("return ", varName, "=", par, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(decl, attributeNode == null ? null : attributeNode.getAnnotationList(), this); out(");"); endLine(); } else { out("var ", names.getter(decl),"=function(){return ", varName, ";};"); endLine(); shareGetter(decl); } } else { directAccess.add(decl); } } } void generateUnitializedAttributeReadCheck(String privname, String pubname) { //TODO we can later optimize this, to replace this getter with the plain one //once the value has been defined out("if (", privname, "===undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to read unitialized attribute «", pubname, "»'));"); } void generateImmutableAttributeReassignmentCheck(String privname, String pubname) { out("if(", privname, "!==undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to reassign immutable attribute «", pubname, "»'));"); } private void addGetterAndSetterToPrototype(TypeDeclaration outer, AttributeDeclaration that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||d.isToplevel()) return; if (!d.isFormal()) { comment(that); String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } final boolean isLate = d.isLate(); if ((that.getSpecifierOrInitializerExpression() != null) || d.isVariable() || classParam != null || isLate) { if (that.getSpecifierOrInitializerExpression() instanceof LazySpecifierExpression) { // attribute is defined by a lazy expression ("=>" syntax) out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); beginBlock(); initSelf(that.getScope()); out("return "); Expression expr = that.getSpecifierOrInitializerExpression().getExpression(); int boxType = boxStart(expr.getTerm()); expr.visit(this); endLine(true); if (boxType == 4) out("/*TODO: callable targs 3*/"); boxUnboxEnd(boxType); endBlock(); boolean hasSetter = false; if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { hasSetter = true; out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{"); initSelf(that.getScope()); out("return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } if (!hasSetter) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(")"); endLine(true); } else { final String privname = names.privateName(d); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck("this."+privname, names.name(d)); } out("return this.", privname, ";}"); if (d.isVariable() || isLate) { final String param = names.createTempVariable(d.getName()); out(",function(", param, "){"); if (isLate && !d.isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(d)); } out("return this.", privname, "=", param, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } } } } @Override public void visit(CharLiteral that) { out(clAlias, "Character("); out(String.valueOf(that.getText().codePointAt(1))); out(")"); } /** Escapes a StringLiteral (needs to be quoted). */ String escapeStringLiteral(String s) { StringBuilder text = new StringBuilder(s); //Escape special chars for (int i=0; i < text.length();i++) { switch(text.charAt(i)) { case 8:text.replace(i, i+1, "\\b"); i++; break; case 9:text.replace(i, i+1, "\\t"); i++; break; case 10:text.replace(i, i+1, "\\n"); i++; break; case 12:text.replace(i, i+1, "\\f"); i++; break; case 13:text.replace(i, i+1, "\\r"); i++; break; case 34:text.replace(i, i+1, "\\\""); i++; break; case 39:text.replace(i, i+1, "\\'"); i++; break; case 92:text.replace(i, i+1, "\\\\"); i++; break; case 0x2028:text.replace(i, i+1, "\\u2028"); i++; break; case 0x2029:text.replace(i, i+1, "\\u2029"); i++; break; } } return text.toString(); } @Override public void visit(StringLiteral that) { final int slen = that.getText().codePointCount(0, that.getText().length()); if (JsCompiler.compilingLanguageModule) { out("String$(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } else { out(clAlias, "String(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } } @Override public void visit(StringTemplate that) { List<StringLiteral> literals = that.getStringLiterals(); List<Expression> exprs = that.getExpressions(); out(clAlias, "StringBuilder().appendAll(["); boolean first = true; for (int i = 0; i < literals.size(); i++) { StringLiteral literal = literals.get(i); if (!literal.getText().isEmpty()) { if (!first) { out(","); } first = false; literal.visit(this); } if (i < exprs.size()) { if (!first) { out(","); } first = false; exprs.get(i).visit(this); out(".string"); } } out("]).string"); } @Override public void visit(FloatLiteral that) { out(clAlias, "Float(", that.getText(), ")"); } @Override public void visit(NaturalLiteral that) { char prefix = that.getText().charAt(0); if (prefix == '$' || prefix == '#') { int radix= prefix == '$' ? 2 : 16; try { out("(", new java.math.BigInteger(that.getText().substring(1), radix).toString(), ")"); } catch (NumberFormatException ex) { that.addError("Invalid numeric literal " + that.getText()); } } else { out("(", that.getText(), ")"); } } @Override public void visit(This that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Super that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Outer that) { boolean outer = false; if (opts.isOptimize()) { Scope scope = that.getScope(); while ((scope != null) && !(scope instanceof TypeDeclaration)) { scope = scope.getContainer(); } if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) { self((TypeDeclaration) scope); out("."); outer = true; } } if (outer) { out("$$outer"); } else { self(that.getTypeModel().getDeclaration()); } } @Override public void visit(BaseMemberExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) { //Don't even bother processing a node with errors return; } Declaration decl = that.getDeclaration(); if (decl != null) { String name = decl.getName(); String pkgName = decl.getUnit().getPackage().getQualifiedNameString(); // map Ceylon true/false/null directly to JS true/false/null if ("ceylon.language".equals(pkgName)) { if ("true".equals(name) || "false".equals(name) || "null".equals(name)) { out(name); return; } } } String exp = memberAccess(that, null); if (decl == null && isInDynamicBlock()) { out("(typeof ", exp, "==='undefined'||", exp, "===null?", clAlias, "throwexc('Undefined or null reference: ", exp, "'):", exp, ")"); } else { out(exp); } } private boolean accessDirectly(Declaration d) { return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter(); } private boolean accessThroughGetter(Declaration d) { return (d instanceof MethodOrValue) && !(d instanceof Method) && !defineAsProperty(d); } private boolean defineAsProperty(Declaration d) { // for now, only define member attributes as properties, not toplevel attributes return d.isMember() && (d instanceof MethodOrValue) && !(d instanceof Method); } /** Returns true if the top-level declaration for the term is annotated "nativejs" */ private static boolean isNative(Term t) { if (t instanceof MemberOrTypeExpression) { return isNative(((MemberOrTypeExpression)t).getDeclaration()); } return false; } /** Returns true if the declaration is annotated "nativejs" */ private static boolean isNative(Declaration d) { return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d); } private static Declaration getToplevel(Declaration d) { while (d != null && !d.isToplevel()) { Scope s = d.getContainer(); // Skip any non-declaration elements while (s != null && !(s instanceof Declaration)) { s = s.getContainer(); } d = (Declaration) s; } return d; } private static boolean hasAnnotationByName(Declaration d, String name){ if (d != null) { for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){ if(annotation.getName().equals(name)) return true; } } return false; } private void generateSafeOp(QualifiedMemberOrTypeExpression that) { boolean isMethod = that.getDeclaration() instanceof Method; String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); super.visit(that); out(","); if (isMethod) { out(clAlias, "JsCallable(", lhsVar, ","); } out(lhsVar, "!==null?", memberAccess(that, lhsVar), ":null)"); if (isMethod) { out(")"); } } @Override public void visit(final QualifiedMemberExpression that) { //Big TODO: make sure the member is actually // refined by the current class! if (that.getMemberOperator() instanceof SafeMemberOp) { generateSafeOp(that); } else if (that.getMemberOperator() instanceof SpreadOp) { generateSpread(that); } else if (that.getDeclaration() instanceof Method && that.getSignature() == null) { //TODO right now this causes that all method invocations are done this way //we need to filter somehow to only use this pattern when the result is supposed to be a callable //looks like checking for signature is a good way (not THE way though; named arg calls don't have signature) generateCallable(that, null); } else if (that.getStaticMethodReference()) { out("function($O$) {return "); if (that.getDeclaration() instanceof Method) { out(clAlias, "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ");}"); } else { out("$O$.", names.name(that.getDeclaration()), ";}"); } } else { final String lhs = generateToString(new GenerateCallback() { @Override public void generateValue() { GenerateJsVisitor.super.visit(that); } }); out(memberAccess(that, lhs)); } } /** SpreadOp cannot be a simple function call because we need to reference the object methods directly, so it's a function */ private void generateSpread(QualifiedMemberOrTypeExpression that) { //Determine if it's a method or attribute boolean isMethod = that.getDeclaration() instanceof Method; //Define a function out("(function()"); beginBlock(); if (opts.isComment()) { out("//SpreadOp at ", that.getLocation()); endLine(); } //Declare an array to store the values/references String tmplist = names.createTempVariable("lst"); out("var ", tmplist, "=[];"); endLine(); //Get an iterator String iter = names.createTempVariable("it"); out("var ", iter, "="); super.visit(that); out(".iterator();"); endLine(); //Iterate String elem = names.createTempVariable("elem"); out("var ", elem, ";"); endLine(); out("while ((", elem, "=", iter, ".next())!==", clAlias, "getFinished())"); beginBlock(); //Add value or reference to the array out(tmplist, ".push("); if (isMethod) { out("{o:", elem, ", f:", memberAccess(that, elem), "}"); } else { out(memberAccess(that, elem)); } out(");"); endBlockNewLine(); //Gather arguments to pass to the callable //Return the array of values or a Callable with the arguments out("return ", clAlias); if (isMethod) { out("JsCallableList(", tmplist, ");"); } else { out("ArraySequence(", tmplist, ");"); } endBlock(); out("())"); } private void generateCallable(QualifiedMemberOrTypeExpression that, String name) { String primaryVar = createRetainedTempVar("opt"); out("(", primaryVar, "="); that.getPrimary().visit(this); out(",", clAlias, "JsCallable(", primaryVar, ",", primaryVar, "!==null?", (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name), ":null))"); } /** * Checks if the given node is a MemberOrTypeExpression or QualifiedType which * represents an access to a supertype member and returns the scope of that * member or null. */ Scope getSuperMemberScope(Node node) { Scope scope = null; if (node instanceof QualifiedMemberOrTypeExpression) { // Check for "super.member" QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node; final Term primary = eliminateParensAndWidening(qmte.getPrimary()); if (primary instanceof Super) { scope = qmte.getDeclaration().getContainer(); } } else if (node instanceof QualifiedType) { // Check for super.Membertype QualifiedType qtype = (QualifiedType) node; if (qtype.getOuterType() instanceof SuperType) { scope = qtype.getDeclarationModel().getContainer(); } } return scope; } private String memberAccessBase(Node node, Declaration decl, boolean setter, String lhs) { final StringBuilder sb = new StringBuilder(); if (lhs != null) { if (lhs.length() > 0) { sb.append(lhs).append("."); } } else if (node instanceof BaseMemberOrTypeExpression) { BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node; String path = qualifiedPath(node, bmte.getDeclaration()); if (path.length() > 0) { sb.append(path); sb.append("."); } } Scope scope = getSuperMemberScope(node); if (opts.isOptimize() && (scope != null)) { sb.append("getT$all()['"); sb.append(scope.getQualifiedNameString()); sb.append("']"); if (defineAsProperty(decl)) { return clAlias + (setter ? "attrSetter(" : "attrGetter(") + sb.toString() + ",'" + names.name(decl) + "')"; } sb.append(".$$.prototype."); } final String member = (accessThroughGetter(decl) && !accessDirectly(decl)) ? (setter ? names.setter(decl) : names.getter(decl)) : names.name(decl); sb.append(member); if (!opts.isOptimize() && (scope != null)) { sb.append(names.scopeSuffix(scope)); } //When compiling the language module we need to modify certain base type names String rval = sb.toString(); if (TypeUtils.isReservedTypename(rval)) { rval = sb.append("$").toString(); } return rval; } /** * Returns a string representing a read access to a member, as represented by * the given expression. If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private String memberAccess(StaticMemberOrTypeExpression expr, String lhs) { Declaration decl = expr.getDeclaration(); String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { return ((lhs != null) && (lhs.length() > 0)) ? (lhs + "." + plainName) : plainName; } boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without getter return memberAccessBase(expr, decl, false, lhs); } // access through getter return memberAccessBase(expr, decl, false, lhs) + (protoCall ? ".call(this)" : "()"); } /** * Generates a write access to a member, as represented by the given expression. * The given callback is responsible for generating the assigned value. * If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private void generateMemberAccess(StaticMemberOrTypeExpression expr, GenerateCallback callback, String lhs) { Declaration decl = expr.getDeclaration(); boolean paren = false; String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { if ((lhs != null) && (lhs.length() > 0)) { out(lhs, "."); } out(plainName, "="); } else { boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without setter out(memberAccessBase(expr, decl, true, lhs), "="); } else { // access through setter out(memberAccessBase(expr, decl, true, lhs), protoCall ? ".call(this," : "("); paren = true; } } callback.generateValue(); if (paren) { out(")"); } } private void generateMemberAccess(final StaticMemberOrTypeExpression expr, final String strValue, final String lhs) { generateMemberAccess(expr, new GenerateCallback() { @Override public void generateValue() { out(strValue); } }, lhs); } @Override public void visit(BaseTypeExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Declaration d = that.getDeclaration(); if (d == null && isInDynamicBlock()) { //It's a native js type but will be wrapped in dyntype() call String id = that.getIdentifier().getText(); out("(typeof ", id, "==='undefined'?", clAlias, "throwexc('Undefined type ", id, "'):", id, ")"); } else { qualify(that, d); out(names.name(d)); } } @Override public void visit(QualifiedTypeExpression that) { if (that.getMemberOperator() instanceof SafeMemberOp) { generateCallable(that, names.name(that.getDeclaration())); } else { super.visit(that); out(".", names.name(that.getDeclaration())); } } public void visit(Dynamic that) { //this is value{xxx} invoker.nativeObject(that.getNamedArgumentList()); } @Override public void visit(InvocationExpression that) { invoker.generateInvocation(that); } @Override public void visit(PositionalArgumentList that) { invoker.generatePositionalArguments(that, that.getPositionalArguments(), false, false); } /** Box a term, visit it, unbox it. */ private void box(Term term) { final int t = boxStart(term); term.visit(this); if (t == 4) out("/*TODO: callable targs 4*/"); boxUnboxEnd(t); } // Make sure fromTerm is compatible with toTerm by boxing it when necessary private int boxStart(Term fromTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = false; ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, Term toTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toTerm); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toDecl); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } int boxUnboxStart(boolean fromNative, ProducedType fromType, boolean toNative) { // Box the value final String fromTypeName = TypeUtils.isUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName(); if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) { if (fromNative) { // conversion from native value to Ceylon value if (fromTypeName.equals("ceylon.language::String")) { if (JsCompiler.compilingLanguageModule) { out("String$("); } else { out(clAlias, "String("); } } else if (fromTypeName.equals("ceylon.language::Integer")) { out("("); } else if (fromTypeName.equals("ceylon.language::Float")) { out(clAlias, "Float("); } else if (fromTypeName.equals("ceylon.language::Boolean")) { out("("); } else if (fromTypeName.equals("ceylon.language::Character")) { out(clAlias, "Character("); } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 0; } return 1; } else if ("ceylon.language::String".equals(fromTypeName) || "ceylon.language::Float".equals(fromTypeName)) { // conversion from Ceylon String or Float to native value return 2; } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 3; } } return 0; } void boxUnboxEnd(int boxType) { switch (boxType) { case 1: out(")"); break; case 2: out(".valueOf()"); break; case 4: out(")"); break; default: //nothing } } @Override public void visit(ObjectArgument that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; final Class c = (Class)that.getDeclarationModel().getTypeDeclaration(); out("(function()"); beginBlock(); out("//ObjectArgument ", that.getIdentifier().getText()); location(that); endLine(); out(function, names.name(c), "()"); beginBlock(); instantiateSelf(c); referenceOuter(c); ExtendedType xt = that.getExtendedType(); final ClassBody body = that.getClassBody(); SatisfiedTypes sts = that.getSatisfiedTypes(); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(xt, c, that, superDecs); callInterfaces(sts, c, that, superDecs); body.visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); //Add reference to metamodel out(names.name(c), ".$$metamodel$$="); TypeUtils.encodeForRuntime(c, null/*TODO check if an object arg can have annotations */, this); endLine(true); typeInitialization(xt, sts, false, c, new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { addToPrototype(c, body.getStatements()); } }); out("return ", names.name(c), "(new ", names.name(c), ".$$);"); endBlock(); out("())"); } @Override public void visit(AttributeArgument that) { out("(function()"); beginBlock(); out("//AttributeArgument ", that.getParameter().getName()); location(that); endLine(); Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("return "); specExpr.getExpression().visit(this); out(";"); } else if (block != null) { visitStatements(block.getStatements()); } endBlock(); out("())"); } @Override public void visit(SequencedArgument that) { List<PositionalArgument> positionalArguments = that.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; if (!spread) { out("["); } boolean first=true; for (PositionalArgument arg: positionalArguments) { if (!first) out(","); if (arg instanceof Tree.ListedArgument) { ((Tree.ListedArgument) arg).getExpression().visit(this); } else if(arg instanceof Tree.SpreadArgument) ((Tree.SpreadArgument) arg).getExpression().visit(this); else // comprehension arg.visit(this); first = false; } if (!spread) { out("]"); } } @Override public void visit(SequenceEnumeration that) { SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); int lim = positionalArguments.size()-1; boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int count=0; ProducedType chainedType = null; if (lim>0 || !spread) { out("["); } for (PositionalArgument expr : positionalArguments) { if (count==lim && spread) { if (lim > 0) { ProducedType seqType = TypeUtils.findSupertype(types.iterable, that.getTypeModel()); closeSequenceWithReifiedType(that, seqType.getTypeArguments()); out(".chain("); chainedType = TypeUtils.findSupertype(types.iterable, expr.getTypeModel()); } count--; } else { if (count > 0) { out(","); } } if (dynblock > 0 && expr instanceof ListedArgument && TypeUtils.isUnknown(expr.getTypeModel())) { TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), types.anything.getType(), this); } else { expr.visit(this); } count++; } if (chainedType == null) { if (!spread) { closeSequenceWithReifiedType(that, that.getTypeModel().getTypeArguments()); } } else { out(","); TypeUtils.printTypeArguments(that, chainedType.getTypeArguments(), this); out(")"); } } } @Override public void visit(Comprehension that) { new ComprehensionGenerator(this, names, directAccess).generateComprehension(that); } @Override public void visit(final SpecifierStatement that) { // A lazy specifier expression in a class/interface should go into the // prototype in prototype style, so don't generate them here. if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression) && (that.getScope().getContainer() instanceof TypeDeclaration))) { specifierStatement(null, that); } } private void specifierStatement(final TypeDeclaration outer, final SpecifierStatement specStmt) { if (specStmt.getBaseMemberExpression() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) specStmt.getBaseMemberExpression(); Declaration bmeDecl = bme.getDeclaration(); if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) { // attr => expr; final boolean property = defineAsProperty(bmeDecl); if (property) { out(clAlias, "defineAttr(", qualifiedPath(specStmt, bmeDecl), ",'", names.name(bmeDecl), "',function()"); } else { if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out ("var "); } out(names.getter(bmeDecl), "=function()"); } beginBlock(); if (outer != null) { initSelf(specStmt.getScope()); } out ("return "); specStmt.getSpecifierExpression().visit(this); out(";"); endBlock(); if (property) { out(",undefined,"); TypeUtils.encodeForRuntime(bmeDecl, null/*TODO shared actual*/, this); out(")"); } endLine(true); directAccess.remove(bmeDecl); } else if (outer != null) { // "attr = expr;" in a prototype definition if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) { out("delete ", names.self(outer), ".", names.name(bmeDecl)); endLine(true); } } else if (bmeDecl instanceof MethodOrValue) { // "attr = expr;" in an initializer or method final MethodOrValue moval = (MethodOrValue)bmeDecl; if (moval.isVariable()) { // simple assignment to a variable attribute generateMemberAccess(bme, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(specStmt.getSpecifierExpression().getExpression().getTerm(), moval); if (dynblock > 0 && !TypeUtils.isUnknown(moval.getType()) && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), moval.getType(), GenerateJsVisitor.this); } else { specStmt.getSpecifierExpression().getExpression().visit(GenerateJsVisitor.this); } if (boxType == 4) { out(","); if (moval instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this); out(","); } else { //TODO extract parameters from Value out("[/*VALUE Callable params", moval.getClass().getName(), "*/],"); } TypeUtils.printTypeArguments(specStmt.getSpecifierExpression().getExpression(), specStmt.getSpecifierExpression().getExpression().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); } boxUnboxEnd(boxType); } }, null); out(";"); } else if (moval.isMember()) { - //Solution to Issue 150 probably here - // Specifier for a member attribute. This actually defines the - // member (e.g. in shortcut refinement syntax the attribute - // declaration itself can be omitted), so generate the attribute. - generateAttributeGetter(null, moval, - specStmt.getSpecifierExpression(), null); + if (moval instanceof Method) { + //same as fat arrow + qualify(specStmt, bmeDecl); + out(names.name(moval), "=function ", names.name(moval), "("); + //Build the parameter list, we'll use it several times + final StringBuilder paramNames = new StringBuilder(); + for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : ((Method) moval).getParameterLists().get(0).getParameters()) { + if (paramNames.length() > 0) paramNames.append(","); + paramNames.append(names.name(p)); + } + out(paramNames.toString()); + out("){"); + initSelf(moval.getContainer()); + for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : ((Method) moval).getParameterLists().get(0).getParameters()) { + if (p.isDefaulted()) { + out("if (", names.name(p), "===undefined)", names.name(p),"="); + qualify(specStmt, moval); + out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")"); + endLine(true); + } + } + out("return "); + specStmt.getSpecifierExpression().visit(this); + out("(", paramNames.toString(), ");}"); + endLine(true); + } else { + // Specifier for a member attribute. This actually defines the + // member (e.g. in shortcut refinement syntax the attribute + // declaration itself can be omitted), so generate the attribute. + generateAttributeGetter(null, moval, + specStmt.getSpecifierExpression(), null); + } } else { // Specifier for some other attribute, or for a method. if (opts.isOptimize() || (bmeDecl.isMember() && (bmeDecl instanceof Method))) { qualify(specStmt, bmeDecl); } out(names.name(bmeDecl), "="); if (dynblock > 0 && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), bme.getTypeModel(), this); } else { specStmt.getSpecifierExpression().visit(this); } out(";"); } } } else if ((specStmt.getBaseMemberExpression() instanceof ParameterizedExpression) && (specStmt.getSpecifierExpression() != null)) { final ParameterizedExpression paramExpr = (ParameterizedExpression) specStmt.getBaseMemberExpression(); if (paramExpr.getPrimary() instanceof BaseMemberExpression) { // func(params) => expr; BaseMemberExpression bme = (BaseMemberExpression) paramExpr.getPrimary(); Declaration bmeDecl = bme.getDeclaration(); if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out("var "); } out(names.name(bmeDecl), "="); singleExprFunction(paramExpr.getParameterLists(), specStmt.getSpecifierExpression().getExpression(), bmeDecl instanceof Scope ? (Scope)bmeDecl : null); out(";"); } } } private void addSpecifierToPrototype(final TypeDeclaration outer, final SpecifierStatement specStmt) { specifierStatement(outer, specStmt); } @Override public void visit(final AssignOp that) { String returnValue = null; StaticMemberOrTypeExpression lhsExpr = null; if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { that.getLeftTerm().visit(this); out("="); int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); return; } out("("); if (that.getLeftTerm() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm(); lhsExpr = bme; Declaration bmeDecl = bme.getDeclaration(); boolean simpleSetter = hasSimpleGetterSetter(bmeDecl); if (!simpleSetter) { returnValue = memberAccess(bme, null); } } else if (that.getLeftTerm() instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm(); lhsExpr = qme; boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration()); String lhsVar = null; if (!simpleSetter) { lhsVar = createRetainedTempVar(); out(lhsVar, "="); super.visit(qme); out(",", lhsVar, "."); returnValue = memberAccess(qme, lhsVar); } else { super.visit(qme); out("."); } } generateMemberAccess(lhsExpr, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(GenerateJsVisitor.this); if (boxType == 4) out("/*TODO: callable targs 7*/"); boxUnboxEnd(boxType); } }, null); if (returnValue != null) { out(",", returnValue); } out(")"); } /** Outputs the module name for the specified declaration. Returns true if something was output. */ boolean qualify(Node that, Declaration d) { String path = qualifiedPath(that, d); if (path.length() > 0) { out(path, "."); } return path.length() > 0; } private String qualifiedPath(Node that, Declaration d) { return qualifiedPath(that, d, false); } private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); if (dynblock > 0 && TypeUtils.isUnknown(that.getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(that.getExpression(), that.getExpression().getTypeModel(), this); endLine(true); return; } super.visit(that); } @Override public void visit(AnnotationList that) {} void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { final String lhs = names.createTempVariable(); out("function(){var ", lhs, "="); termgen.left(); out(";return "); termgen.right(); out(".scale(", lhs, ");}()"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } if (resources != null) { for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){", clAlias, "addSuppressedException(", resourceVar, "$swallow,", catchVarName, ");}"); } } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null) { out("finally"); encloseBlockInFunction(that.getFinallyClause().getBlock()); } } @Override public void visit(Throw that) { out("throw "); if (that.getExpression() != null) { that.getExpression().visit(this); } else { out(clAlias, "Exception()"); } out(";"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase){ boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); out(expvar, "==="); //TODO equality? /*out(".equals(");*/ exp.visit(this); //out(")==="); clAlias(); out("getTrue()"); first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() == null) { if (dynblock > 0 && expr.getTypeModel().getDeclaration() instanceof UnknownType) { out("else throw ", clAlias, "Exception('Ceylon switch over unknown type does not cover all cases')"); } } else { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), scope instanceof TypeDeclaration ? (TypeDeclaration)scope : null, null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null, scope instanceof Method ? (Method)scope : null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); Scope parent = scope == null ? null : scope.getContainer(); initParameters(paramList, parent instanceof TypeDeclaration ? (TypeDeclaration)parent : null, scope instanceof Method ? (Method)scope:null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape custom = escapeStringLiteral(sb.toString()); out(") { throw ", clAlias, "AssertionException('", custom, "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$model({Type:"); TypeUtils.typeNameOrList(that, that.getType().getTypeModel(), this, true); out("})"); } @Override public void visit(MemberLiteral that) { com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget(); if (ref == null) { that.addUnexpectedError("Member literal with no valid target"); } else { //TODO We can skip the typeLiteral call and directly return a Function or Method Declaration d = ref.getDeclaration(); out(clAlias, "typeLiteral$model({Type:{t:"); if (that.getType() == null) { qualify(that, d); } else { qualify(that, that.getType().getTypeModel().getDeclaration()); out(names.name(that.getType().getTypeModel().getDeclaration())); out(".$$.prototype."); } //Como le hago con setters? if (d instanceof Value) { out("$prop$"); } out(names.name(d)); if (ref.getTypeArguments() != null && !ref.getTypeArguments().isEmpty()) { out(",a:"); TypeUtils.printTypeArguments(that, ref.getTypeArguments(), this); } out("}})"); } } }
true
false
null
null
diff --git a/Calendar/src/calendar/DrawCalendar.java b/Calendar/src/calendar/DrawCalendar.java index 6213edd..ad82f21 100644 --- a/Calendar/src/calendar/DrawCalendar.java +++ b/Calendar/src/calendar/DrawCalendar.java @@ -1,1694 +1,1695 @@ package calendar; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; /** * @author Kelly Hutchison <kmh5754 at psu.edu> */ public class DrawCalendar extends JPanel implements ActionListener { //<editor-fold defaultstate="collapsed" desc="Variables"> private GridBagLayout layout; // layout of applet private GridBagConstraints constraints; // helper for the layout private JButton viewEvents; private final int space = 3; // Spacing between buttons private JLabel month; // JLabel to display month and year private JPanel pan1; // JPanel label to contain month JLabel private JPanel pan2; private JPanel pan3; private JPanel pan4; private JPanel weekdayPanel; private JButton alarmButton; private JButton reminderButton; private JButton eventButton; private String currentMonth; private String currentYear; private Calendar cal; private GregorianCalendar checkYear; private int curYear; private int curMonth; private int curDay; private Integer dayClicked; private int dayOfWeek; private Font f; private JLabel sunday; private JLabel monday; private JLabel tuesday; private JLabel wednesday; private JLabel thursday; private JLabel friday; private JLabel saturday; private JLabel monthLabel; private JLabel dateLabel; private JLabel yearLabel; private JTextArea listOfEvents; private Boolean isLeapYear; private Alarm alarm; private Event event; private Memo memo; private JFrame popUp = null; private JFrame schedule; private JButton next; private JButton back; private ArrayList<MyButton> bttns = new ArrayList<>(); private String driver = "org.apache.derby.jdbc.EmbeddedDriver"; private Connection dbConn = null; private Statement stmt; private ResultSet results; private String sql; private Boolean changeLabels = false; //private Boolean future=true; //</editor-fold> // Default Constructor public DrawCalendar() throws InstantiationException, ClassNotFoundException, IllegalAccessException, SQLException, IOException { // set up graphics window super(); // this can be omitted setBackground(Color.WHITE); layout = new GridBagLayout(); // set up layout setLayout(layout); constraints = new GridBagConstraints(); cal = Calendar.getInstance(); checkYear = new GregorianCalendar(); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); curMonth = cal.get(Calendar.MONTH) + 1; // zero based curYear = cal.get(Calendar.YEAR); curDay = cal.get(Calendar.DATE); isLeapYear = checkYear.isLeapYear(curYear); // Default dayClicked to -1 dayClicked = -1; // set currentYear string to the current year currentYear = Integer.toString(curYear); // Set current month // set the currentMonth string to the current month //<editor-fold defaultstate="collapsed" desc="Sets currentMonth"> if (curMonth == 1) { currentMonth = "JANUARY"; } if (curMonth == 2) { currentMonth = "FEBRUARY"; } if (curMonth == 3) { currentMonth = "MARCH"; } if (curMonth == 4) { currentMonth = "APRIL"; } if (curMonth == 5) { currentMonth = "MAY"; } if (curMonth == 6) { currentMonth = "JUNE"; } if (curMonth == 7) { currentMonth = "JULY"; } if (curMonth == 8) { currentMonth = "AUGUST"; } if (curMonth == 9) { currentMonth = "SEPTEMBER"; } if (curMonth == 10) { currentMonth = "OCTOBER"; } if (curMonth == 11) { currentMonth = "NOVEMBER"; } if (curMonth == 12) { currentMonth = "DECEMBER"; } if (curMonth == 1) { currentMonth = "JANUARY"; } if (curMonth == 2) { currentMonth = "FEBRUARY"; } if (curMonth == 3) { currentMonth = "MARCH"; } if (curMonth == 4) { currentMonth = "APRIL"; } if (curMonth == 5) { currentMonth = "MAY"; } if (curMonth == 6) { currentMonth = "JUNE"; } if (curMonth == 7) { currentMonth = "JULY"; } if (curMonth == 8) { currentMonth = "AUGUST"; } if (curMonth == 9) { currentMonth = "SEPTEMBER"; } if (curMonth == 10) { currentMonth = "OCTOBER"; } if (curMonth == 11) { currentMonth = "NOVEMBER"; } if (curMonth == 12) { currentMonth = "DECEMBER"; } //</editor-fold> DBManager.connect(); dbConn = DBManager.getConnection(); stmt = dbConn.createStatement(); try { // test to see if we need to run the initial sql script DatabaseMetaData dbMeta = dbConn.getMetaData(); String[] tableTypes = {"TABLE"}; results = dbMeta.getTables(null, null, "%", tableTypes); if (!results.next()) { // no table found, we need to execute the initial sql statements // first read the sql script InputStream is = DrawCalendar.class.getResourceAsStream("initSQL.sql"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; line = br.readLine(); while (line != null) { sb.append(line); if (line.contains(";")) { sql = sb.toString(); sb = new StringBuilder(); // executeQuery cannot process ; so remove it from sql sql = sql.substring(0, sql.indexOf(';')); // run sql here if (sql.toUpperCase().contains("SELECT")) { // SELECT statement stmt.executeQuery(sql); } else { // All ohter type of statements stmt.execute(sql); } } line = br.readLine(); } } results.close(); stmt.close(); } // don't have much about exception handling yet catch (SQLException e) { // could not start Derby engine e.printStackTrace(); } for (int i = 0; i < 31; i++) { MyButton mb = new MyButton(i); bttns.add(mb); } f = new Font("Arial BLACK", Font.PLAIN, 20); for (int i = 1; i <= 31; i++) { - bttns.get(i - 1).setFont(f); - bttns.get(i - 1).setBackground(Color.gray); - bttns.get(i - 1).setOpaque(false); - bttns.get(i - 1).setBorderPainted(true); - } - f = new Font("Arial BLACK", Font.BOLD, 20); - for (int i = 0; i < 31; i++) { - bttns.get(curDay - 1).setFont(f); - bttns.get(curDay - 1).setBackground(Color.CYAN); - bttns.get(curDay - 1).setOpaque(true); - bttns.get(curDay - 1).setBorderPainted(true); + if (i == curDay) { + f = new Font("Arial BLACK", Font.BOLD, 20); + bttns.get(i - 1).setFont(f); + bttns.get(i - 1).setBackground(Color.CYAN); + bttns.get(i - 1).setOpaque(true); + bttns.get(i - 1).setBorderPainted(true); + } else { + f = new Font("Arial BLACK", Font.PLAIN, 20); + bttns.get(i - 1).setFont(f); + bttns.get(i - 1).setBackground(Color.gray); + bttns.get(i - 1).setOpaque(true); + bttns.get(i - 1).setBorderPainted(true); + } } int counter = 0; try { stmt = dbConn.createStatement(); results = stmt.executeQuery("select count(*) from " + "calendar where datetime ='" + curMonth + bttns.get(0).getDay() + curYear + "'"); while (results.next()) { counter = results.getInt(1); } if (counter == 0) { for (int j = 0; j < 31; j++) { stmt.execute("insert into calendar (datetime,memo) values ('" + curMonth + bttns.get(j).getDay() + curYear + "', '')"); } } stmt.close(); results.close(); } catch (SQLException sqlex) { sqlex.printStackTrace(); } pan1 = new JPanel(); // Instantiate JPanel f = new Font("Arial BLACK", Font.BOLD, 30); // Change font size on Font variable f month = new JLabel(" " + currentMonth + " " + currentYear + " "); // Assign JLabel a value month.setFont(f); // Assign JLabel to font f back = new JButton("Previous Month"); next = new JButton("Next Month"); back.addActionListener(this); next.addActionListener(this); pan1.setLayout(new GridBagLayout()); // set layout of JPanel to Grid Bag Layout GridBagConstraints gbc = new GridBagConstraints(); // set constraints gbc.insets = new Insets(5, 50, 5, 50); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(pan1, gbc); pan1.add(back, gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(pan1, gbc); pan1.add(month, gbc);//, gbc); // add month variable to panel gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(pan1, gbc); pan1.add(next, gbc); pan1.setBackground(Color.LIGHT_GRAY); // set background of panel to a color f = new Font("Arial BLACK", Font.BOLD, 20); // Assign new font for days weekdayPanel = new JPanel(); // instantiate panel // Create Labels sunday = new JLabel("SUN"); monday = new JLabel("MON"); tuesday = new JLabel("TUE"); wednesday = new JLabel("WED"); thursday = new JLabel("THU"); friday = new JLabel("FRI"); saturday = new JLabel("SAT"); // Center JLabels sunday.setHorizontalAlignment(JLabel.CENTER); monday.setHorizontalAlignment(JLabel.CENTER); tuesday.setHorizontalAlignment(JLabel.CENTER); wednesday.setHorizontalAlignment(JLabel.CENTER); thursday.setHorizontalAlignment(JLabel.CENTER); friday.setHorizontalAlignment(JLabel.CENTER); saturday.setHorizontalAlignment(JLabel.CENTER); // Set font of JLabels sunday.setFont(f); monday.setFont(f); tuesday.setFont(f); wednesday.setFont(f); thursday.setFont(f); friday.setFont(f); saturday.setFont(f); gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.insets = new Insets(space, space, space, space); // Set spacing between buttons weekdayPanel.setLayout(new GridBagLayout()); weekdayPanel.setBackground(Color.CYAN); //weekdayPanel.add(sunday); // Find first day of week of month //<editor-fold defaultstate="collapsed" desc="Sets first day of the week of month"> cal.set(Calendar.DAY_OF_MONTH, 1); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); } if (dayOfWeek == 2) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); } if (dayOfWeek == 3) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); } if (dayOfWeek == 4) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); } if (dayOfWeek == 5) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); } if (dayOfWeek == 6) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); } if (dayOfWeek == 7) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); } cal.set(Calendar.DAY_OF_MONTH, curDay); //</editor-fold> gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 7; gbc.gridheight = 1; layout.setConstraints(weekdayPanel, gbc); add(weekdayPanel); f = new Font("Arial", Font.PLAIN, 20); // Assign new font for dates // set default fonts of day numbers for (int i = 0; i < 31; i++) { bttns.get(i).setFont(f); } // Set un-focusable // So when application runs, none of buttons are initially selected for (int i = 0; i < 31; i++) { bttns.get(i).setFocusable(false); } f = new Font("Arial BLACK", Font.BOLD, 20); // Set current date block to background color // Set current day block to be bold for (int i = 1; i <= 31; i++) { if (curDay == i && curMonth == cal.get(Calendar.MONTH)) { bttns.get(i - 1).setFont(f); bttns.get(i - 1).setBackground(Color.CYAN); bttns.get(i - 1).setOpaque(true); bttns.get(i - 1).setBorderPainted(true); } } // Set constraint weights constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets(space, space, space, space); // Set spacing between buttons // Set constraints for each button and JPanel on calendar constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 7; constraints.gridheight = 1; layout.setConstraints(pan1, constraints); add(pan1); // add panel for (int i = 0; i < 7; i++) { constraints.gridx = i; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(i), constraints); bttns.get(i).addActionListener(this); add(bttns.get(i)); } for (int i = 0; i < 7; i++) { constraints.gridx = i; constraints.gridy = 3; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(i + 7), constraints); bttns.get(i + 7).addActionListener(this); add(bttns.get(i + 7)); } for (int i = 0; i < 7; i++) { constraints.gridx = i; constraints.gridy = 4; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(i + 14), constraints); bttns.get(i + 14).addActionListener(this); add(bttns.get(i + 14)); } for (int i = 0; i < 7; i++) { constraints.gridx = i; constraints.gridy = 5; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(i + 21), constraints); bttns.get(i + 21).addActionListener(this); add(bttns.get(i + 21)); } if ((isLeapYear) || (!isLeapYear && curMonth != 2)) { constraints.gridx = 0; // define constraints for button constraints.gridy = 6; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(28), constraints); bttns.get(28).addActionListener(this); add(bttns.get(28)); } if (curMonth != 2) { constraints.gridx = 1; // define constraints for button constraints.gridy = 6; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(29), constraints); bttns.get(29).addActionListener(this); add(bttns.get(29)); // add button } if (curMonth == 1 || curMonth == 3 || curMonth == 5 || curMonth == 7 || curMonth == 8 || curMonth == 10 || curMonth == 12) { constraints.gridx = 2; // define constraints for button constraints.gridy = 6; constraints.gridwidth = 1; constraints.gridheight = 1; layout.setConstraints(bttns.get(30), constraints); bttns.get(30).addActionListener(this); add(bttns.get(30)); // add button } } @Override public void actionPerformed(ActionEvent e) { // Process "click" on drawIt, position combo box // Determine which button is clicked for (int i = 0; i < 31; i++) { if (e.getSource() == bttns.get(i)) { popUpMenu(); dayClicked = i + 1; } } if (e.getSource() == next) { if (curMonth < 12) { ++curMonth; } else { curMonth = 1; curYear += 1; } + changeLabels=true; repaint(); - } if (e.getSource() == back) { if (curMonth > 2) { --curMonth; } else { curMonth = 12; --curYear; } + changeLabels=true; repaint(); } // alarm button if (e.getSource() == alarmButton) { try { alarm = new Alarm(bttns.get(dayClicked - 1), curMonth, curYear); repaint(); } catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) { Logger.getLogger(DrawCalendar.class.getName()).log(Level.SEVERE, null, ex); } } // Event button if (e.getSource() == eventButton) { event = new Event(bttns.get(dayClicked - 1), curMonth, curYear); repaint(); } // memo button if (e.getSource() == reminderButton) { // memo = new Memo(monthArray, dayClicked - 1, indexDay1++); repaint(); } if (e.getSource() == viewEvents) { try { viewDate(); } catch (SQLException ex) { Logger.getLogger(DrawCalendar.class.getName()).log(Level.SEVERE, null, ex); } } repaint(); } public void popUpMenu() { String currentTitle = dayClicked.toString(); if (popUp != null) { popUp.dispose(); } popUp = new JFrame("Select: " + currentTitle); Font newFont = new Font("Arial BLACK", Font.BOLD, 15); // Change font size on Font variable f alarmButton = new JButton("Add Alarm"); // create new alarmButton button reminderButton = new JButton("Add Memo"); // create new reminderButton button eventButton = new JButton("Add Event"); // create new eventButton button viewEvents = new JButton("View Today's Schedule"); // add action listeners alarmButton.addActionListener(this); reminderButton.addActionListener(this); eventButton.addActionListener(this); viewEvents.addActionListener(this); // Set button fonts alarmButton.setFont(newFont); reminderButton.setFont(newFont); eventButton.setFont(newFont); viewEvents.setFont(newFont); pan2 = new JPanel(); pan2.setLayout(new GridBagLayout()); // set layout of JPanel to Grid Bag Layout pan2.add(alarmButton, new GridBagConstraints()); // add month variable to panel pan2.add(eventButton, new GridBagConstraints()); // add month variable to panel pan2.add(reminderButton, new GridBagConstraints()); // add month variable to panel pan2.add(viewEvents, new GridBagConstraints()); popUp.setLocation(230, 300); // set location of pop up menu on the screen popUp.setBackground(Color.YELLOW); popUp.setLayout(new FlowLayout()); popUp.setSize(800, 100); // Set default size of JFrame Calendar popUp.setResizable(false); // Allow JFrame to be resized popUp.add(pan2); // add calender GUI to JFrame popUp.setVisible(true); // Set visibility of JFrame } @Override public void paint(Graphics g) { super.paint(g); //g.setColor(Color.GREEN); f = new Font("Arial BLACK", Font.ITALIC, 20); int count = 0; // Change color of day number when something is stored on that day // Day 1 // Change Month Label switch (curMonth) { case 1: { month.setText("January " + curYear); break; } case 2: { month.setText("February " + curYear); break; } case 3: { month.setText("March " + curYear); break; } case 4: { month.setText("April " + curYear); break; } case 5: { month.setText("May " + curYear); break; } case 6: { month.setText("June " + curYear); break; } case 7: { month.setText("July " + curYear); break; } case 8: { month.setText("August " + curYear); break; } case 9: { month.setText("September " + curYear); break; } case 10: { month.setText("October " + curYear); break; } case 11: { month.setText("November " + curYear); break; } case 12: { month.setText("December " + curYear); break; } } // If not current month and year, unhighlight "today" btn if (curMonth != cal.get(Calendar.MONTH) || curYear != cal.get(Calendar.YEAR)) { f = new Font("Arial BLACK", Font.PLAIN, 20); // Set current date block to background color // Set current day block to be bold - for (int i = 1; i <= 31; i++) { bttns.get(curDay - 1).setFont(f); bttns.get(curDay - 1).setBackground(Color.gray); bttns.get(curDay - 1).setOpaque(false); bttns.get(curDay - 1).setBorderPainted(false); - } } // If go back to current month and year, highlight "today" btn if (curMonth == cal.get(Calendar.MONTH) && curYear == cal.get(Calendar.YEAR)) { f = new Font("Arial BLACK", Font.BOLD, 20); // Set current date block to background color // Set current day block to be bold for (int i = 1; i <= 31; i++) { bttns.get(curDay - 1).setFont(f); bttns.get(curDay - 1).setBackground(Color.CYAN); bttns.get(curDay - 1).setOpaque(true); bttns.get(curDay - 1).setBorderPainted(true); } } // Find first day of week of month //<editor-fold defaultstate="collapsed" desc="Sets first day of the week of month"> if (changeLabels) { GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.insets = new Insets(space, space, space, space); // Set spacing between buttons weekdayPanel.setLayout(new GridBagLayout()); weekdayPanel.setBackground(Color.CYAN); cal.set(Calendar.MONTH, curMonth); cal.set(Calendar.DAY_OF_MONTH, 1); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); } if (dayOfWeek == 2) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); } if (dayOfWeek == 3) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); } if (dayOfWeek == 4) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); } if (dayOfWeek == 5) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); } if (dayOfWeek == 6) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); } if (dayOfWeek == 7) { // Add week day names gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(saturday, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(sunday, gbc); gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(monday, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(tuesday, gbc); gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(wednesday, gbc); gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(thursday, gbc); gbc.gridx = 6; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; layout.setConstraints(weekdayPanel, gbc); add(friday, gbc); } cal.set(Calendar.DAY_OF_MONTH, curDay); changeLabels = false; } //</editor-fold> for (int i = 0; i < 31; i++) { if (dayClicked - 1 == i) { try { dbConn = DBManager.getConnection(); stmt = dbConn.createStatement(); results = stmt.executeQuery("select count(*) from " + "event where datetime ='" + curMonth + bttns.get(i).getDay() + curYear + "'"); while (results.next()) { count = results.getInt(1); } if (count == 0) { results = stmt.executeQuery("select count(*) from " + "calendar where memo != ''"); while (results.next()) { count = results.getInt(1); } } if (count == 0) { results = stmt.executeQuery("select count(*) from " + "alarm where datetime ='" + curMonth + bttns.get(i).getDay() + curYear + "'"); while (results.next()) { count = results.getInt(1); } } stmt.close(); results.close(); } catch (SQLException ex) { System.out.println("paint"); ex.printStackTrace(); } if (count != 0) { bttns.get(i).setFont(f); bttns.get(i).setForeground(Color.BLUE); } } } } public void viewDate() throws SQLException { schedule = new JFrame("Schedule"); // monthLabel, dateLabel, yearLabel, listOfEvents //<editor-fold defaultstate="collapsed" desc="Set current month label"> if (curMonth == 1) { monthLabel = new JLabel("January "); } if (curMonth == 2) { monthLabel = new JLabel("February "); } if (curMonth == 3) { monthLabel = new JLabel("March "); } if (curMonth == 4) { monthLabel = new JLabel("April "); } if (curMonth == 5) { monthLabel = new JLabel("May "); } if (curMonth == 6) { monthLabel = new JLabel("June "); } if (curMonth == 7) { monthLabel = new JLabel("July "); } if (curMonth == 8) { monthLabel = new JLabel("August "); } if (curMonth == 9) { monthLabel = new JLabel("September "); } if (curMonth == 10) { monthLabel = new JLabel("October "); } if (curMonth == 11) { monthLabel = new JLabel("November "); } if (curMonth == 12) { monthLabel = new JLabel("December "); } //</editor-fold> dateLabel = new JLabel(dayClicked + ", "); yearLabel = new JLabel(curYear + " "); listOfEvents = new JTextArea(); for (int i = 0; i < 31; i++) { if (dayClicked == i) { try { stmt = dbConn.createStatement(); results = stmt.executeQuery("select memo from " + "calendar where datetime = '" + curMonth + bttns.get(i - 1).getDay() + curYear + "'"); listOfEvents.append("Memos: "); while (results.next()) { listOfEvents.append(results.getString("memo") + '\n'); } listOfEvents.append("Events: " + '\n'); results = stmt.executeQuery(" " + "select name, starttime, endtime from " + "event where datetime = '" + curMonth + bttns.get(i - 1).getDay() + curYear + "'"); while (results.next()) { listOfEvents.append(" " + results.getString("name") + ' ' + results.getString("starttime") + ' ' + results.getString("endtime") + '\n'); } listOfEvents.append("Alarms: " + '\n'); results = stmt.executeQuery("select name, starttime from " + "alarm where datetime = '" + curMonth + bttns.get(i - 1).getDay() + curYear + "'"); while (results.next()) { listOfEvents.append(" " + results.getString("name") + ' ' + results.getString("starttime") + '\n'); } stmt.close(); results.close(); } catch (SQLException ex) { System.out.println("View Events"); ex.printStackTrace(); } } } f = new Font("Arial BLACK", Font.BOLD, 24); // Change font size on Font variable f monthLabel.setFont(f); dateLabel.setFont(f); yearLabel.setFont(f); f = new Font("Arial BLACK", Font.PLAIN, 15); // Change font size on Font variable f listOfEvents.setFont(f); listOfEvents.setEditable(false); pan3 = new JPanel(); pan4 = new JPanel(); pan3.add(monthLabel); pan3.add(dateLabel); pan3.add(yearLabel); pan4.add(listOfEvents); schedule.setLocation(430, 300); // set location of pop up menu on the screen schedule.setBackground(Color.GREEN); schedule.setLayout(new BorderLayout()); schedule.setSize(500, 300); // Set default size of JFrame Calendar schedule.setResizable(true); // Allow JFrame to be resized schedule.add(pan3, BorderLayout.NORTH); // add calender GUI to JFrame schedule.add(pan4, BorderLayout.CENTER); schedule.setVisible(true); // Set visibility of JFrame } public static void main(String[] args) throws InstantiationException, ClassNotFoundException, IllegalAccessException, SQLException, IOException { DrawCalendar myCalendar = new DrawCalendar(); // window for drawing JFrame application = new JFrame("Calendar"); // the program itself application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set frame to exit when it is closed application.setSize(800, 800); // Set default size of JFrame Calendar application.setLocation(230, 0); application.setResizable(true); // Allow JFrame to be resized application.add(myCalendar); // add calender GUI to JFrame application.setVisible(true); // Set visibility of JFrame } } \ No newline at end of file
false
false
null
null
diff --git a/src/main/java/io/cloudsoft/opengamma/server/OpenGammaServerImpl.java b/src/main/java/io/cloudsoft/opengamma/server/OpenGammaServerImpl.java index b1cb4a3..d16072b 100644 --- a/src/main/java/io/cloudsoft/opengamma/server/OpenGammaServerImpl.java +++ b/src/main/java/io/cloudsoft/opengamma/server/OpenGammaServerImpl.java @@ -1,170 +1,172 @@ package io.cloudsoft.opengamma.server; import java.util.Map; import org.jclouds.compute.domain.OsFamily; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.enricher.RollingTimeWindowMeanEnricher; import brooklyn.enricher.TimeWeightedDeltaEnricher; import brooklyn.entity.basic.SoftwareProcessImpl; import brooklyn.entity.database.postgresql.PostgreSqlNode; import brooklyn.entity.java.JavaAppUtils; import brooklyn.entity.java.UsesJmx; import brooklyn.entity.messaging.activemq.ActiveMQBroker; import brooklyn.entity.webapp.WebAppServiceConstants; import brooklyn.entity.webapp.WebAppServiceMethods; import brooklyn.event.feed.http.HttpFeed; import brooklyn.event.feed.http.HttpPollConfig; import brooklyn.event.feed.http.HttpValueFunctions; import brooklyn.event.feed.jmx.JmxAttributePollConfig; import brooklyn.event.feed.jmx.JmxFeed; import brooklyn.event.feed.jmx.JmxHelper; import brooklyn.location.MachineProvisioningLocation; import brooklyn.location.access.BrooklynAccessUtils; import brooklyn.location.jclouds.templates.PortableTemplateBuilder; import brooklyn.util.exceptions.Exceptions; import brooklyn.util.time.Duration; import brooklyn.util.time.Time; import com.google.common.base.Functions; import com.google.common.net.HostAndPort; public class OpenGammaServerImpl extends SoftwareProcessImpl implements OpenGammaServer, UsesJmx { private static final Logger log = LoggerFactory.getLogger(OpenGammaServerImpl.class); - + + private volatile JmxFeed jmxFeed; + private JmxFeed jmxMxBeanFeed; private HttpFeed httpFeed; private ActiveMQBroker broker; private PostgreSqlNode database; @Override public void init() { broker = getConfig(BROKER); database = getConfig(DATABASE); } @SuppressWarnings("rawtypes") @Override public Class getDriverInterface() { return OpenGammaServerDriver.class; } @SuppressWarnings({ "unchecked", "rawtypes" }) protected Map<String,Object> obtainProvisioningFlags(MachineProvisioningLocation location) { Map flags = super.obtainProvisioningFlags(location); flags.put("templateBuilder", new PortableTemplateBuilder() // need a beefy machine .os64Bit(true) .minRam(8192) // either should work... however ubuntu not available in GCE // .osFamily(OsFamily.UBUNTU).osVersionMatches("12.04") // .osFamily(OsFamily.CENTOS) ); return flags; } @Override protected void connectSensors() { super.connectSensors(); HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(HTTP_PORT)); log.debug("HostAndPort seen during connectSensors " + hp); String rootUrl = "http://"+hp.getHostText()+":"+hp.getPort()+"/"; setAttribute(ROOT_URL, rootUrl); httpFeed = HttpFeed.builder() .entity(this) .period(1000) .baseUri(rootUrl) .poll(new HttpPollConfig<Boolean>(SERVICE_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .build(); } @Override protected void postStart() { super.postStart(); - - String ogJettyStatsMbeanName = "com.opengamma.jetty:service=HttpConnector"; - - JmxFeed.builder().entity(this).period(Duration.ONE_SECOND) + String ogJettyStatsMbeanName = "com.opengamma.jetty:service=HttpConnector"; + jmxFeed = JmxFeed.builder().entity(this).period(Duration.ONE_SECOND) .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP) .objectName(ogJettyStatsMbeanName) .attributeName("Running") .setOnFailureOrException(false)) .pollAttribute(new JmxAttributePollConfig<Integer>(REQUEST_COUNT) .objectName(ogJettyStatsMbeanName) .attributeName("Requests")) // these two from jetty not available from opengamma bean: // jettyStatsHandler.attribute("requestTimeTotal").subscribe(TOTAL_PROCESSING_TIME); // jettyStatsHandler.attribute("responsesBytesTotal").subscribe(BYTES_SENT); .pollAttribute(new JmxAttributePollConfig<Integer>(TOTAL_PROCESSING_TIME) .objectName(ogJettyStatsMbeanName) .attributeName("ConnectionsDurationTotal")) .pollAttribute(new JmxAttributePollConfig<Integer>(MAX_PROCESSING_TIME) .objectName(ogJettyStatsMbeanName) .attributeName("ConnectionsDurationMax")) .pollAttribute(new JmxAttributePollConfig<Integer>(VIEW_PROCESSES_COUNT) .objectName("com.opengamma:type=ViewProcessor,name=ViewProcessor main") .attributeName("NumberOfViewProcesses")) .pollAttribute(new JmxAttributePollConfig<Integer>(CALC_JOB_COUNT) .objectName("com.opengamma:type=CalculationNodes,name=local") .attributeName("TotalJobCount")) .pollAttribute(new JmxAttributePollConfig<Integer>(CALC_NODE_COUNT) .objectName("com.opengamma:type=CalculationNodes,name=local") .attributeName("TotalNodeCount")) .build(); - - JavaAppUtils.connectMXBeanSensors(this); + + jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this); JavaAppUtils.connectJavaAppServerPolicies(this); WebAppServiceMethods.connectWebAppServerPolicies(this); addEnricher(new TimeWeightedDeltaEnricher<Integer>(this, WebAppServiceConstants.TOTAL_PROCESSING_TIME, PROCESSING_TIME_PER_SECOND_LAST, 1)); addEnricher(new RollingTimeWindowMeanEnricher<Double>(this, PROCESSING_TIME_PER_SECOND_LAST, PROCESSING_TIME_PER_SECOND_IN_WINDOW, WebAppServiceMethods.DEFAULT_WINDOW_DURATION)); // turn stats on, allowing a few sleep-then-retries in case the server isn't yet up for (int i=3; i<=0; i--) { try { // many of the stats only are available once we explicitly turn them on Object jettyStatsOnResult = new JmxHelper(this).operation(JmxHelper.createObjectName("com.opengamma.jetty:service=HttpConnector"), "setStatsOn", true); log.debug("result of setStatsOn for "+this+": "+jettyStatsOnResult); break; } catch (Exception e) { Exceptions.propagateIfFatal(e); if (i==0) throw Exceptions.propagate(e); Time.sleep(Duration.TEN_SECONDS); } } } @Override protected void disconnectSensors() { super.disconnectSensors(); if (httpFeed != null) httpFeed.stop(); + if (jmxFeed != null) jmxFeed.stop(); + if (jmxMxBeanFeed != null) jmxMxBeanFeed.stop(); } /** HTTP port number for Jetty web service. */ public Integer getHttpPort() { return getAttribute(HTTP_PORT); } /** HTTPS port number for Jetty web service. */ public Integer getHttpsPort() { return getAttribute(HTTPS_PORT); } /** {@inheritDoc} */ @Override public ActiveMQBroker getBroker() { return broker; } /** {@inheritDoc} */ @Override public PostgreSqlNode getDatabase() { return database; } }
false
false
null
null
diff --git a/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java b/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java index edd4f6abb..3125082e3 100644 --- a/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java +++ b/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java @@ -1,546 +1,541 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.messaging.jms; import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.jboss.messaging.core.message.impl.MessageImpl; -import org.jboss.messaging.jms.client.JBossMessage; /** * * A ScheduledDeliveryTest * * @author <a href="mailto:[email protected]">Tim Fox</a> * @version <tt>$Revision$</tt> * * $Id$ * */ public class ScheduledDeliveryTest extends JMSTestCase { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- // Attributes ---------------------------------------------------- // Constructors -------------------------------------------------- public ScheduledDeliveryTest(String name) { super(name); } // Public -------------------------------------------------------- - public void test1() - { - } - public void testScheduledDeliveryTX() throws Exception { scheduledDelivery(true); } public void testScheduledDeliveryNoTX() throws Exception { scheduledDelivery(false); } public void testScheduledDeliveryWithRestart() throws Exception { Connection conn = null; try { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue1 = (Queue) getInitialContext().lookup("/queue/testQueue"); MessageProducer prod = sess.createProducer(queue1); //Send one scheduled long now = System.currentTimeMillis(); TextMessage tm1 = sess.createTextMessage("testScheduled1"); tm1.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 29000); prod.send(tm1); //First send some non scheduled messages TextMessage tm2 = sess.createTextMessage("testScheduled2"); prod.send(tm2); TextMessage tm3 = sess.createTextMessage("testScheduled3"); prod.send(tm3); TextMessage tm4 = sess.createTextMessage("testScheduled4"); prod.send(tm4); //Now send some more scheduled messages //These numbers have to be large with Hudson, since restart can take some time TextMessage tm5 = sess.createTextMessage("testScheduled5"); tm5.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 27000); prod.send(tm5); TextMessage tm6 = sess.createTextMessage("testScheduled6"); tm6.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 26000); prod.send(tm6); TextMessage tm7 = sess.createTextMessage("testScheduled7"); tm7.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 25000); prod.send(tm7); TextMessage tm8 = sess.createTextMessage("testScheduled8"); tm8.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 28000); prod.send(tm8); //And one scheduled with a -ve number TextMessage tm9 = sess.createTextMessage("testScheduled9"); tm8.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), -3); prod.send(tm9); //Now stop the server and restart it conn.close(); stop(); start(); // Messaging server restart implies new ConnectionFactory lookup deployAndLookupAdministeredObjects(); conn = cf.createConnection(); conn.start(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sess.createConsumer(queue1); forceGC(); //First the non scheduled messages should be received TextMessage rm1 = (TextMessage)cons.receive(250); assertNotNull(rm1); assertEquals(tm2.getText(), rm1.getText()); TextMessage rm2 = (TextMessage)cons.receive(250); assertNotNull(rm2); assertEquals(tm3.getText(), rm2.getText()); TextMessage rm3 = (TextMessage)cons.receive(250); assertNotNull(rm3); assertEquals(tm4.getText(), rm3.getText()); //Now the one with a scheduled with a -ve number TextMessage rm5 = (TextMessage)cons.receive(250); assertNotNull(rm5); assertEquals(tm9.getText(), rm5.getText()); //Now the scheduled TextMessage rm6 = (TextMessage)cons.receive(25500); assertNotNull(rm6); assertEquals(tm7.getText(), rm6.getText()); long now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 3000); TextMessage rm7 = (TextMessage)cons.receive(26500); assertNotNull(rm7); assertEquals(tm6.getText(), rm7.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 4000); TextMessage rm8 = (TextMessage)cons.receive(27500); assertNotNull(rm8); assertEquals(tm5.getText(), rm8.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 5000); TextMessage rm9 = (TextMessage)cons.receive(28500); assertNotNull(rm9); assertEquals(tm8.getText(), rm9.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 6000); TextMessage rm10 = (TextMessage)cons.receive(29500); assertNotNull(rm10); assertEquals(tm1.getText(), rm10.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 7000); } finally { removeAllMessages("testQueue", true); if (conn != null) { conn.close(); } } } public void testDelayedRedelivery() throws Exception { String qName = "testDelayedRedeliveryDefaultQ"; try { long delay = 3000; addAddressSettings(qName, delay); createQueue(qName); queue1 = (Queue) getInitialContext().lookup("/queue/" + qName); this.delayedRedeliveryDefaultOnClose(delay); this.delayedRedeliveryDefaultOnRollback(delay); } finally { removeAddressSettings(qName); this.destroyQueue(qName); } } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- private void delayedRedeliveryDefaultOnClose(long delay) throws Exception { Connection conn = null; try { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); final int NUM_MESSAGES = 5; forceGC(); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); } Session sess2 = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer cons = sess2.createConsumer(queue1); conn.start(); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage)cons.receive(500); assertNotNull(tm); assertEquals("message" + i, tm.getText()); } //Now close the session //This should cancel back to the queue with a delayed redelivery long now = System.currentTimeMillis(); sess2.close(); Session sess3 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons2 = sess3.createConsumer(queue1); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage)cons2.receive(delay + 1000); assertNotNull(tm); long time = System.currentTimeMillis(); assertTrue(time - now >= delay); //Hudson can introduce a large degree of indeterminism assertTrue((time - now) + ">" + (delay + 1000), time - now < delay + 1000); } } finally { if (conn != null) { conn.close(); } } } private void delayedRedeliveryDefaultOnRollback(long delay) throws Exception { Connection conn = null; try { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); final int NUM_MESSAGES = 5; for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sess.createTextMessage("message" + i); prod.send(tm); } Session sess2 = conn.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer cons = sess2.createConsumer(queue1); conn.start(); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage)cons.receive(500); assertNotNull(tm); assertEquals("message" + i, tm.getText()); } //Now rollback long now = System.currentTimeMillis(); sess2.rollback(); //This should redeliver with a delayed redelivery for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage)cons.receive(delay + 1000); assertNotNull(tm); long time = System.currentTimeMillis(); assertTrue(time - now >= delay); //Hudson can introduce a large degree of indeterminism assertTrue((time - now) + ">" + (delay + 1000), time - now < delay + 1000); } sess2.commit(); } finally { if (conn != null) { conn.close(); } } } private void scheduledDelivery(boolean tx) throws Exception { Connection conn = null; try { conn = cf.createConnection(); Session sess = conn.createSession(tx, tx ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); MessageConsumer cons = sess.createConsumer(queue1); conn.start(); //Send one scheduled long now = System.currentTimeMillis(); TextMessage tm1 = sess.createTextMessage("testScheduled1"); tm1.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 7000); prod.send(tm1); //First send some non scheduled messages TextMessage tm2 = sess.createTextMessage("testScheduled2"); prod.send(tm2); TextMessage tm3 = sess.createTextMessage("testScheduled3"); prod.send(tm3); TextMessage tm4 = sess.createTextMessage("testScheduled4"); prod.send(tm4); //Now send some more scheduled messages TextMessage tm5 = sess.createTextMessage("testScheduled5"); tm5.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 5000); prod.send(tm5); TextMessage tm6 = sess.createTextMessage("testScheduled6"); tm6.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 4000); prod.send(tm6); TextMessage tm7 = sess.createTextMessage("testScheduled7"); tm7.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 3000); prod.send(tm7); TextMessage tm8 = sess.createTextMessage("testScheduled8"); tm8.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), now + 6000); prod.send(tm8); //And one scheduled with a -ve number TextMessage tm9 = sess.createTextMessage("testScheduled9"); - tm8.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), -3); + tm9.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), -3); prod.send(tm9); if (tx) { sess.commit(); } //First the non scheduled messages should be received forceGC(); TextMessage rm1 = (TextMessage)cons.receive(250); assertNotNull(rm1); assertEquals(tm2.getText(), rm1.getText()); TextMessage rm2 = (TextMessage)cons.receive(250); assertNotNull(rm2); assertEquals(tm3.getText(), rm2.getText()); TextMessage rm3 = (TextMessage)cons.receive(250); assertNotNull(rm3); assertEquals(tm4.getText(), rm3.getText()); //Now the one with a scheduled with a -ve number TextMessage rm5 = (TextMessage)cons.receive(250); assertNotNull(rm5); assertEquals(tm9.getText(), rm5.getText()); //Now the scheduled TextMessage rm6 = (TextMessage)cons.receive(3250); assertNotNull(rm6); assertEquals(tm7.getText(), rm6.getText()); long now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 3000); TextMessage rm7 = (TextMessage)cons.receive(1250); assertNotNull(rm7); assertEquals(tm6.getText(), rm7.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 4000); TextMessage rm8 = (TextMessage)cons.receive(1250); assertNotNull(rm8); assertEquals(tm5.getText(), rm8.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 5000); TextMessage rm9 = (TextMessage)cons.receive(1250); assertNotNull(rm9); assertEquals(tm8.getText(), rm9.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 6000); TextMessage rm10 = (TextMessage)cons.receive(1250); assertNotNull(rm10); assertEquals(tm1.getText(), rm10.getText()); now2 = System.currentTimeMillis(); assertTrue(now2 - now >= 7000); if (tx) { sess.commit(); } } finally { if (conn != null) { conn.close(); } } } // Inner classes ------------------------------------------------- }
false
false
null
null
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProfileModificationWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProfileModificationWizardPage.java index 473356908..dfabab1f2 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProfileModificationWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProfileModificationWizardPage.java @@ -1,340 +1,345 @@ /******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; import org.eclipse.equinox.internal.p2.ui.viewers.StaticContentProvider; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.ui.*; import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProfileModificationOperation; import org.eclipse.equinox.internal.provisional.p2.ui.query.IUPropertyUtils; import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.*; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.statushandlers.StatusManager; public abstract class ProfileModificationWizardPage extends WizardPage { - private static final int DEFAULT_HEIGHT = 20; + private static final int DEFAULT_HEIGHT = 15; private static final int DEFAULT_WIDTH = 120; private static final int DEFAULT_DESCRIPTION_HEIGHT = 4; private static final int DEFAULT_COLUMN_WIDTH = 60; private static final int DEFAULT_SMALL_COLUMN_WIDTH = 20; private static final String NESTING_INDENT = " "; //$NON-NLS-1$ private static final IStatus NULL_PLAN_STATUS = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, null); private IInstallableUnit[] ius; ProvisioningPlan currentPlan; IStatus currentStatus; private String profileId; CheckboxTableViewer listViewer; Text detailsArea; StaticContentProvider contentProvider; protected Display display; protected ProfileModificationWizardPage(String id, IInstallableUnit[] ius, String profileID, ProvisioningPlan initialPlan) { super(id); this.ius = ius; this.profileId = profileID; this.currentPlan = initialPlan; } public void createControl(Composite parent) { display = parent.getDisplay(); - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); + SashForm sashForm = new SashForm(parent, SWT.VERTICAL); + FillLayout layout = new FillLayout(); + sashForm.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(data); - initializeDialogUnits(composite); + sashForm.setLayoutData(data); + initializeDialogUnits(sashForm); + + Composite composite = new Composite(sashForm, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + gridLayout.marginWidth = 0; + gridLayout.marginHeight = 0; + composite.setLayout(gridLayout); // The viewer allows selection of IU's for browsing the details, // and checking to include in the provisioning operation. listViewer = CheckboxTableViewer.newCheckList(composite, SWT.BORDER | SWT.FULL_SELECTION); data = new GridData(GridData.FILL_BOTH); data.heightHint = convertHeightInCharsToPixels(DEFAULT_HEIGHT); data.widthHint = convertWidthInCharsToPixels(DEFAULT_WIDTH); Table table = listViewer.getTable(); table.setLayoutData(data); table.setHeaderVisible(true); IUColumnConfig[] columns = getColumnConfig(); for (int i = 0; i < columns.length; i++) { TableColumn tc = new TableColumn(table, SWT.LEFT, i); tc.setResizable(true); tc.setText(columns[i].columnTitle); if (columns[i].columnField == IUColumnConfig.COLUMN_SIZE) { tc.setAlignment(SWT.RIGHT); tc.setWidth(convertWidthInCharsToPixels(DEFAULT_SMALL_COLUMN_WIDTH)); } else tc.setWidth(convertWidthInCharsToPixels(DEFAULT_COLUMN_WIDTH)); } final List list = new ArrayList(ius.length); makeElements(getIUs(), list); listViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { checkedIUsChanged(); } }); listViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateStatus(); } }); // Filters and sorters before establishing content, so we don't refresh unnecessarily. listViewer.setComparator(new IUComparator(IUComparator.IU_NAME)); listViewer.setComparer(new ProvElementComparer()); contentProvider = new StaticContentProvider(list.toArray()); listViewer.setContentProvider(contentProvider); listViewer.setInput(new Object()); listViewer.setLabelProvider(new IUDetailsLabelProvider(null, getColumnConfig(), getShell())); setInitialCheckState(); // If the initial provisioning plan was already calculated, // no need to repeat it until the user changes selections if (currentPlan == null) checkedIUsChanged(); else currentStatus = PlanStatusHelper.computeStatus(currentPlan, ius); + // Optional area to show the size createSizingInfo(composite); // The text area shows a description of the selected IU, or error detail if applicable. - Group group = new Group(composite, SWT.NONE); + Group group = new Group(sashForm, SWT.NONE); group.setText(ProvUIMessages.ProfileModificationWizardPage_DetailsLabel); group.setLayout(new GridLayout()); - group.setLayoutData(new GridData(GridData.FILL_BOTH)); createDetailsArea(group); updateStatus(); - setControl(composite); - Dialog.applyDialogFont(composite); + setControl(sashForm); + sashForm.setWeights(new int[] {80, 20}); + Dialog.applyDialogFont(sashForm); } protected void createSizingInfo(Composite parent) { // Default is to do nothing } protected void createDetailsArea(Composite parent) { detailsArea = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.heightHint = convertHeightInCharsToPixels(DEFAULT_DESCRIPTION_HEIGHT); data.widthHint = convertWidthInCharsToPixels(DEFAULT_WIDTH); detailsArea.setLayoutData(data); } protected void makeElements(IInstallableUnit[] iusToShow, List list) { for (int i = 0; i < iusToShow.length; i++) { list.add(new AvailableIUElement(iusToShow[i], getProfileId())); } } public boolean performFinish() { if (currentStatus != null && currentStatus.getSeverity() != IStatus.ERROR) { ProfileModificationOperation op = createProfileModificationOperation(currentPlan); ProvisioningOperationRunner.schedule(op, getShell(), StatusManager.SHOW | StatusManager.LOG); return true; } return false; } protected Object[] getCheckedElements() { return listViewer.getCheckedElements(); } protected Object[] getSelectedElements() { return ((IStructuredSelection) listViewer.getSelection()).toArray(); } protected IInstallableUnit[] elementsToIUs(Object[] elements) { IInstallableUnit[] theIUs = new IInstallableUnit[elements.length]; for (int i = 0; i < elements.length; i++) { theIUs[i] = (IInstallableUnit) ProvUI.getAdapter(elements[i], IInstallableUnit.class); } return theIUs; } protected IInstallableUnit getSelectedIU() { IInstallableUnit[] units = elementsToIUs(getSelectedElements()); if (units.length == 0) return null; return units[0]; } protected String getProfileId() { return profileId; } protected IInstallableUnit[] getIUs() { return ius; } protected IUColumnConfig[] getColumnConfig() { return ProvUI.getIUColumnConfig(); } protected void checkedIUsChanged() { try { final Object[] selections = getCheckedElements(); if (selections.length == 0) { currentPlan = null; currentStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, IStatusCodes.EXPECTED_NOTHING_TO_DO, ProvUIMessages.ProfileModificationWizardPage_NothingSelected, null); } else getContainer().run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { try { currentPlan = computeProvisioningPlan(selections, monitor); if (currentPlan != null) currentStatus = PlanStatusHelper.computeStatus(currentPlan, elementsToIUs(selections)); else currentStatus = NULL_PLAN_STATUS; } catch (ProvisionException e) { currentPlan = null; currentStatus = ProvUI.handleException(e.getCause(), ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, StatusManager.LOG); } } }); } catch (InterruptedException e) { // Nothing to report if thread was interrupted } catch (InvocationTargetException e) { currentPlan = null; currentStatus = ProvUI.handleException(e.getCause(), ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, StatusManager.LOG); } updateStatus(); } private ProfileModificationOperation createProfileModificationOperation(ProvisioningPlan plan) { return new ProfileModificationOperation(getOperationLabel(), profileId, plan); } protected abstract ProvisioningPlan computeProvisioningPlan(Object[] checkedElements, IProgressMonitor monitor) throws ProvisionException; protected void setInitialCheckState() { // The default is to check everything because // in most cases, the user has selected exactly // what they want before this page opens. listViewer.setAllChecked(true); } // We currently create an empty provisioning context, but // in the future we could consider letting clients supply this. protected ProvisioningContext getProvisioningContext() { return new ProvisioningContext(); } protected abstract String getOperationLabel(); void updateStatus() { int messageType = IMessageProvider.NONE; boolean pageComplete = true; if (currentStatus != null && !currentStatus.isOK()) { messageType = IMessageProvider.INFORMATION; int severity = currentStatus.getSeverity(); if (severity == IStatus.ERROR) { messageType = IMessageProvider.ERROR; pageComplete = false; // Log errors for later support, but not if these are // simple UI validation errors. if (currentStatus.getCode() != IStatusCodes.EXPECTED_NOTHING_TO_DO) ProvUI.reportStatus(currentStatus, StatusManager.LOG); } else if (severity == IStatus.WARNING) { messageType = IMessageProvider.WARNING; // Log warnings for later support ProvUI.reportStatus(currentStatus, StatusManager.LOG); } } setPageComplete(pageComplete); setMessage(getMessageText(), messageType); detailsArea.setText(getDetailText()); } String getDetailText() { String detail = ""; //$NON-NLS-1$ if (currentStatus == null || currentStatus.isOK()) { IInstallableUnit iu = getSelectedIU(); if (iu != null) detail = getIUDescription(iu); } else { // current status is not OK. See if there are embedded exceptions or status to report StringBuffer buffer = new StringBuffer(); appendDetailText(currentStatus, buffer, -1, false); detail = buffer.toString(); } return detail; } void appendDetailText(IStatus status, StringBuffer buffer, int indent, boolean includeTopLevel) { for (int i = 0; i < indent; i++) buffer.append(NESTING_INDENT); if (includeTopLevel && status.getMessage() != null) buffer.append(status.getMessage()); Throwable t = status.getException(); if (t != null) { // A provision (or core) exception occurred. Get its status message or if none, its top level message. if (t instanceof CoreException) { IStatus exceptionStatus = ((CoreException) t).getStatus(); if (exceptionStatus != null && exceptionStatus.getMessage() != null) buffer.append(exceptionStatus.getMessage()); else { String details = t.getLocalizedMessage(); if (details != null) buffer.append(details); } } else { String details = t.getLocalizedMessage(); if (details != null) buffer.append(details); } } else { // This is the most important case. No exception occurred, we have a non-OK status after trying // to get a provisioning plan. It's important not to lose the multi status information. The top level status // message has already been reported IStatus[] children = status.getChildren(); for (int i = 0; i < children.length; i++) { appendDetailText(children[i], buffer, indent + 1, true); buffer.append('\n'); } } } String getMessageText() { if (currentStatus == null || currentStatus.isOK()) return getDescription(); return currentStatus.getMessage(); } protected String getIUDescription(IInstallableUnit iu) { // Get the iu description in the default locale String description = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION); if (description == null) description = ""; //$NON-NLS-1$ return description; } } \ No newline at end of file
false
false
null
null
diff --git a/src/com/android/exchange/SyncManager.java b/src/com/android/exchange/SyncManager.java index 7c372b3..ce71e84 100644 --- a/src/com/android/exchange/SyncManager.java +++ b/src/com/android/exchange/SyncManager.java @@ -1,1874 +1,1875 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange; import com.android.email.mail.MessagingException; import com.android.email.mail.store.TrustManagerFactory; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.HostAuth; import com.android.email.provider.EmailContent.HostAuthColumns; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.Message; import com.android.email.provider.EmailContent.SyncColumns; import com.android.exchange.utility.FileLogger; import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRoute; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncStatusObserver; import android.database.ContentObserver; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Debug; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.PowerManager.WakeLock; import android.provider.ContactsContract; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * The SyncManager handles all aspects of starting, maintaining, and stopping the various sync * adapters used by Exchange. However, it is capable of handing any kind of email sync, and it * would be appropriate to use for IMAP push, when that functionality is added to the Email * application. * * The Email application communicates with EAS sync adapters via SyncManager's binder interface, * which exposes UI-related functionality to the application (see the definitions below) * * SyncManager uses ContentObservers to detect changes to accounts, mailboxes, and messages in * order to maintain proper 2-way syncing of data. (More documentation to follow) * */ public class SyncManager extends Service implements Runnable { private static final String TAG = "EAS SyncManager"; // The SyncManager's mailbox "id" private static final int SYNC_MANAGER_ID = -1; private static final int SECONDS = 1000; private static final int MINUTES = 60*SECONDS; private static final int ONE_DAY_MINUTES = 1440; private static final int SYNC_MANAGER_HEARTBEAT_TIME = 15*MINUTES; private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES; // Sync hold constants for services with transient errors private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES; // Reason codes when SyncManager.kick is called (mainly for debugging) // UI has changed data, requiring an upsync of changes public static final int SYNC_UPSYNC = 0; // A scheduled sync (when not using push) public static final int SYNC_SCHEDULED = 1; // Mailbox was marked push public static final int SYNC_PUSH = 2; // A ping (EAS push signal) was received public static final int SYNC_PING = 3; // startSync was requested of SyncManager public static final int SYNC_SERVICE_START_SYNC = 4; // A part request (attachment load, for now) was sent to SyncManager public static final int SYNC_SERVICE_PART_REQUEST = 5; // Misc. public static final int SYNC_KICK = 6; private static final String WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.TYPE + "!=" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + " and " + MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ')'; protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE = MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ',' + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + ',' + Mailbox.TYPE_CONTACTS + ')'; private static final String WHERE_MAILBOX_KEY = Message.MAILBOX_KEY + "=?"; private static final String WHERE_PROTOCOL_EAS = HostAuthColumns.PROTOCOL + "=\"" + AbstractSyncService.EAS_PROTOCOL + "\""; private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN = "(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX + " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')' + " and " + MailboxColumns.ACCOUNT_KEY + " in ("; private static final String ACCOUNT_KEY_IN = MailboxColumns.ACCOUNT_KEY + " in ("; // Offsets into the syncStatus data for EAS that indicate type, exit status, and change count // The format is S<type_char>:<exit_char>:<change_count> public static final int STATUS_TYPE_CHAR = 1; public static final int STATUS_EXIT_CHAR = 3; public static final int STATUS_CHANGE_COUNT_OFFSET = 5; // Ready for ping public static final int PING_STATUS_OK = 0; // Service already running (can't ping) public static final int PING_STATUS_RUNNING = 1; // Service waiting after I/O error (can't ping) public static final int PING_STATUS_WAITING = 2; // Service had a fatal error; can't run public static final int PING_STATUS_UNABLE = 3; // We synchronize on this for all actions affecting the service and error maps private static Object sSyncToken = new Object(); // All threads can use this lock to wait for connectivity public static Object sConnectivityLock = new Object(); public static boolean sConnectivityHold = false; // Keeps track of running services (by mailbox id) private HashMap<Long, AbstractSyncService> mServiceMap = new HashMap<Long, AbstractSyncService>(); // Keeps track of services whose last sync ended with an error (by mailbox id) private HashMap<Long, SyncError> mSyncErrorMap = new HashMap<Long, SyncError>(); // Keeps track of which services require a wake lock (by mailbox id) private HashMap<Long, Boolean> mWakeLocks = new HashMap<Long, Boolean>(); // Keeps track of PendingIntents for mailbox alarms (by mailbox id) private HashMap<Long, PendingIntent> mPendingIntents = new HashMap<Long, PendingIntent>(); // The actual WakeLock obtained by SyncManager private WakeLock mWakeLock = null; private static final AccountList EMPTY_ACCOUNT_LIST = new AccountList(); // Observers that we use to look for changed mail-related data private Handler mHandler = new Handler(); private AccountObserver mAccountObserver; private MailboxObserver mMailboxObserver; private SyncedMessageObserver mSyncedMessageObserver; private MessageObserver mMessageObserver; private EasSyncStatusObserver mSyncStatusObserver; private EasAccountsUpdatedListener mAccountsUpdatedListener; private ContentResolver mResolver; // The singleton SyncManager object, with its thread and stop flag protected static SyncManager INSTANCE; private static Thread sServiceThread = null; // Cached unique device id private static String sDeviceId = null; // ConnectionManager that all EAS threads can use private static ClientConnectionManager sClientConnectionManager = null; private boolean mStop = false; // The reason for SyncManager's next wakeup call private String mNextWaitReason; // Whether we have an unsatisfied "kick" pending private boolean mKicked = false; // Receiver of connectivity broadcasts private ConnectivityReceiver mConnectivityReceiver = null; // The callback sent in from the UI using setCallback private IEmailServiceCallback mCallback; private RemoteCallbackList<IEmailServiceCallback> mCallbackList = new RemoteCallbackList<IEmailServiceCallback>(); /** * Proxy that can be used by various sync adapters to tie into SyncManager's callback system. * Used this way: SyncManager.callback().callbackMethod(args...); * The proxy wraps checking for existence of a SyncManager instance and an active callback. * Failures of these callbacks can be safely ignored. */ static private final IEmailServiceCallback.Stub sCallbackProxy = new IEmailServiceCallback.Stub() { public void loadAttachmentStatus(long messageId, long attachmentId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.loadAttachmentStatus(messageId, attachmentId, statusCode, progress); } } public void sendMessageStatus(long messageId, String subject, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.sendMessageStatus(messageId, subject, statusCode, progress); } } public void syncMailboxListStatus(long accountId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.syncMailboxListStatus(accountId, statusCode, progress); } } public void syncMailboxStatus(long mailboxId, int statusCode, int progress) throws RemoteException { IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback; if (cb != null) { cb.syncMailboxStatus(mailboxId, statusCode, progress); } else if (INSTANCE != null) { INSTANCE.log("orphan syncMailboxStatus, id=" + mailboxId + " status=" + statusCode); } } }; /** * Create our EmailService implementation here. */ private final IEmailService.Stub mBinder = new IEmailService.Stub() { public int validate(String protocol, String host, String userName, String password, int port, boolean ssl, boolean trustCertificates) throws RemoteException { try { AbstractSyncService.validate(EasSyncService.class, host, userName, password, port, ssl, trustCertificates, SyncManager.this); return MessagingException.NO_ERROR; } catch (MessagingException e) { return e.getExceptionType(); } } public void startSync(long mailboxId) throws RemoteException { checkSyncManagerServiceRunning(); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m.mType == Mailbox.TYPE_OUTBOX) { // We're using SERVER_ID to indicate an error condition (it has no other use for // sent mail) Upon request to sync the Outbox, we clear this so that all messages // are candidates for sending. ContentValues cv = new ContentValues(); cv.put(SyncColumns.SERVER_ID, 0); INSTANCE.getContentResolver().update(Message.CONTENT_URI, cv, WHERE_MAILBOX_KEY, new String[] {Long.toString(mailboxId)}); kick("start outbox"); // Outbox can't be synced in EAS return; } else if (m.mType == Mailbox.TYPE_DRAFTS) { // Drafts can't be synced in EAS return; } startManualSync(mailboxId, SyncManager.SYNC_SERVICE_START_SYNC, null); } public void stopSync(long mailboxId) throws RemoteException { stopManualSync(mailboxId); } public void loadAttachment(long attachmentId, String destinationFile, String contentUriString) throws RemoteException { Attachment att = Attachment.restoreAttachmentWithId(SyncManager.this, attachmentId); partRequest(new PartRequest(att, destinationFile, contentUriString)); } public void updateFolderList(long accountId) throws RemoteException { reloadFolderList(SyncManager.this, accountId, false); } public void hostChanged(long accountId) throws RemoteException { if (INSTANCE != null) { synchronized (INSTANCE.mSyncErrorMap) { // Go through the various error mailboxes for (long mailboxId: INSTANCE.mSyncErrorMap.keySet()) { SyncError error = INSTANCE.mSyncErrorMap.get(mailboxId); // If it's a login failure, look a little harder Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); // If it's for the account whose host has changed, clear the error if (m.mAccountKey == accountId) { error.fatal = false; error.holdEndTime = 0; } } } // Stop any running syncs INSTANCE.stopAccountSyncs(accountId, true); // Kick SyncManager kick("host changed"); } } public void setLogging(int on) throws RemoteException { Eas.setUserDebug(on); } public void loadMore(long messageId) throws RemoteException { // TODO Auto-generated method stub } // The following three methods are not implemented in this version public boolean createFolder(long accountId, String name) throws RemoteException { return false; } public boolean deleteFolder(long accountId, String name) throws RemoteException { return false; } public boolean renameFolder(long accountId, String oldName, String newName) throws RemoteException { return false; } public void setCallback(IEmailServiceCallback cb) throws RemoteException { if (mCallback != null) { mCallbackList.unregister(mCallback); } mCallback = cb; mCallbackList.register(cb); } }; static class AccountList extends ArrayList<Account> { private static final long serialVersionUID = 1L; public boolean contains(long id) { for (Account account: this) { if (account.mId == id) { return true; } } return false; } public Account getById(long id) { for (Account account: this) { if (account.mId == id) { return account; } } return null; } } class AccountObserver extends ContentObserver { // mAccounts keeps track of Accounts that we care about (EAS for now) AccountList mAccounts = new AccountList(); String mSyncableEasMailboxSelector = null; String mEasAccountSelector = null; public AccountObserver(Handler handler) { super(handler); // At startup, we want to see what EAS accounts exist and cache them Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null); try { collectEasAccounts(c, mAccounts); } finally { c.close(); } // Create the account mailbox for any account that doesn't have one Context context = getContext(); for (Account account: mAccounts) { int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey=" + account.mId, null); if (cnt == 0) { addAccountMailbox(account.mId); } } } /** * Returns a String suitable for appending to a where clause that selects for all syncable * mailboxes in all eas accounts * @return a complex selection string that is not to be cached */ public String getSyncableEasMailboxWhere() { if (mSyncableEasMailboxSelector == null) { StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN); boolean first = true; for (Account account: mAccounts) { if (!first) { sb.append(','); } else { first = false; } sb.append(account.mId); } sb.append(')'); mSyncableEasMailboxSelector = sb.toString(); } return mSyncableEasMailboxSelector; } /** * Returns a String suitable for appending to a where clause that selects for all eas * accounts. * @return a String in the form "accountKey in (a, b, c...)" that is not to be cached */ public String getAccountKeyWhere() { if (mEasAccountSelector == null) { StringBuilder sb = new StringBuilder(ACCOUNT_KEY_IN); boolean first = true; for (Account account: mAccounts) { if (!first) { sb.append(','); } else { first = false; } sb.append(account.mId); } sb.append(')'); mEasAccountSelector = sb.toString(); } return mEasAccountSelector; } private boolean syncParametersChanged(Account account) { long accountId = account.mId; // Reload account from database to get its current state account = Account.restoreAccountWithId(getContext(), accountId); for (Account oldAccount: mAccounts) { if (oldAccount.mId == accountId) { return oldAccount.mSyncInterval != account.mSyncInterval || oldAccount.mSyncLookback != account.mSyncLookback; } } // Really, we can't get here, but we don't want the compiler to complain return false; } @Override public void onChange(boolean selfChange) { maybeStartSyncManagerThread(); // A change to the list requires us to scan for deletions (to stop running syncs) // At startup, we want to see what accounts exist and cache them AccountList currentAccounts = new AccountList(); Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null); try { collectEasAccounts(c, currentAccounts); for (Account account : mAccounts) { if (!currentAccounts.contains(account.mId)) { // This is a deletion; shut down any account-related syncs stopAccountSyncs(account.mId, true); // Delete this from AccountManager... android.accounts.Account acct = new android.accounts.Account(account.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); AccountManager.get(SyncManager.this).removeAccount(acct, null, null); mSyncableEasMailboxSelector = null; mEasAccountSelector = null; } else { // See whether any of our accounts has changed sync interval or window if (syncParametersChanged(account)) { // Set pushable boxes' sync interval to the sync interval of the Account Account updatedAccount = Account.restoreAccountWithId(getContext(), account.mId); ContentValues cv = new ContentValues(); cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval); getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] {Long.toString(account.mId)}); // Stop all current syncs; the appropriate ones will restart INSTANCE.log("Account " + account.mDisplayName + " changed; stop running syncs..."); stopAccountSyncs(account.mId, true); } } } // Look for new accounts for (Account account: currentAccounts) { if (!mAccounts.contains(account.mId)) { // This is an addition; create our magic hidden mailbox... addAccountMailbox(account.mId); // Don't forget to cache the HostAuth HostAuth ha = HostAuth.restoreHostAuthWithId(getContext(), account.mHostAuthKeyRecv); account.mHostAuthRecv = ha; mAccounts.add(account); mSyncableEasMailboxSelector = null; mEasAccountSelector = null; } } // Finally, make sure mAccounts is up to date mAccounts = currentAccounts; } finally { c.close(); } // See if there's anything to do... kick("account changed"); } private void collectEasAccounts(Cursor c, ArrayList<Account> accounts) { Context context = getContext(); if (context == null) return; while (c.moveToNext()) { long hostAuthId = c.getLong(Account.CONTENT_HOST_AUTH_KEY_RECV_COLUMN); if (hostAuthId > 0) { HostAuth ha = HostAuth.restoreHostAuthWithId(context, hostAuthId); if (ha != null && ha.mProtocol.equals("eas")) { Account account = new Account().restore(c); // Cache the HostAuth account.mHostAuthRecv = ha; accounts.add(account); } } } } private void addAccountMailbox(long acctId) { Account acct = Account.restoreAccountWithId(getContext(), acctId); Mailbox main = new Mailbox(); main.mDisplayName = Eas.ACCOUNT_MAILBOX; main.mServerId = Eas.ACCOUNT_MAILBOX + System.nanoTime(); main.mAccountKey = acct.mId; main.mType = Mailbox.TYPE_EAS_ACCOUNT_MAILBOX; main.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; main.mFlagVisible = false; main.save(getContext()); INSTANCE.log("Initializing account: " + acct.mDisplayName); } } class MailboxObserver extends ContentObserver { public MailboxObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { // See if there's anything to do... if (!selfChange) { kick("mailbox changed"); } } } class SyncedMessageObserver extends ContentObserver { Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class); PendingIntent syncAlarmPendingIntent = PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0); AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE); public SyncedMessageObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { INSTANCE.log("SyncedMessage changed: (re)setting alarm for 10s"); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent); } } class MessageObserver extends ContentObserver { public MessageObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { // A rather blunt instrument here. But we don't have information about the URI that // triggered this, though it must have been an insert if (!selfChange) { kick(null); } } } static public IEmailServiceCallback callback() { return sCallbackProxy; } static public AccountList getAccountList() { if (INSTANCE != null) { return INSTANCE.mAccountObserver.mAccounts; } else { return EMPTY_ACCOUNT_LIST; } } static public String getEasAccountSelector() { if (INSTANCE != null) { return INSTANCE.mAccountObserver.getAccountKeyWhere(); } else { return null; } } private Account getAccountById(long accountId) { return mAccountObserver.mAccounts.getById(accountId); } public class SyncStatus { static public final int NOT_RUNNING = 0; static public final int DIED = 1; static public final int SYNC = 2; static public final int IDLE = 3; } class SyncError { int reason; boolean fatal = false; long holdDelay = 15*SECONDS; long holdEndTime = System.currentTimeMillis() + holdDelay; SyncError(int _reason, boolean _fatal) { reason = _reason; fatal = _fatal; } /** * We double the holdDelay from 15 seconds through 4 mins */ void escalate() { if (holdDelay < HOLD_DELAY_MAXIMUM) { holdDelay *= 2; } holdEndTime = System.currentTimeMillis() + holdDelay; } } public class EasSyncStatusObserver implements SyncStatusObserver { public void onStatusChanged(int which) { // We ignore the argument (we can only get called in one case - when settings change) // TODO Go through each account and see if sync is enabled and/or automatic for // the Contacts authority, and set syncInterval accordingly. Then kick ourselves. if (INSTANCE != null) { checkPIMSyncSettings(); } } } public class EasAccountsUpdatedListener implements OnAccountsUpdateListener { public void onAccountsUpdated(android.accounts.Account[] accounts) { checkWithAccountManager(); } } static public void smLog(String str) { if (INSTANCE != null) { INSTANCE.log(str); } } protected void log(String str) { if (Eas.USER_LOG) { Log.d(TAG, str); if (Eas.FILE_LOG) { FileLogger.log(TAG, str); } } } protected void alwaysLog(String str) { if (!Eas.USER_LOG) { Log.d(TAG, str); } else { log(str); } } /** * EAS requires a unique device id, so that sync is possible from a variety of different * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other * device that doesn't provide one, we can create it as droid<n> where <n> is system time. * This would work on a real device as well, but it would be better to use the "real" id if * it's available */ static public String getDeviceId() throws IOException { return getDeviceId(null); } - + static public synchronized String getDeviceId(Context context) throws IOException { if (sDeviceId != null) { return sDeviceId; } else if (INSTANCE == null && context == null) { throw new IOException("No context for getDeviceId"); } else if (context == null) { context = INSTANCE; } // Otherwise, we'll read the id file or create one if it's not found try { File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists() && f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); return id; } else if (f.createNewFile()) { BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); id = "droid" + System.currentTimeMillis(); w.write(id); w.close(); sDeviceId = id; return id; } } catch (IOException e) { } throw new IOException("Can't get device name"); } @Override public IBinder onBind(Intent arg0) { return mBinder; } /** - * Note that there are two ways the EAS SyncManager service can be created: + * Note that there are two ways the EAS SyncManager service can be created: * - * 1) as a background service instantiated via startService (which happens on boot, when the - * first EAS account is created, etc), in which case the service thread is spun up, mailboxes + * 1) as a background service instantiated via startService (which happens on boot, when the + * first EAS account is created, etc), in which case the service thread is spun up, mailboxes * sync, etc. and * 2) to execute an RPC call from the UI, in which case the background service will already be * running most of the time (unless we're creating a first EAS account) * * If the running background service detects that there are no EAS accounts (on boot, if none * were created, or afterward if the last remaining EAS account is deleted), it will call * stopSelf() to terminate operation. * * The goal is to ensure that the background service is running at all times when there is at * least one EAS account in existence * * Because there are edge cases in which our process can crash (typically, this has been seen * in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the * background service having been started. We explicitly try to start the service in Welcome * (to handle the case of the app having been reloaded). We also start the service on any * startSync call (if it isn't already running) */ @Override public void onCreate() { alwaysLog("!!! EAS SyncManager, onCreate"); if (INSTANCE == null) { INSTANCE = this; mResolver = getContentResolver(); mAccountObserver = new AccountObserver(mHandler); mResolver.registerContentObserver(Account.CONTENT_URI, true, mAccountObserver); mMailboxObserver = new MailboxObserver(mHandler); mSyncedMessageObserver = new SyncedMessageObserver(mHandler); mMessageObserver = new MessageObserver(mHandler); mSyncStatusObserver = new EasSyncStatusObserver(); } else { alwaysLog("!!! EAS SyncManager onCreated, but INSTANCE not null??"); } if (sDeviceId == null) { try { getDeviceId(this); } catch (IOException e) { // We can't run in this situation throw new RuntimeException(); } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { alwaysLog("!!! EAS SyncManager, onStartCommand"); maybeStartSyncManagerThread(); if (sServiceThread == null) { alwaysLog("!!! EAS SyncManager, stopping self"); stopSelf(); } return Service.START_STICKY; } @Override public void onDestroy() { alwaysLog("!!! EAS SyncManager, onDestroy"); if (INSTANCE != null) { INSTANCE = null; mResolver.unregisterContentObserver(mAccountObserver); mResolver = null; mAccountObserver = null; mMailboxObserver = null; mSyncedMessageObserver = null; mMessageObserver = null; mSyncStatusObserver = null; + mAccountsUpdatedListener = null; } } void maybeStartSyncManagerThread() { // Start our thread... // See if there are any EAS accounts; otherwise, just go away if (EmailContent.count(this, HostAuth.CONTENT_URI, WHERE_PROTOCOL_EAS, null) > 0) { if (sServiceThread == null || !sServiceThread.isAlive()) { log(sServiceThread == null ? "Starting thread..." : "Restarting thread..."); sServiceThread = new Thread(this, "SyncManager"); sServiceThread.start(); } } } static void checkSyncManagerServiceRunning() { // Get the service thread running if it isn't // This is a stopgap for cases in which SyncManager died (due to a crash somewhere in // com.android.email) and hasn't been restarted // See the comment for onCreate for details if (INSTANCE == null) return; if (sServiceThread == null) { INSTANCE.alwaysLog("!!! checkSyncManagerServiceRunning; starting service..."); INSTANCE.startService(new Intent(INSTANCE, SyncManager.class)); } } - + static public ConnPerRoute sConnPerRoute = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return 8; } }; static public synchronized ClientConnectionManager getClientConnectionManager() { if (sClientConnectionManager == null) { // Create a registry for our three schemes; http and https will use built-in factories SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Create a new SSLSocketFactory for our "trusted ssl" // Get the unsecure trust manager from the factory X509TrustManager trustManager = TrustManagerFactory.get(null, false); TrustManager[] trustManagers = new TrustManager[] {trustManager}; SSLContext sslcontext; try { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, trustManagers, null); SSLContextImpl sslContext = new SSLContextImpl(); try { sslContext.engineInit(null, trustManagers, null, null, null); } catch (KeyManagementException e) { throw new AssertionError(e); } // Ok, now make our factory SSLSocketFactory sf = new SSLSocketFactory(sslContext.engineGetSocketFactory()); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Register the httpts scheme with our factory registry.register(new Scheme("httpts", sf, 443)); // And create a ccm with our registry HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); sClientConnectionManager = new ThreadSafeClientConnManager(params, registry); } catch (NoSuchAlgorithmException e2) { } catch (KeyManagementException e1) { } } // Null is a valid return result if we get an exception return sClientConnectionManager; } public static void stopAccountSyncs(long acctId) { if (INSTANCE != null) { INSTANCE.stopAccountSyncs(acctId, true); } } private void stopAccountSyncs(long acctId, boolean includeAccountMailbox) { synchronized (sSyncToken) { List<Long> deletedBoxes = new ArrayList<Long>(); for (Long mid : INSTANCE.mServiceMap.keySet()) { Mailbox box = Mailbox.restoreMailboxWithId(INSTANCE, mid); if (box != null) { if (box.mAccountKey == acctId) { if (!includeAccountMailbox && box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { AbstractSyncService svc = INSTANCE.mServiceMap.get(mid); if (svc != null) { svc.stop(); } continue; } AbstractSyncService svc = INSTANCE.mServiceMap.get(mid); if (svc != null) { svc.stop(); Thread t = svc.mThread; if (t != null) { t.interrupt(); } } deletedBoxes.add(mid); } } } for (Long mid : deletedBoxes) { releaseMailbox(mid); } } } static public void reloadFolderList(Context context, long accountId, boolean force) { if (INSTANCE == null) return; Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + "=?", new String[] {Long.toString(accountId), Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX)}, null); try { if (c.moveToFirst()) { synchronized(sSyncToken) { Mailbox m = new Mailbox().restore(c); Account acct = Account.restoreAccountWithId(context, accountId); if (acct == null) { return; } String syncKey = acct.mSyncKey; // No need to reload the list if we don't have one if (!force && (syncKey == null || syncKey.equals("0"))) { return; } // Change all ping/push boxes to push/hold ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD); context.getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX, new String[] {Long.toString(accountId)}); INSTANCE.log("Set push/ping boxes to push/hold"); long id = m.mId; AbstractSyncService svc = INSTANCE.mServiceMap.get(id); // Tell the service we're done if (svc != null) { synchronized (svc.getSynchronizer()) { svc.stop(); } // Interrupt the thread so that it can stop Thread thread = svc.mThread; thread.setName(thread.getName() + " (Stopped)"); thread.interrupt(); // Abandon the service INSTANCE.releaseMailbox(id); // And have it start naturally kick("reload folder list"); } } } } finally { c.close(); } } /** * Informs SyncManager that an account has a new folder list; as a result, any existing folder * might have become invalid. Therefore, we act as if the account has been deleted, and then * we reinitialize it. * * @param acctId */ static public void folderListReloaded(long acctId) { if (INSTANCE != null) { INSTANCE.stopAccountSyncs(acctId, false); kick("reload folder list"); } } // private void logLocks(String str) { // StringBuilder sb = new StringBuilder(str); // boolean first = true; // for (long id: mWakeLocks.keySet()) { // if (!first) { // sb.append(", "); // } else { // first = false; // } // sb.append(id); // } // log(sb.toString()); // } private void acquireWakeLock(long id) { synchronized (mWakeLocks) { Boolean lock = mWakeLocks.get(id); if (lock == null) { if (id > 0) { //log("+WakeLock requested for " + alarmOwner(id)); } if (mWakeLock == null) { PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE"); mWakeLock.acquire(); log("+WAKE LOCK ACQUIRED"); } mWakeLocks.put(id, true); //logLocks("Post-acquire of WakeLock for " + alarmOwner(id) + ": "); } } } private void releaseWakeLock(long id) { synchronized (mWakeLocks) { Boolean lock = mWakeLocks.get(id); if (lock != null) { if (id > 0) { //log("+WakeLock not needed for " + alarmOwner(id)); } mWakeLocks.remove(id); if (mWakeLocks.isEmpty()) { if (mWakeLock != null) { mWakeLock.release(); } mWakeLock = null; log("+WAKE LOCK RELEASED"); } else { //logLocks("Post-release of WakeLock for " + alarmOwner(id) + ": "); } } } } static public String alarmOwner(long id) { if (id == SYNC_MANAGER_ID) { return "SyncManager"; } else { String name = Long.toString(id); if (Eas.USER_LOG && INSTANCE != null) { Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id); if (m != null) { name = m.mDisplayName + '(' + m.mAccountKey + ')'; } } return "Mailbox " + name; } } private void clearAlarm(long id) { synchronized (mPendingIntents) { PendingIntent pi = mPendingIntents.get(id); if (pi != null) { AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pi); log("+Alarm cleared for " + alarmOwner(id)); mPendingIntents.remove(id); } } } private void setAlarm(long id, long millis) { synchronized (mPendingIntents) { PendingIntent pi = mPendingIntents.get(id); if (pi == null) { Intent i = new Intent(this, MailboxAlarmReceiver.class); i.putExtra("mailbox", id); i.setData(Uri.parse("Box" + id)); pi = PendingIntent.getBroadcast(this, 0, i, 0); mPendingIntents.put(id, pi); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi); log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s"); } } } private void clearAlarms() { AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); synchronized (mPendingIntents) { for (PendingIntent pi : mPendingIntents.values()) { alarmManager.cancel(pi); } mPendingIntents.clear(); } } static public void runAwake(long id) { if (INSTANCE == null) return; INSTANCE.acquireWakeLock(id); INSTANCE.clearAlarm(id); } static public void runAsleep(long id, long millis) { if (INSTANCE == null) return; INSTANCE.setAlarm(id, millis); INSTANCE.releaseWakeLock(id); } static public void ping(Context context, long id) { checkSyncManagerServiceRunning(); if (id < 0) { kick("ping SyncManager"); } else if (INSTANCE == null) { context.startService(new Intent(context, SyncManager.class)); } else { AbstractSyncService service = INSTANCE.mServiceMap.get(id); if (service != null) { Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id); if (m != null) { // We ignore drafts completely (doesn't sync). Changes in Outbox are handled // in the checkMailboxes loop, so we can ignore these pings. if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) { String[] args = new String[] {Long.toString(m.mId)}; ContentResolver resolver = INSTANCE.mResolver; resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args); resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args); return; } service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey); service.mMailbox = m; service.ping(); } } } } /** * See if we need to change the syncInterval for any of our PIM mailboxes based on changes * to settings in the AccountManager (sync settings). * This code is called 1) when SyncManager starts, and 2) when SyncManager is running and there * are changes made (this is detected via a SyncStatusObserver) */ private void checkPIMSyncSettings() { ContentValues cv = new ContentValues(); // For now, just Contacts // First, walk through our list of accounts List<Account> easAccounts = getAccountList(); for (Account easAccount: easAccounts) { // Find the contacts mailbox long contactsId = Mailbox.findMailboxOfType(this, easAccount.mId, Mailbox.TYPE_CONTACTS); // Presumably there is one, but if not, it's ok. Just move on... if (contactsId != Mailbox.NO_MAILBOX) { // Create an AccountManager style Account android.accounts.Account acct = new android.accounts.Account(easAccount.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); // Get the Contacts mailbox; this happens rarely so it's ok to get it all Mailbox contacts = Mailbox.restoreMailboxWithId(this, contactsId); int syncInterval = contacts.mSyncInterval; // If we're syncable, look further... if (ContentResolver.getIsSyncable(acct, ContactsContract.AUTHORITY) > 0) { // If we're supposed to sync automatically (push), set to push if it's not if (ContentResolver.getSyncAutomatically(acct, ContactsContract.AUTHORITY)) { if (syncInterval == Mailbox.CHECK_INTERVAL_NEVER || syncInterval > 0) { log("Sync setting: Contacts for " + acct.name + " changed to push"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); } // If we're NOT supposed to push, and we're not set up that way, change it } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync setting: Contacts for " + acct.name + " changed to manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If not, set it to never check } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync setting: Contacts for " + acct.name + " changed to manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If we've made a change, update the Mailbox, and kick if (cv.containsKey(MailboxColumns.SYNC_INTERVAL)) { mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, contactsId), cv,null, null); kick("sync settings change"); } } } } private void checkWithAccountManager() { android.accounts.Account[] accts = AccountManager.get(this).getAccountsByType(Eas.ACCOUNT_MANAGER_TYPE); List<Account> easAccounts = getAccountList(); for (Account easAccount: easAccounts) { String accountName = easAccount.mEmailAddress; boolean found = false; for (android.accounts.Account acct: accts) { if (acct.name.equalsIgnoreCase(accountName)) { found = true; break; } } if (!found) { // This account has been deleted in the AccountManager! log("Account deleted in AccountManager; deleting from provider: " + accountName); // TODO This will orphan downloaded attachments; need to handle this mResolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI, easAccount.mId), null, null); } } } private void releaseConnectivityLock(String reason) { // Clear our sync error map when we get connected mSyncErrorMap.clear(); synchronized (sConnectivityLock) { sConnectivityLock.notifyAll(); } kick(reason); } public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); if (b != null) { NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO); String info = "Connectivity alert for " + a.getTypeName(); State state = a.getState(); if (state == State.CONNECTED) { info += " CONNECTED"; log(info); releaseConnectivityLock("connected"); } else if (state == State.DISCONNECTED) { info += " DISCONNECTED"; a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (a != null && a.getState() == State.CONNECTED) { info += " (OTHER CONNECTED)"; releaseConnectivityLock("disconnect/other"); ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo i = cm.getActiveNetworkInfo(); if (i == null || i.getState() != State.CONNECTED) { log("CM says we're connected, but no active info?"); } } } else { log(info); kick("disconnected"); } } } } } private void startService(AbstractSyncService service, Mailbox m) { synchronized (sSyncToken) { String mailboxName = m.mDisplayName; String accountName = service.mAccount.mDisplayName; Thread thread = new Thread(service, mailboxName + "(" + accountName + ")"); log("Starting thread for " + mailboxName + " in account " + accountName); thread.start(); mServiceMap.put(m.mId, service); runAwake(m.mId); } } private void startService(Mailbox m, int reason, PartRequest req) { // Don't sync if there's no connectivity if (sConnectivityHold) return; synchronized (sSyncToken) { Account acct = Account.restoreAccountWithId(this, m.mAccountKey); if (acct != null) { // Always make sure there's not a running instance of this service AbstractSyncService service = mServiceMap.get(m.mId); if (service == null) { service = new EasSyncService(this, m); service.mSyncReason = reason; if (req != null) { service.addPartRequest(req); } startService(service, m); } } } } private void stopServices() { synchronized (sSyncToken) { ArrayList<Long> toStop = new ArrayList<Long>(); // Keep track of which services to stop for (Long mailboxId : mServiceMap.keySet()) { toStop.add(mailboxId); } // Shut down all of those running services for (Long mailboxId : toStop) { AbstractSyncService svc = mServiceMap.get(mailboxId); if (svc != null) { log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName); svc.stop(); if (svc.mThread != null) { svc.mThread.interrupt(); } } releaseWakeLock(mailboxId); } } } private void waitForConnectivity() { int cnt = 0; while (!mStop) { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { //log("NetworkInfo: " + info.getTypeName() + ", " + info.getState().name()); return; } else { // If we're waiting for the long haul, shut down running service threads if (++cnt > 1) { stopServices(); } // Wait until a network is connected, but let the device sleep // We'll set an alarm just in case we don't get notified (bugs happen) synchronized (sConnectivityLock) { runAsleep(SYNC_MANAGER_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS); try { log("Connectivity lock..."); sConnectivityHold = true; sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME); log("Connectivity lock released..."); } catch (InterruptedException e) { } finally { sConnectivityHold = false; } runAwake(SYNC_MANAGER_ID); } } } } public void run() { mStop = false; // If we're really debugging, turn on all logging if (Eas.DEBUG) { Eas.USER_LOG = true; Eas.PARSER_LOG = true; Eas.FILE_LOG = true; } // If we need to wait for the debugger, do so if (Eas.WAIT_DEBUG) { Debug.waitForDebugger(); } // Set up our observers; we need them to know when to start/stop various syncs based // on the insert/delete/update of mailboxes and accounts // We also observe synced messages to trigger upsyncs at the appropriate time mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver); mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver); mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver); ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); mAccountsUpdatedListener = new EasAccountsUpdatedListener(); AccountManager.get(getApplication()) .addOnAccountsUpdatedListener(mAccountsUpdatedListener, mHandler, true); mConnectivityReceiver = new ConnectivityReceiver(); registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); // See if any settings have changed while we weren't running... checkPIMSyncSettings(); try { while (!mStop) { runAwake(SYNC_MANAGER_ID); waitForConnectivity(); mNextWaitReason = "Heartbeat"; long nextWait = checkMailboxes(); try { synchronized (this) { if (!mKicked) { if (nextWait < 0) { log("Negative wait? Setting to 1s"); nextWait = 1*SECONDS; } if (nextWait > 10*SECONDS) { log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason); runAsleep(SYNC_MANAGER_ID, nextWait + (3*SECONDS)); } wait(nextWait); } } } catch (InterruptedException e) { // Needs to be caught, but causes no problem } finally { synchronized (this) { if (mKicked) { //log("Wait deferred due to kick"); mKicked = false; } } } } stopServices(); log("Shutdown requested"); } finally { // Lots of cleanup here // Stop our running syncs stopServices(); // Stop receivers and content observers if (mConnectivityReceiver != null) { unregisterReceiver(mConnectivityReceiver); } - + if (INSTANCE != null) { ContentResolver resolver = getContentResolver(); resolver.unregisterContentObserver(mAccountObserver); resolver.unregisterContentObserver(mMailboxObserver); resolver.unregisterContentObserver(mSyncedMessageObserver); resolver.unregisterContentObserver(mMessageObserver); } // Don't leak the Intent associated with this listener if (mAccountsUpdatedListener != null) { AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener); mAccountsUpdatedListener = null; } // Clear pending alarms and associated Intents clearAlarms(); // Release our wake lock, if we have one synchronized (mWakeLocks) { if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } log("Goodbye"); } if (!mStop) { // If this wasn't intentional, try to restart the service throw new RuntimeException("EAS SyncManager crash; please restart me..."); } } private void releaseMailbox(long mailboxId) { mServiceMap.remove(mailboxId); releaseWakeLock(mailboxId); } private long checkMailboxes () { // First, see if any running mailboxes have been deleted ArrayList<Long> deletedMailboxes = new ArrayList<Long>(); synchronized (sSyncToken) { for (long mailboxId: mServiceMap.keySet()) { Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId); if (m == null) { deletedMailboxes.add(mailboxId); } } // If so, stop them or remove them from the map for (Long mailboxId: deletedMailboxes) { AbstractSyncService svc = mServiceMap.get(mailboxId); if (svc != null) { boolean alive = svc.mThread.isAlive(); log("Deleted mailbox: " + svc.mMailboxName); if (alive) { stopManualSync(mailboxId); } else { log("Removing from serviceMap"); releaseMailbox(mailboxId); } } } } long nextWait = SYNC_MANAGER_HEARTBEAT_TIME; long now = System.currentTimeMillis(); // Start up threads that need it; use a query which finds eas mailboxes where the // the sync interval is not "never". This is the set of mailboxes that we control Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, mAccountObserver.getSyncableEasMailboxWhere(), null, null); try { while (c.moveToNext()) { long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN); AbstractSyncService service = null; synchronized (sSyncToken) { service = mServiceMap.get(mid); } if (service == null) { // Check whether we're in a hold (temporary or permanent) SyncError syncError = mSyncErrorMap.get(mid); if (syncError != null) { // Nothing we can do about fatal errors if (syncError.fatal) continue; if (now < syncError.holdEndTime) { // If release time is earlier than next wait time, // move next wait time up to the release time if (syncError.holdEndTime < now + nextWait) { nextWait = syncError.holdEndTime - now; mNextWaitReason = "Release hold"; } continue; } else { // Keep the error around, but clear the end time syncError.holdEndTime = 0; } } // We handle a few types of mailboxes specially int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); if (type == Mailbox.TYPE_CONTACTS) { // See if "sync automatically" is set Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN)); if (account != null) { android.accounts.Account a = new android.accounts.Account(account.mEmailAddress, Eas.ACCOUNT_MANAGER_TYPE); if (!ContentResolver.getSyncAutomatically(a, ContactsContract.AUTHORITY)) { continue; } } } else if (type == Mailbox.TYPE_TRASH) { continue; } // Otherwise, we use the sync interval long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN); if (interval == Mailbox.CHECK_INTERVAL_PUSH) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(m, SYNC_PUSH, null); } else if (type == Mailbox.TYPE_OUTBOX) { int cnt = EmailContent.count(this, Message.CONTENT_URI, EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED, new String[] {Long.toString(mid)}); if (cnt > 0) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(new EasOutboxService(this, m), m); } } else if (interval > 0 && interval <= ONE_DAY_MINUTES) { long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN); long sinceLastSync = now - lastSync; if (sinceLastSync < 0) { log("WHOA! lastSync in the future for mailbox: " + mid); sinceLastSync = interval*MINUTES; } long toNextSync = interval*MINUTES - sinceLastSync; String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); if (toNextSync <= 0) { Mailbox m = EmailContent.getContent(c, Mailbox.class); startService(m, SYNC_SCHEDULED, null); } else if (toNextSync < nextWait) { nextWait = toNextSync; if (Eas.USER_LOG) { log("Next sync for " + name + " in " + nextWait/1000 + "s"); } mNextWaitReason = "Scheduled sync, " + name; } else if (Eas.USER_LOG) { log("Next sync for " + name + " in " + toNextSync/1000 + "s"); } } } else { Thread thread = service.mThread; // Look for threads that have died but aren't in an error state if (thread != null && !thread.isAlive() && !mSyncErrorMap.containsKey(mid)) { releaseMailbox(mid); // Restart this if necessary if (nextWait > 3*SECONDS) { nextWait = 3*SECONDS; mNextWaitReason = "Clean up dead thread(s)"; } } else { long requestTime = service.mRequestTime; if (requestTime > 0) { long timeToRequest = requestTime - now; if (service instanceof AbstractSyncService && timeToRequest <= 0) { service.mRequestTime = 0; service.ping(); } else if (requestTime > 0 && timeToRequest < nextWait) { if (timeToRequest < 11*MINUTES) { nextWait = timeToRequest < 250 ? 250 : timeToRequest; mNextWaitReason = "Sync data change"; } else { log("Illegal timeToRequest: " + timeToRequest); } } } } } } } finally { c.close(); } return nextWait; } static public void serviceRequest(long mailboxId, int reason) { serviceRequest(mailboxId, 5*SECONDS, reason); } static public void serviceRequest(long mailboxId, long ms, int reason) { if (INSTANCE == null) return; Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); // Never allow manual start of Drafts or Outbox via serviceRequest if (m == null || m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) { INSTANCE.log("Ignoring serviceRequest for drafts/outbox"); return; } try { AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.mRequestTime = System.currentTimeMillis() + ms; kick("service request"); } else { startManualSync(mailboxId, reason, null); } } catch (Exception e) { e.printStackTrace(); } } static public void serviceRequestImmediate(long mailboxId) { if (INSTANCE == null) return; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.mRequestTime = System.currentTimeMillis(); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m != null) { service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey); service.mMailbox = m; kick("service request immediate"); } } } static public void partRequest(PartRequest req) { if (INSTANCE == null) return; Message msg = Message.restoreMessageWithId(INSTANCE, req.emailId); if (msg == null) { return; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service == null) { service = startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req); kick("part request"); } else { service.addPartRequest(req); } } static public PartRequest hasPartRequest(long emailId, String part) { if (INSTANCE == null) return null; Message msg = Message.restoreMessageWithId(INSTANCE, emailId); if (msg == null) { return null; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { return service.hasPartRequest(emailId, part); } return null; } static public void cancelPartRequest(long emailId, String part) { Message msg = Message.restoreMessageWithId(INSTANCE, emailId); if (msg == null) { return; } long mailboxId = msg.mMailboxKey; AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId); if (service != null) { service.cancelPartRequest(emailId, part); } } /** * Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in * an error state * * @param mailboxId * @return whether or not the Mailbox is available for syncing (i.e. is a valid push target) */ static public int pingStatus(long mailboxId) { // Already syncing... if (INSTANCE.mServiceMap.get(mailboxId) != null) { return PING_STATUS_RUNNING; } // No errors or a transient error, don't ping... SyncError error = INSTANCE.mSyncErrorMap.get(mailboxId); if (error != null) { if (error.fatal) { return PING_STATUS_UNABLE; } else if (error.holdEndTime > 0) { return PING_STATUS_WAITING; } } return PING_STATUS_OK; } static public AbstractSyncService startManualSync(long mailboxId, int reason, PartRequest req) { if (INSTANCE == null || INSTANCE.mServiceMap == null) return null; synchronized (sSyncToken) { if (INSTANCE.mServiceMap.get(mailboxId) == null) { INSTANCE.mSyncErrorMap.remove(mailboxId); Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (m != null) { INSTANCE.log("Starting sync for " + m.mDisplayName); INSTANCE.startService(m, reason, req); } } } return INSTANCE.mServiceMap.get(mailboxId); } // DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP static private void stopManualSync(long mailboxId) { if (INSTANCE == null || INSTANCE.mServiceMap == null) return; synchronized (sSyncToken) { AbstractSyncService svc = INSTANCE.mServiceMap.get(mailboxId); if (svc != null) { INSTANCE.log("Stopping sync for " + svc.mMailboxName); svc.stop(); svc.mThread.interrupt(); INSTANCE.releaseWakeLock(mailboxId); } } } /** * Wake up SyncManager to check for mailboxes needing service */ static public void kick(String reason) { if (INSTANCE != null) { synchronized (INSTANCE) { INSTANCE.mKicked = true; INSTANCE.notify(); } } if (sConnectivityLock != null) { synchronized (sConnectivityLock) { sConnectivityLock.notify(); } } } static public void accountUpdated(long acctId) { if (INSTANCE == null) return; synchronized (sSyncToken) { for (AbstractSyncService svc : INSTANCE.mServiceMap.values()) { if (svc.mAccount.mId == acctId) { svc.mAccount = Account.restoreAccountWithId(INSTANCE, acctId); } } } } /** * Sent by services indicating that their thread is finished; action depends on the exitStatus * of the service. * * @param svc the service that is finished */ static public void done(AbstractSyncService svc) { if (INSTANCE == null) return; synchronized(sSyncToken) { long mailboxId = svc.mMailboxId; HashMap<Long, SyncError> errorMap = INSTANCE.mSyncErrorMap; SyncError syncError = errorMap.get(mailboxId); INSTANCE.releaseMailbox(mailboxId); int exitStatus = svc.mExitStatus; switch (exitStatus) { case AbstractSyncService.EXIT_DONE: if (!svc.mPartRequests.isEmpty()) { // TODO Handle this case } errorMap.remove(mailboxId); break; case AbstractSyncService.EXIT_IO_ERROR: Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId); if (syncError != null) { syncError.escalate(); INSTANCE.log(m.mDisplayName + " held for " + syncError.holdDelay + "ms"); } else { errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, false)); INSTANCE.log(m.mDisplayName + " added to syncErrorMap, hold for 15s"); } break; case AbstractSyncService.EXIT_LOGIN_FAILURE: case AbstractSyncService.EXIT_EXCEPTION: errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, true)); break; } kick("sync completed"); } } /** * Given the status string from a Mailbox, return the type code for the last sync * @param status the syncStatus column of a Mailbox * @return */ static public int getStatusType(String status) { if (status == null) { return -1; } else { return status.charAt(STATUS_TYPE_CHAR) - '0'; } } /** * Given the status string from a Mailbox, return the change count for the last sync * The change count is the number of adds + deletes + changes in the last sync * @param status the syncStatus column of a Mailbox * @return */ static public int getStatusChangeCount(String status) { try { String s = status.substring(STATUS_CHANGE_COUNT_OFFSET); return Integer.parseInt(s); } catch (RuntimeException e) { return -1; } } static public Context getContext() { return INSTANCE; } }
false
false
null
null
diff --git a/libcore/luni/src/main/java/java/io/ObjectInputStream.java b/libcore/luni/src/main/java/java/io/ObjectInputStream.java index 7dc87ffea..6d24eb282 100644 --- a/libcore/luni/src/main/java/java/io/ObjectInputStream.java +++ b/libcore/luni/src/main/java/java/io/ObjectInputStream.java @@ -1,2765 +1,2771 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.io; // BEGIN android-note // Harmony uses ObjectAccessors to access fields through JNI. Android has not // yet migrated that API. As a consequence, there's a lot of changes here... // END android-note import java.io.EmulatedFields.ObjectSlot; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; // BEGIN android-added import dalvik.system.VMStack; // END android-added // BEGIN android-removed // import org.apache.harmony.misc.accessors.ObjectAccessor; // import org.apache.harmony.misc.accessors.AccessorFactory; // END android-removed import org.apache.harmony.kernel.vm.VM; import org.apache.harmony.luni.internal.nls.Messages; import org.apache.harmony.luni.util.Msg; import org.apache.harmony.luni.util.PriviAction; /** * A specialized {@link InputStream} that is able to read (deserialize) Java * objects as well as primitive data types (int, byte, char etc.). The data has * typically been saved using an ObjectOutputStream. * * @see ObjectOutputStream * @see ObjectInput * @see Serializable * @see Externalizable */ public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants { // BEGIN android-note // this is non-static to avoid sync contention. Would static be faster? // END android-note private InputStream emptyStream = new ByteArrayInputStream( new byte[0]); // To put into objectsRead when reading unsharedObject private static final Object UNSHARED_OBJ = new Object(); // $NON-LOCK-1$ // If the receiver has already read & not consumed a TC code private boolean hasPushbackTC; // Push back TC code if the variable above is true private byte pushbackTC; // How many nested levels to readObject. When we reach 0 we have to validate // the graph then reset it private int nestedLevels; // All objects are assigned an ID (integer handle) private int currentHandle; // Where we read from private DataInputStream input; // Where we read primitive types from private DataInputStream primitiveTypes; // Where we keep primitive type data private InputStream primitiveData = emptyStream; // Resolve object is a mechanism for replacement private boolean enableResolve; // Table mapping Integer (handle) -> Object private HashMap<Integer, Object> objectsRead; // Used by defaultReadObject private Object currentObject; // Used by defaultReadObject private ObjectStreamClass currentClass; // All validations to be executed when the complete graph is read. See inner // type below. private InputValidationDesc[] validations; // Allows the receiver to decide if it needs to call readObjectOverride private boolean subclassOverridingImplementation; // Original caller's class loader, used to perform class lookups private ClassLoader callerClassLoader; // false when reading missing fields private boolean mustResolve = true; // Handle for the current class descriptor private Integer descriptorHandle; private static final HashMap<String, Class<?>> PRIMITIVE_CLASSES = new HashMap<String, Class<?>>(); static { PRIMITIVE_CLASSES.put("byte", byte.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("short", short.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("int", int.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("long", long.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("boolean", boolean.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("char", char.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("float", float.class); //$NON-NLS-1$ PRIMITIVE_CLASSES.put("double", double.class); //$NON-NLS-1$ } // BEGIN android-removed // private ObjectAccessor accessor = AccessorFactory.getObjectAccessor(); // END android-removed // Internal type used to keep track of validators & corresponding priority static class InputValidationDesc { ObjectInputValidation validator; int priority; } /** * GetField is an inner class that provides access to the persistent fields * read from the source stream. */ public abstract static class GetField { /** * Gets the ObjectStreamClass that describes a field. * * @return the descriptor class for a serialized field. */ public abstract ObjectStreamClass getObjectStreamClass(); /** * Indicates if the field identified by {@code name} is defaulted. This * means that it has no value in this stream. * * @param name * the name of the field to check. * @return {@code true} if the field is defaulted, {@code false} * otherwise. * @throws IllegalArgumentException * if {@code name} does not identify a serializable field. * @throws IOException * if an error occurs while reading from the source input * stream. */ public abstract boolean defaulted(String name) throws IOException, IllegalArgumentException; /** * Gets the value of the boolean field identified by {@code name} from * the persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code boolean}. */ public abstract boolean get(String name, boolean defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the character field identified by {@code name} from * the persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code char}. */ public abstract char get(String name, char defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the byte field identified by {@code name} from the * persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code byte}. */ public abstract byte get(String name, byte defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the short field identified by {@code name} from the * persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code short}. */ public abstract short get(String name, short defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the integer field identified by {@code name} from * the persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code int}. */ public abstract int get(String name, int defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the long field identified by {@code name} from the * persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code long}. */ public abstract long get(String name, long defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the float field identified by {@code name} from the * persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code float} is * not {@code char}. */ public abstract float get(String name, float defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the double field identified by {@code name} from * the persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code double}. */ public abstract double get(String name, double defaultValue) throws IOException, IllegalArgumentException; /** * Gets the value of the object field identified by {@code name} from * the persistent field. * * @param name * the name of the field to get. * @param defaultValue * the default value that is used if the field does not have * a value when read from the source stream. * @return the value of the field identified by {@code name}. * @throws IOException * if an error occurs while reading from the source input * stream. * @throws IllegalArgumentException * if the type of the field identified by {@code name} is * not {@code Object}. */ public abstract Object get(String name, Object defaultValue) throws IOException, IllegalArgumentException; } /** * Constructs a new ObjectInputStream. This default constructor can be used * by subclasses that do not want to use the public constructor if it * allocates unneeded data. * * @throws IOException * if an error occurs when creating this stream. * @throws SecurityException * if a security manager is installed and it denies subclassing * this class. * @see SecurityManager#checkPermission(java.security.Permission) */ protected ObjectInputStream() throws IOException, SecurityException { super(); SecurityManager currentManager = System.getSecurityManager(); if (currentManager != null) { currentManager.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); } // WARNING - we should throw IOException if not called from a subclass // according to the JavaDoc. Add the test. this.subclassOverridingImplementation = true; } /** * Constructs a new ObjectInputStream that reads from the InputStream * {@code input}. * * @param input * the non-null source InputStream to filter reads on. * @throws IOException * if an error occurs while reading the stream header. * @throws StreamCorruptedException * if the source stream does not contain serialized objects that * can be read. * @throws SecurityException * if a security manager is installed and it denies subclassing * this class. */ public ObjectInputStream(InputStream input) throws StreamCorruptedException, IOException { final Class<?> implementationClass = getClass(); final Class<?> thisClass = ObjectInputStream.class; SecurityManager sm = System.getSecurityManager(); if (sm != null && implementationClass != thisClass) { boolean mustCheck = (AccessController .doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { try { Method method = implementationClass .getMethod( "readFields", //$NON-NLS-1$ ObjectStreamClass.EMPTY_CONSTRUCTOR_PARAM_TYPES); if (method.getDeclaringClass() != thisClass) { return Boolean.TRUE; } } catch (NoSuchMethodException e) { } try { Method method = implementationClass .getMethod( "readUnshared", //$NON-NLS-1$ ObjectStreamClass.EMPTY_CONSTRUCTOR_PARAM_TYPES); if (method.getDeclaringClass() != thisClass) { return Boolean.TRUE; } } catch (NoSuchMethodException e) { } return Boolean.FALSE; } })).booleanValue(); if (mustCheck) { sm .checkPermission(ObjectStreamConstants.SUBCLASS_IMPLEMENTATION_PERMISSION); } } this.input = (input instanceof DataInputStream) ? (DataInputStream) input : new DataInputStream(input); primitiveTypes = new DataInputStream(this); enableResolve = false; this.subclassOverridingImplementation = false; resetState(); nestedLevels = 0; // So read...() methods can be used by // subclasses during readStreamHeader() primitiveData = this.input; // Has to be done here according to the specification readStreamHeader(); primitiveData = emptyStream; } /** * Returns the number of bytes of primitive data that can be read from this * stream without blocking. This method should not be used at any arbitrary * position; just when reading primitive data types (int, char etc). * * @return the number of available primitive data bytes. * @throws IOException * if any I/O problem occurs while computing the available * bytes. */ @Override public int available() throws IOException { // returns 0 if next data is an object, or N if reading primitive types checkReadPrimitiveTypes(); return primitiveData.available(); } /** * Checks to if it is ok to read primitive types from this stream at * this point. One is not supposed to read primitive types when about to * read an object, for example, so an exception has to be thrown. * * @throws IOException * If any IO problem occurred when trying to read primitive type * or if it is illegal to read primitive types */ private void checkReadPrimitiveTypes() throws IOException { // If we still have primitive data, it is ok to read primitive data if (primitiveData == input || primitiveData.available() > 0) { return; } // If we got here either we had no Stream previously created or // we no longer have data in that one, so get more bytes do { int next = 0; if (hasPushbackTC) { hasPushbackTC = false; } else { next = input.read(); pushbackTC = (byte) next; } switch (pushbackTC) { case TC_BLOCKDATA: primitiveData = new ByteArrayInputStream(readBlockData()); return; case TC_BLOCKDATALONG: primitiveData = new ByteArrayInputStream( readBlockDataLong()); return; case TC_RESET: resetState(); break; default: if (next != -1) { pushbackTC(); } return; } // Only TC_RESET falls through } while (true); } /** * Closes this stream. This implementation closes the source stream. * * @throws IOException * if an error occurs while closing this stream. */ @Override public void close() throws IOException { input.close(); } /** * Default method to read objects from this stream. Serializable fields * defined in the object's class and superclasses are read from the source * stream. * * @throws ClassNotFoundException * if the object's class cannot be found. * @throws IOException * if an I/O error occurs while reading the object data. * @throws NotActiveException * if this method is not called from {@code readObject()}. * @see ObjectOutputStream#defaultWriteObject */ public void defaultReadObject() throws IOException, ClassNotFoundException, NotActiveException { // We can't be called from just anywhere. There are rules. if (currentObject != null || !mustResolve) { readFieldValues(currentObject, currentClass); } else { throw new NotActiveException(); } } /** * Enables object replacement for this stream. By default this is not * enabled. Only trusted subclasses (loaded with system class loader) are * allowed to change this status. * * @param enable * {@code true} to enable object replacement; {@code false} to * disable it. * @return the previous setting. * @throws SecurityException * if a security manager is installed and it denies enabling * object replacement for this stream. * @see #resolveObject * @see ObjectOutputStream#enableReplaceObject */ protected boolean enableResolveObject(boolean enable) throws SecurityException { if (enable) { // The Stream has to be trusted for this feature to be enabled. // trusted means the stream's classloader has to be null SecurityManager currentManager = System.getSecurityManager(); if (currentManager != null) { currentManager.checkPermission(SUBSTITUTION_PERMISSION); } } boolean originalValue = enableResolve; enableResolve = enable; return originalValue; } /** * Checks if two classes belong to the same package. * * @param c1 * one of the classes to test. * @param c2 * the other class to test. * @return {@code true} if the two classes belong to the same package, * {@code false} otherwise. */ private boolean inSamePackage(Class<?> c1, Class<?> c2) { String nameC1 = c1.getName(); String nameC2 = c2.getName(); int indexDotC1 = nameC1.lastIndexOf('.'); int indexDotC2 = nameC2.lastIndexOf('.'); if (indexDotC1 != indexDotC2) { return false; // cannot be in the same package if indices are not } // the same if (indexDotC1 < 0) { return true; // both of them are in default package } return nameC1.substring(0, indexDotC1).equals( nameC2.substring(0, indexDotC2)); } // BEGIN android-added /** * Create and return a new instance of class {@code instantiationClass} * but running the constructor defined in class * {@code constructorClass} (same as {@code instantiationClass} * or a superclass). * * Has to be native to avoid visibility rules and to be able to have * {@code instantiationClass} not the same as * {@code constructorClass} (no such API in java.lang.reflect). * * @param instantiationClass * The new object will be an instance of this class * @param constructorClass * The empty constructor to run will be in this class * @return the object created from {@code instantiationClass} */ private static native Object newInstance(Class<?> instantiationClass, Class<?> constructorClass); // END android-added /** * Return the next {@code int} handle to be used to indicate cyclic * references being loaded from the stream. * * @return the next handle to represent the next cyclic reference */ private Integer nextHandle() { return Integer.valueOf(this.currentHandle++); } /** * Return the next token code (TC) from the receiver, which indicates what * kind of object follows * * @return the next TC from the receiver * * @throws IOException * If an IO error occurs * * @see ObjectStreamConstants */ private byte nextTC() throws IOException { if (hasPushbackTC) { hasPushbackTC = false; // We are consuming it } else { // Just in case a later call decides to really push it back, // we don't require the caller to pass it as parameter pushbackTC = input.readByte(); } return pushbackTC; } /** * Pushes back the last TC code read */ private void pushbackTC() { hasPushbackTC = true; } /** * Reads a single byte from the source stream and returns it as an integer * in the range from 0 to 255. Returns -1 if the end of the source stream * has been reached. Blocks if no input is available. * * @return the byte read or -1 if the end of the source stream has been * reached. * @throws IOException * if an error occurs while reading from this stream. */ @Override public int read() throws IOException { checkReadPrimitiveTypes(); return primitiveData.read(); } /** * Reads at most {@code length} bytes from the source stream and stores them * in byte array {@code buffer} starting at offset {@code count}. Blocks * until {@code count} bytes have been read, the end of the source stream is * detected or an exception is thrown. * * @param buffer * the array in which to store the bytes read. * @param offset * the initial position in {@code buffer} to store the bytes * read from the source stream. * @param length * the maximum number of bytes to store in {@code buffer}. * @return the number of bytes read or -1 if the end of the source input * stream has been reached. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code length < 0}, or if * {@code offset + length} is greater than the length of * {@code buffer}. * @throws IOException * if an error occurs while reading from this stream. * @throws NullPointerException * if {@code buffer} is {@code null}. */ @Override public int read(byte[] buffer, int offset, int length) throws IOException { // BEGIN android-changed if (buffer == null) { throw new NullPointerException(Msg.getString("K0047")); //$NON-NLS-1$ } // avoid int overflow // Exception priorities (in case of multiple errors) differ from // RI, but are spec-compliant. // removed redundant check, used (offset | length) < 0 instead of // (offset < 0) || (length < 0) to safe one operation if ((offset | length) < 0 || length > buffer.length - offset) { throw new ArrayIndexOutOfBoundsException(Msg.getString("K002f")); //$NON-NLS-1$ } // END android-changed if (length == 0) { return 0; } checkReadPrimitiveTypes(); return primitiveData.read(buffer, offset, length); } /** * Reads and returns an array of raw bytes with primitive data. The array * will have up to 255 bytes. The primitive data will be in the format * described by {@code DataOutputStream}. * * @return The primitive data read, as raw bytes * * @throws IOException * If an IO exception happened when reading the primitive data. */ private byte[] readBlockData() throws IOException { byte[] result = new byte[input.readByte() & 0xff]; input.readFully(result); return result; } /** * Reads and returns an array of raw bytes with primitive data. The array * will have more than 255 bytes. The primitive data will be in the format * described by {@code DataOutputStream}. * * @return The primitive data read, as raw bytes * * @throws IOException * If an IO exception happened when reading the primitive data. */ private byte[] readBlockDataLong() throws IOException { byte[] result = new byte[input.readInt()]; input.readFully(result); return result; } /** * Reads a boolean from the source stream. * * @return the boolean value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public boolean readBoolean() throws IOException { return primitiveTypes.readBoolean(); } /** * Reads a byte (8 bit) from the source stream. * * @return the byte value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public byte readByte() throws IOException { return primitiveTypes.readByte(); } /** * Reads a character (16 bit) from the source stream. * * @return the char value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public char readChar() throws IOException { return primitiveTypes.readChar(); } /** * Reads and discards block data and objects until TC_ENDBLOCKDATA is found. * * @throws IOException * If an IO exception happened when reading the optional class * annotation. * @throws ClassNotFoundException * If the class corresponding to the class descriptor could not * be found. */ private void discardData() throws ClassNotFoundException, IOException { primitiveData = emptyStream; boolean resolve = mustResolve; mustResolve = false; do { byte tc = nextTC(); if (tc == TC_ENDBLOCKDATA) { mustResolve = resolve; return; // End of annotation } readContent(tc); } while (true); } /** * Reads a class descriptor (an {@code ObjectStreamClass}) from the * stream. * * @return the class descriptor read from the stream * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws ClassNotFoundException * If the class corresponding to the class descriptor could not * be found. */ private ObjectStreamClass readClassDesc() throws ClassNotFoundException, IOException { byte tc = nextTC(); switch (tc) { case TC_CLASSDESC: return readNewClassDesc(false); case TC_PROXYCLASSDESC: Class<?> proxyClass = readNewProxyClassDesc(); ObjectStreamClass streamClass = ObjectStreamClass .lookup(proxyClass); streamClass.setLoadFields(new ObjectStreamField[0]); registerObjectRead(streamClass, nextHandle(), false); checkedSetSuperClassDesc(streamClass, readClassDesc()); return streamClass; case TC_REFERENCE: return (ObjectStreamClass) readCyclicReference(); case TC_NULL: return null; default: throw new StreamCorruptedException(Msg.getString( "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$ } } /** * Reads the content of the receiver based on the previously read token * {@code tc}. * * @param tc * The token code for the next item in the stream * @return the object read from the stream * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws ClassNotFoundException * If the class corresponding to the object being read could not * be found. */ private Object readContent(byte tc) throws ClassNotFoundException, IOException { switch (tc) { case TC_BLOCKDATA: return readBlockData(); case TC_BLOCKDATALONG: return readBlockDataLong(); case TC_CLASS: return readNewClass(false); case TC_CLASSDESC: return readNewClassDesc(false); case TC_ARRAY: return readNewArray(false); case TC_OBJECT: return readNewObject(false); case TC_STRING: return readNewString(false); case TC_LONGSTRING: return readNewLongString(false); case TC_REFERENCE: return readCyclicReference(); case TC_NULL: return null; case TC_EXCEPTION: Exception exc = readException(); throw new WriteAbortedException(Msg.getString("K00d3"), exc); //$NON-NLS-1$ case TC_RESET: resetState(); return null; default: throw new StreamCorruptedException(Msg.getString( "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$ } } /** * Reads the content of the receiver based on the previously read token * {@code tc}. Primitive data content is considered an error. * * @param unshared * read the object unshared * @return the object read from the stream * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws ClassNotFoundException * If the class corresponding to the object being read could not * be found. */ private Object readNonPrimitiveContent(boolean unshared) throws ClassNotFoundException, IOException { checkReadPrimitiveTypes(); if (primitiveData.available() > 0) { OptionalDataException e = new OptionalDataException(); e.length = primitiveData.available(); throw e; } do { byte tc = nextTC(); switch (tc) { case TC_CLASS: return readNewClass(unshared); case TC_CLASSDESC: return readNewClassDesc(unshared); case TC_ARRAY: return readNewArray(unshared); case TC_OBJECT: return readNewObject(unshared); case TC_STRING: return readNewString(unshared); case TC_LONGSTRING: return readNewLongString(unshared); case TC_ENUM: return readEnum(unshared); case TC_REFERENCE: if (unshared) { readNewHandle(); throw new InvalidObjectException(Msg.getString("KA002")); //$NON-NLS-1$ } return readCyclicReference(); case TC_NULL: return null; case TC_EXCEPTION: Exception exc = readException(); throw new WriteAbortedException(Msg.getString("K00d3"), exc); //$NON-NLS-1$ case TC_RESET: resetState(); break; case TC_ENDBLOCKDATA: // Can occur reading class annotation pushbackTC(); OptionalDataException e = new OptionalDataException(); e.eof = true; throw e; default: throw new StreamCorruptedException(Msg.getString( "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$ } // Only TC_RESET falls through } while (true); } /** * Reads the next item from the stream assuming it is a cyclic reference to * an object previously read. Return the actual object previously read. * * @return the object previously read from the stream * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws InvalidObjectException * If the cyclic reference is not valid. */ private Object readCyclicReference() throws InvalidObjectException, IOException { return registeredObjectRead(readNewHandle()); } /** * Reads a double (64 bit) from the source stream. * * @return the double value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public double readDouble() throws IOException { return primitiveTypes.readDouble(); } /** * Read the next item assuming it is an exception. The exception is not a * regular instance in the object graph, but the exception instance that * happened (if any) when dumping the original object graph. The set of seen * objects will be reset just before and just after loading this exception * object. * <p> * When exceptions are found normally in the object graph, they are loaded * as a regular object, and not by this method. In that case, the set of * "known objects" is not reset. * * @return the exception read * * @throws IOException * If an IO exception happened when reading the exception * object. * @throws ClassNotFoundException * If a class could not be found when reading the object graph * for the exception * @throws OptionalDataException * If optional data could not be found when reading the * exception graph * @throws WriteAbortedException * If another exception was caused when dumping this exception */ private Exception readException() throws WriteAbortedException, OptionalDataException, ClassNotFoundException, IOException { resetSeenObjects(); // Now we read the Throwable object that was saved // WARNING - the grammar says it is a Throwable, but the // WriteAbortedException constructor takes an Exception. So, we read an // Exception from the stream Exception exc = (Exception) readObject(); // We reset the receiver's state (the grammar has "reset" in normal // font) resetSeenObjects(); return exc; } /** * Reads a collection of field descriptors (name, type name, etc) for the * class descriptor {@code cDesc} (an {@code ObjectStreamClass}) * * @param cDesc * The class descriptor (an {@code ObjectStreamClass}) * for which to write field information * * @throws IOException * If an IO exception happened when reading the field * descriptors. * @throws ClassNotFoundException * If a class for one of the field types could not be found * * @see #readObject() */ private void readFieldDescriptors(ObjectStreamClass cDesc) throws ClassNotFoundException, IOException { short numFields = input.readShort(); ObjectStreamField[] fields = new ObjectStreamField[numFields]; // We set it now, but each element will be inserted in the array further // down cDesc.setLoadFields(fields); // Check ObjectOutputStream.writeFieldDescriptors for (short i = 0; i < numFields; i++) { char typecode = (char) input.readByte(); String fieldName = input.readUTF(); boolean isPrimType = ObjectStreamClass.isPrimitiveType(typecode); String classSig; if (isPrimType) { classSig = String.valueOf(typecode); } else { // The spec says it is a UTF, but experience shows they dump // this String using writeObject (unlike the field name, which // is saved with writeUTF). // And if resolveObject is enabled, the classSig may be modified // so that the original class descriptor cannot be read // properly, so it is disabled. boolean old = enableResolve; try { enableResolve = false; classSig = (String) readObject(); } finally { enableResolve = old; } } classSig = formatClassSig(classSig); ObjectStreamField f = new ObjectStreamField(classSig, fieldName); fields[i] = f; } } /* * Format the class signature for ObjectStreamField, for example, * "[L[Ljava.lang.String;;" is converted to "[Ljava.lang.String;" */ private static String formatClassSig(String classSig) { int start = 0; int end = classSig.length(); if (end <= 0) { return classSig; } while (classSig.startsWith("[L", start) //$NON-NLS-1$ && classSig.charAt(end - 1) == ';') { start += 2; end--; } if (start > 0) { start -= 2; end++; return classSig.substring(start, end); } return classSig; } /** * Reads the persistent fields of the object that is currently being read * from the source stream. The values read are stored in a GetField object * that provides access to the persistent fields. This GetField object is * then returned. * * @return the GetField object from which persistent fields can be accessed * by name. * @throws ClassNotFoundException * if the class of an object being deserialized can not be * found. * @throws IOException * if an error occurs while reading from this stream. * @throws NotActiveException * if this stream is currently not reading an object. */ public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { // We can't be called from just anywhere. There are rules. if (currentObject == null) { throw new NotActiveException(); } EmulatedFieldsForLoading result = new EmulatedFieldsForLoading( currentClass); readFieldValues(result); return result; } /** * Reads a collection of field values for the emulated fields * {@code emulatedFields} * * @param emulatedFields * an {@code EmulatedFieldsForLoading}, concrete subclass * of {@code GetField} * * @throws IOException * If an IO exception happened when reading the field values. * @throws InvalidClassException * If an incompatible type is being assigned to an emulated * field. * @throws OptionalDataException * If optional data could not be found when reading the * exception graph * * @see #readFields * @see #readObject() */ private void readFieldValues(EmulatedFieldsForLoading emulatedFields) throws OptionalDataException, InvalidClassException, IOException { EmulatedFields.ObjectSlot[] slots = emulatedFields.emulatedFields() .slots(); for (ObjectSlot element : slots) { element.defaulted = false; Class<?> type = element.field.getType(); if (type == Integer.TYPE) { element.fieldValue = Integer.valueOf(input.readInt()); } else if (type == Byte.TYPE) { element.fieldValue = Byte.valueOf(input.readByte()); } else if (type == Character.TYPE) { element.fieldValue = Character.valueOf(input.readChar()); } else if (type == Short.TYPE) { element.fieldValue = Short.valueOf(input.readShort()); } else if (type == Boolean.TYPE) { element.fieldValue = Boolean.valueOf(input.readBoolean()); } else if (type == Long.TYPE) { element.fieldValue = Long.valueOf(input.readLong()); } else if (type == Float.TYPE) { element.fieldValue = Float.valueOf(input.readFloat()); } else if (type == Double.TYPE) { element.fieldValue = Double.valueOf(input.readDouble()); } else { // Either array or Object try { element.fieldValue = readObject(); } catch (ClassNotFoundException cnf) { // WARNING- Not sure this is the right thing to do. Write // test case. throw new InvalidClassException(cnf.toString()); } } } } /** * Reads a collection of field values for the class descriptor * {@code classDesc} (an {@code ObjectStreamClass}). The * values will be used to set instance fields in object {@code obj}. * This is the default mechanism, when emulated fields (an * {@code GetField}) are not used. Actual values to load are stored * directly into the object {@code obj}. * * @param obj * Instance in which the fields will be set. * @param classDesc * A class descriptor (an {@code ObjectStreamClass}) * defining which fields should be loaded. * * @throws IOException * If an IO exception happened when reading the field values. * @throws InvalidClassException * If an incompatible type is being assigned to an emulated * field. * @throws OptionalDataException * If optional data could not be found when reading the * exception graph * @throws ClassNotFoundException * If a class of an object being de-serialized can not be found * * @see #readFields * @see #readObject() */ private void readFieldValues(Object obj, ObjectStreamClass classDesc) throws OptionalDataException, ClassNotFoundException, IOException { // Now we must read all fields and assign them to the receiver ObjectStreamField[] fields = classDesc.getLoadFields(); fields = (null == fields ? new ObjectStreamField[] {} : fields); Class<?> declaringClass = classDesc.forClass(); if (declaringClass == null && mustResolve) { throw new ClassNotFoundException(classDesc.getName()); } for (ObjectStreamField fieldDesc : fields) { // BEGIN android-removed // // get associated Field // long fieldID = fieldDesc.getFieldID(accessor, declaringClass); // END android-removed // Code duplication starts, just because Java is typed if (fieldDesc.isPrimitive()) { try { // BEGIN android-changed switch (fieldDesc.getTypeCode()) { case 'B': setField(obj, declaringClass, fieldDesc.getName(), input.readByte()); break; case 'C': setField(obj, declaringClass, fieldDesc.getName(), input.readChar()); break; case 'D': setField(obj, declaringClass, fieldDesc.getName(), input.readDouble()); break; case 'F': setField(obj, declaringClass, fieldDesc.getName(), input.readFloat()); break; case 'I': setField(obj, declaringClass, fieldDesc.getName(), input.readInt()); break; case 'J': setField(obj, declaringClass, fieldDesc.getName(), input.readLong()); break; case 'S': setField(obj, declaringClass, fieldDesc.getName(), input.readShort()); break; case 'Z': setField(obj, declaringClass, fieldDesc.getName(), input.readBoolean()); break; default: throw new StreamCorruptedException(Msg.getString( "K00d5", fieldDesc.getTypeCode())); //$NON-NLS-1$ } // END android-changed } catch (NoSuchFieldError err) { } } else { // Object type (array included). String fieldName = fieldDesc.getName(); boolean setBack = false; // BEGIN android-added ObjectStreamField field = classDesc.getField(fieldName); // END android-added if (mustResolve && fieldDesc == null) { setBack = true; mustResolve = false; } Object toSet; if (fieldDesc != null && fieldDesc.isUnshared()) { toSet = readUnshared(); } else { toSet = readObject(); } if (setBack) { mustResolve = true; } if (fieldDesc != null) { if (toSet != null) { - Class<?> fieldType = fieldDesc.getType(); + // BEGIN android-changed + // Get the field type from the local field rather than + // from the stream's supplied data. That's the field + // we'll be setting, so that's the one that needs to be + // validated. + Class<?> fieldType = field.getTypeInternal(); + // END android-added Class<?> valueType = toSet.getClass(); if (!fieldType.isAssignableFrom(valueType)) { throw new ClassCastException(Msg.getString( "K00d4", new String[] { //$NON-NLS-1$ fieldType.toString(), valueType.toString(), classDesc.getName() + "." //$NON-NLS-1$ + fieldName })); } try { // BEGIN android-changed objSetField(obj, declaringClass, fieldName, field .getTypeString(), toSet); // END android-changed } catch (NoSuchFieldError e) { // Ignored } } } } } } /** * Reads a float (32 bit) from the source stream. * * @return the float value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public float readFloat() throws IOException { return primitiveTypes.readFloat(); } /** * Reads bytes from the source stream into the byte array {@code buffer}. * This method will block until {@code buffer.length} bytes have been read. * * @param buffer * the array in which to store the bytes read. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public void readFully(byte[] buffer) throws IOException { primitiveTypes.readFully(buffer); } /** * Reads bytes from the source stream into the byte array {@code buffer}. * This method will block until {@code length} number of bytes have been * read. * * @param buffer * the byte array in which to store the bytes read. * @param offset * the initial position in {@code buffer} to store the bytes * read from the source stream. * @param length * the maximum number of bytes to store in {@code buffer}. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public void readFully(byte[] buffer, int offset, int length) throws IOException { primitiveTypes.readFully(buffer, offset, length); } /** * Walks the hierarchy of classes described by class descriptor * {@code classDesc} and reads the field values corresponding to * fields declared by the corresponding class descriptor. The instance to * store field values into is {@code object}. If the class * (corresponding to class descriptor {@code classDesc}) defines * private instance method {@code readObject} it will be used to load * field values. * * @param object * Instance into which stored field values loaded. * @param classDesc * A class descriptor (an {@code ObjectStreamClass}) * defining which fields should be loaded. * * @throws IOException * If an IO exception happened when reading the field values in * the hierarchy. * @throws ClassNotFoundException * If a class for one of the field types could not be found * @throws NotActiveException * If {@code defaultReadObject} is called from the wrong * context. * * @see #defaultReadObject * @see #readObject() */ private void readHierarchy(Object object, ObjectStreamClass classDesc) throws IOException, ClassNotFoundException, NotActiveException { // We can't be called from just anywhere. There are rules. if (object == null && mustResolve) { throw new NotActiveException(); } ArrayList<ObjectStreamClass> streamClassList = new ArrayList<ObjectStreamClass>( 32); ObjectStreamClass nextStreamClass = classDesc; while (nextStreamClass != null) { streamClassList.add(0, nextStreamClass); nextStreamClass = nextStreamClass.getSuperclass(); } if (object == null) { Iterator<ObjectStreamClass> streamIt = streamClassList.iterator(); while (streamIt.hasNext()) { ObjectStreamClass streamClass = streamIt.next(); readObjectForClass(null, streamClass); } } else { ArrayList<Class<?>> classList = new ArrayList<Class<?>>(32); Class<?> nextClass = object.getClass(); while (nextClass != null) { Class<?> testClass = nextClass.getSuperclass(); if (testClass != null) { classList.add(0, nextClass); } nextClass = testClass; } int lastIndex = 0; for (int i = 0; i < classList.size(); i++) { Class<?> superclass = classList.get(i); int index = findStreamSuperclass(superclass, streamClassList, lastIndex); if (index == -1) { readObjectNoData(object, superclass, ObjectStreamClass.lookupStreamClass(superclass)); } else { for (int j = lastIndex; j <= index; j++) { readObjectForClass(object, streamClassList.get(j)); } lastIndex = index + 1; } } } } private int findStreamSuperclass(Class<?> cl, ArrayList<ObjectStreamClass> classList, int lastIndex) { ObjectStreamClass objCl; String forName; for (int i = lastIndex; i < classList.size(); i++) { objCl = classList.get(i); forName = objCl.forClass().getName(); if (objCl.getName().equals(forName)) { if (cl.getName().equals(objCl.getName())) { return i; } } else { // there was a class replacement if (cl.getName().equals(forName)) { return i; } } } return -1; } private void readObjectNoData(Object object, Class<?> cl, ObjectStreamClass classDesc) throws ObjectStreamException { if (!classDesc.isSerializable()) { return; } if (classDesc.hasMethodReadObjectNoData()){ final Method readMethod = classDesc.getMethodReadObjectNoData(); try { readMethod.invoke(object, new Object[0]); } catch (InvocationTargetException e) { Throwable ex = e.getTargetException(); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else if (ex instanceof Error) { throw (Error) ex; } throw (ObjectStreamException) ex; } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } } private void readObjectForClass(Object object, ObjectStreamClass classDesc) throws IOException, ClassNotFoundException, NotActiveException { // Have to do this before calling defaultReadObject or anything that // calls defaultReadObject currentObject = object; currentClass = classDesc; boolean hadWriteMethod = (classDesc.getFlags() & SC_WRITE_METHOD) > 0; Class<?> targetClass = classDesc.forClass(); final Method readMethod; if (targetClass == null || !mustResolve) { readMethod = null; } else { readMethod = classDesc.getMethodReadObject(); } try { if (readMethod != null) { // We have to be able to fetch its value, even if it is private AccessController.doPrivileged(new PriviAction<Object>( readMethod)); try { readMethod.invoke(object, new Object[] { this }); } catch (InvocationTargetException e) { Throwable ex = e.getTargetException(); if (ex instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex; } else if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else if (ex instanceof Error) { throw (Error) ex; } throw (IOException) ex; } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } else { defaultReadObject(); } if (hadWriteMethod) { discardData(); } } finally { // Cleanup, needs to run always so that we can later detect invalid // calls to defaultReadObject currentObject = null; // We did not set this, so we do not need to // clean it currentClass = null; } } /** * Reads an integer (32 bit) from the source stream. * * @return the integer value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public int readInt() throws IOException { return primitiveTypes.readInt(); } /** * Reads the next line from the source stream. Lines are terminated by * {@code '\r'}, {@code '\n'}, {@code "\r\n"} or an {@code EOF}. * * @return the string read from the source stream. * @throws IOException * if an error occurs while reading from the source stream. * @deprecated Use {@link BufferedReader} */ @Deprecated public String readLine() throws IOException { return primitiveTypes.readLine(); } /** * Reads a long (64 bit) from the source stream. * * @return the long value read from the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public long readLong() throws IOException { return primitiveTypes.readLong(); } /** * Read a new array from the receiver. It is assumed the array has not been * read yet (not a cyclic reference). Return the array read. * * @param unshared * read the object unshared * @return the array read * * @throws IOException * If an IO exception happened when reading the array. * @throws ClassNotFoundException * If a class for one of the objects could not be found * @throws OptionalDataException * If optional data could not be found when reading the array. */ private Object readNewArray(boolean unshared) throws OptionalDataException, ClassNotFoundException, IOException { ObjectStreamClass classDesc = readClassDesc(); if (classDesc == null) { throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$ } Integer newHandle = nextHandle(); // Array size int size = input.readInt(); Class<?> arrayClass = classDesc.forClass(); Class<?> componentType = arrayClass.getComponentType(); Object result = Array.newInstance(componentType, size); registerObjectRead(result, newHandle, unshared); // Now we have code duplication just because Java is typed. We have to // read N elements and assign to array positions, but we must typecast // the array first, and also call different methods depending on the // elements. if (componentType.isPrimitive()) { if (componentType == Integer.TYPE) { int[] intArray = (int[]) result; for (int i = 0; i < size; i++) { intArray[i] = input.readInt(); } } else if (componentType == Byte.TYPE) { byte[] byteArray = (byte[]) result; input.readFully(byteArray, 0, size); } else if (componentType == Character.TYPE) { char[] charArray = (char[]) result; for (int i = 0; i < size; i++) { charArray[i] = input.readChar(); } } else if (componentType == Short.TYPE) { short[] shortArray = (short[]) result; for (int i = 0; i < size; i++) { shortArray[i] = input.readShort(); } } else if (componentType == Boolean.TYPE) { boolean[] booleanArray = (boolean[]) result; for (int i = 0; i < size; i++) { booleanArray[i] = input.readBoolean(); } } else if (componentType == Long.TYPE) { long[] longArray = (long[]) result; for (int i = 0; i < size; i++) { longArray[i] = input.readLong(); } } else if (componentType == Float.TYPE) { float[] floatArray = (float[]) result; for (int i = 0; i < size; i++) { floatArray[i] = input.readFloat(); } } else if (componentType == Double.TYPE) { double[] doubleArray = (double[]) result; for (int i = 0; i < size; i++) { doubleArray[i] = input.readDouble(); } } else { throw new ClassNotFoundException(Msg.getString( "K00d7", classDesc.getName())); //$NON-NLS-1$ } } else { // Array of Objects Object[] objectArray = (Object[]) result; for (int i = 0; i < size; i++) { // TODO: This place is the opportunity for enhancement // We can implement writing elements through fast-path, // without setting up the context (see readObject()) for // each element with public API objectArray[i] = readObject(); } } if (enableResolve) { result = resolveObject(result); registerObjectRead(result, newHandle, false); } return result; } /** * Reads a new class from the receiver. It is assumed the class has not been * read yet (not a cyclic reference). Return the class read. * * @param unshared * read the object unshared * @return The {@code java.lang.Class} read from the stream. * * @throws IOException * If an IO exception happened when reading the class. * @throws ClassNotFoundException * If a class for one of the objects could not be found */ private Class<?> readNewClass(boolean unshared) throws ClassNotFoundException, IOException { ObjectStreamClass classDesc = readClassDesc(); if (classDesc != null) { Class<?> localClass = classDesc.forClass(); if (localClass != null) { registerObjectRead(localClass, nextHandle(), unshared); } return localClass; } throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$ } /* * read class type for Enum, note there's difference between enum and normal * classes */ private ObjectStreamClass readEnumDesc() throws IOException, ClassNotFoundException { byte tc = nextTC(); switch (tc) { case TC_CLASSDESC: return readEnumDescInternal(); case TC_REFERENCE: return (ObjectStreamClass) readCyclicReference(); case TC_NULL: return null; default: throw new StreamCorruptedException(Msg.getString( "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$ } } private ObjectStreamClass readEnumDescInternal() throws IOException, ClassNotFoundException { ObjectStreamClass classDesc; primitiveData = input; Integer oldHandle = descriptorHandle; descriptorHandle = nextHandle(); classDesc = readClassDescriptor(); registerObjectRead(classDesc, descriptorHandle, false); descriptorHandle = oldHandle; primitiveData = emptyStream; classDesc.setClass(resolveClass(classDesc)); // Consume unread class annotation data and TC_ENDBLOCKDATA discardData(); ObjectStreamClass superClass = readClassDesc(); checkedSetSuperClassDesc(classDesc, superClass); // Check SUIDs, note all SUID for Enum is 0L if (0L != classDesc.getSerialVersionUID() || 0L != superClass.getSerialVersionUID()) { throw new InvalidClassException(superClass.getName(), Msg .getString("K00da", superClass, //$NON-NLS-1$ superClass)); } byte tc = nextTC(); // discard TC_ENDBLOCKDATA after classDesc if any if (tc == TC_ENDBLOCKDATA) { // read next parent class. For enum, it may be null superClass.setSuperclass(readClassDesc()); } else { // not TC_ENDBLOCKDATA, push back for next read pushbackTC(); } return classDesc; } @SuppressWarnings("unchecked")// For the Enum.valueOf call private Object readEnum(boolean unshared) throws OptionalDataException, ClassNotFoundException, IOException { // read classdesc for Enum first ObjectStreamClass classDesc = readEnumDesc(); Integer newHandle = nextHandle(); // read name after class desc String name; byte tc = nextTC(); switch (tc) { case TC_REFERENCE: if (unshared) { readNewHandle(); throw new InvalidObjectException(Msg.getString("KA002")); //$NON-NLS-1$ } name = (String) readCyclicReference(); break; case TC_STRING: name = (String) readNewString(unshared); break; default: throw new StreamCorruptedException(Msg.getString("K00d2"));//$NON-NLS-1$ } Enum<?> result = Enum.valueOf((Class) classDesc.forClass(), name); registerObjectRead(result, newHandle, unshared); return result; } /** * Reads a new class descriptor from the receiver. It is assumed the class * descriptor has not been read yet (not a cyclic reference). Return the * class descriptor read. * * @param unshared * read the object unshared * @return The {@code ObjectStreamClass} read from the stream. * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws ClassNotFoundException * If a class for one of the objects could not be found */ private ObjectStreamClass readNewClassDesc(boolean unshared) throws ClassNotFoundException, IOException { // So read...() methods can be used by // subclasses during readClassDescriptor() primitiveData = input; Integer oldHandle = descriptorHandle; descriptorHandle = nextHandle(); ObjectStreamClass newClassDesc = readClassDescriptor(); registerObjectRead(newClassDesc, descriptorHandle, unshared); descriptorHandle = oldHandle; primitiveData = emptyStream; // We need to map classDesc to class. try { newClassDesc.setClass(resolveClass(newClassDesc)); // Check SUIDs & base name of the class verifyAndInit(newClassDesc); } catch (ClassNotFoundException e) { if (mustResolve) { throw e; // Just continue, the class may not be required } } // Resolve the field signatures using the class loader of the // resolved class ObjectStreamField[] fields = newClassDesc.getLoadFields(); fields = (null == fields ? new ObjectStreamField[] {} : fields); ClassLoader loader = newClassDesc.forClass() == null ? callerClassLoader : newClassDesc.forClass().getClassLoader(); for (ObjectStreamField element : fields) { element.resolve(loader); } // Consume unread class annotation data and TC_ENDBLOCKDATA discardData(); checkedSetSuperClassDesc(newClassDesc, readClassDesc()); return newClassDesc; } /** * Reads a new proxy class descriptor from the receiver. It is assumed the * proxy class descriptor has not been read yet (not a cyclic reference). * Return the proxy class descriptor read. * * @return The {@code Class} read from the stream. * * @throws IOException * If an IO exception happened when reading the class * descriptor. * @throws ClassNotFoundException * If a class for one of the objects could not be found */ private Class<?> readNewProxyClassDesc() throws ClassNotFoundException, IOException { int count = input.readInt(); String[] interfaceNames = new String[count]; for (int i = 0; i < count; i++) { interfaceNames[i] = input.readUTF(); } Class<?> proxy = resolveProxyClass(interfaceNames); // Consume unread class annotation data and TC_ENDBLOCKDATA discardData(); return proxy; } /** * Reads a class descriptor from the source stream. * * @return the class descriptor read from the source stream. * @throws ClassNotFoundException * if a class for one of the objects cannot be found. * @throws IOException * if an error occurs while reading from the source stream. */ protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass newClassDesc = new ObjectStreamClass(); String name = input.readUTF(); if (name.length() == 0) { // luni.07 = The stream is corrupted throw new IOException(Messages.getString("luni.07")); //$NON-NLS-1$ } newClassDesc.setName(name); newClassDesc.setSerialVersionUID(input.readLong()); newClassDesc.setFlags(input.readByte()); /* * We must register the class descriptor before reading field * descriptors. If called outside of readObject, the descriptorHandle * might be null. */ descriptorHandle = (null == descriptorHandle ? nextHandle() : descriptorHandle); registerObjectRead(newClassDesc, descriptorHandle, false); readFieldDescriptors(newClassDesc); return newClassDesc; } /** * Creates the proxy class that implements the interfaces specified in * {@code interfaceNames}. * * @param interfaceNames * the interfaces used to create the proxy class. * @return the proxy class. * @throws ClassNotFoundException * if the proxy class or any of the specified interfaces cannot * be created. * @throws IOException * if an error occurs while reading from the source stream. * @see ObjectOutputStream#annotateProxyClass(Class) */ protected Class<?> resolveProxyClass(String[] interfaceNames) throws IOException, ClassNotFoundException { // TODO: This method is opportunity for performance enhancement // We can cache the classloader and recently used interfaces. // BEGIN android-changed // ClassLoader loader = VM.getNonBootstrapClassLoader(); ClassLoader loader = ClassLoader.getSystemClassLoader(); // END android-changed Class<?>[] interfaces = new Class<?>[interfaceNames.length]; for (int i = 0; i < interfaceNames.length; i++) { interfaces[i] = Class.forName(interfaceNames[i], false, loader); } try { return Proxy.getProxyClass(loader, interfaces); } catch (IllegalArgumentException e) { throw new ClassNotFoundException(e.toString(), e); } } /** * Write a new handle describing a cyclic reference from the stream. * * @return the handle read * * @throws IOException * If an IO exception happened when reading the handle */ private int readNewHandle() throws IOException { return input.readInt(); } private Class<?> resolveConstructorClass(Class<?> objectClass, boolean wasSerializable, boolean wasExternalizable) throws OptionalDataException, ClassNotFoundException, IOException { // The class of the instance may not be the same as the class of the // constructor to run // This is the constructor to run if Externalizable Class<?> constructorClass = objectClass; // WARNING - What if the object is serializable and externalizable ? // Is that possible ? if (wasSerializable) { // Now we must run the constructor of the class just above the // one that implements Serializable so that slots that were not // dumped can be initialized properly while (constructorClass != null && ObjectStreamClass.isSerializable(constructorClass)) { constructorClass = constructorClass.getSuperclass(); } } // Fetch the empty constructor, or null if none. Constructor<?> constructor = null; if (constructorClass != null) { try { constructor = constructorClass .getDeclaredConstructor(ObjectStreamClass.EMPTY_CONSTRUCTOR_PARAM_TYPES); } catch (NoSuchMethodException nsmEx) { // Ignored } } // Has to have an empty constructor if (constructor == null) { throw new InvalidClassException(constructorClass.getName(), Msg .getString("K00dc")); //$NON-NLS-1$ } int constructorModifiers = constructor.getModifiers(); // Now we must check if the empty constructor is visible to the // instantiation class if (Modifier.isPrivate(constructorModifiers) || (wasExternalizable && !Modifier .isPublic(constructorModifiers))) { throw new InvalidClassException(constructorClass.getName(), Msg .getString("K00dc")); //$NON-NLS-1$ } // We know we are testing from a subclass, so the only other case // where the visibility is not allowed is when the constructor has // default visibility and the instantiation class is in a different // package than the constructor class if (!Modifier.isPublic(constructorModifiers) && !Modifier.isProtected(constructorModifiers)) { // Not public, not private and not protected...means default // visibility. Check if same package if (!inSamePackage(constructorClass, objectClass)) { throw new InvalidClassException(constructorClass.getName(), Msg.getString("K00dc")); //$NON-NLS-1$ } } return constructorClass; } /** * Read a new object from the stream. It is assumed the object has not been * loaded yet (not a cyclic reference). Return the object read. * * If the object implements <code>Externalizable</code> its * <code>readExternal</code> is called. Otherwise, all fields described by * the class hierarchy are loaded. Each class can define how its declared * instance fields are loaded by defining a private method * <code>readObject</code> * * @param unshared * read the object unshared * @return the object read * * @throws IOException * If an IO exception happened when reading the object. * @throws OptionalDataException * If optional data could not be found when reading the object * graph * @throws ClassNotFoundException * If a class for one of the objects could not be found */ private Object readNewObject(boolean unshared) throws OptionalDataException, ClassNotFoundException, IOException { ObjectStreamClass classDesc = readClassDesc(); if (classDesc == null) { throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$ } Integer newHandle = nextHandle(); // Note that these values come from the Stream, and in fact it could be // that the classes have been changed so that the info below now // conflicts with the newer class boolean wasExternalizable = (classDesc.getFlags() & SC_EXTERNALIZABLE) > 0; boolean wasSerializable = (classDesc.getFlags() & SC_SERIALIZABLE) > 0; // Maybe we should cache the values above in classDesc ? It may be the // case that when reading classDesc we may need to read more stuff // depending on the values above Class<?> objectClass = classDesc.forClass(); Object result, registeredResult = null; if (objectClass != null) { // BEGIN android-changed // long constructor = classDesc.getConstructor(); // if (constructor == ObjectStreamClass.CONSTRUCTOR_IS_NOT_RESOLVED) { // constructor = accessor.getMethodID(resolveConstructorClass(objectClass, wasSerializable, wasExternalizable), null, new Class[0]); // classDesc.setConstructor(constructor); // } Class constructorClass = resolveConstructorClass(objectClass, wasSerializable, wasExternalizable); // END android-changed // Now we know which class to instantiate and which constructor to // run. We are allowed to run the constructor. // BEGIN android-changed // result = accessor.newInstance(objectClass, constructor, null); result = newInstance(objectClass, constructorClass); // END android-changed registerObjectRead(result, newHandle, unshared); registeredResult = result; } else { result = null; } try { // This is how we know what to do in defaultReadObject. And it is // also used by defaultReadObject to check if it was called from an // invalid place. It also allows readExternal to call // defaultReadObject and have it work. currentObject = result; currentClass = classDesc; // If Externalizable, just let the object read itself if (wasExternalizable) { boolean blockData = (classDesc.getFlags() & SC_BLOCK_DATA) > 0; if (!blockData) { primitiveData = input; } if (mustResolve) { Externalizable extern = (Externalizable) result; extern.readExternal(this); } if (blockData) { // Similar to readHierarchy. Anything not read by // readExternal has to be consumed here discardData(); } else { primitiveData = emptyStream; } } else { // If we got here, it is Serializable but not Externalizable. // Walk the hierarchy reading each class' slots readHierarchy(result, classDesc); } } finally { // Cleanup, needs to run always so that we can later detect invalid // calls to defaultReadObject currentObject = null; currentClass = null; } if (objectClass != null) { if (classDesc.hasMethodReadResolve()){ Method methodReadResolve = classDesc.getMethodReadResolve(); try { result = methodReadResolve.invoke(result, (Object[]) null); } catch (IllegalAccessException iae) { } catch (InvocationTargetException ite) { Throwable target = ite.getTargetException(); if (target instanceof ObjectStreamException) { throw (ObjectStreamException) target; } else if (target instanceof Error) { throw (Error) target; } else { throw (RuntimeException) target; } } } } // We get here either if class-based replacement was not needed or if it // was needed but produced the same object or if it could not be // computed. // The object to return is the one we instantiated or a replacement for // it if (result != null && enableResolve) { result = resolveObject(result); } if (registeredResult != result) { registerObjectRead(result, newHandle, unshared); } return result; } /** * Read a string encoded in {@link DataInput modified UTF-8} from the * receiver. Return the string read. * * @param unshared * read the object unshared * @return the string just read. * @throws IOException * If an IO exception happened when reading the String. */ private Object readNewString(boolean unshared) throws IOException { Object result = input.readUTF(); if (enableResolve) { result = resolveObject(result); } registerObjectRead(result, nextHandle(), unshared); return result; } /** * Read a new String in UTF format from the receiver. Return the string * read. * * @param unshared * read the object unshared * @return the string just read. * * @throws IOException * If an IO exception happened when reading the String. */ private Object readNewLongString(boolean unshared) throws IOException { long length = input.readLong(); Object result = input.decodeUTF((int) length); if (enableResolve) { result = resolveObject(result); } registerObjectRead(result, nextHandle(), unshared); return result; } /** * Reads the next object from the source stream. * * @return the object read from the source stream. * @throws ClassNotFoundException * if the class of one of the objects in the object graph cannot * be found. * @throws IOException * if an error occurs while reading from the source stream. * @throws OptionalDataException * if primitive data types were found instead of an object. * @see ObjectOutputStream#writeObject(Object) */ public final Object readObject() throws OptionalDataException, ClassNotFoundException, IOException { return readObject(false); } /** * Reads the next unshared object from the source stream. * * @return the new object read. * @throws ClassNotFoundException * if the class of one of the objects in the object graph cannot * be found. * @throws IOException * if an error occurs while reading from the source stream. * @see ObjectOutputStream#writeUnshared */ public Object readUnshared() throws IOException, ClassNotFoundException { return readObject(true); } private Object readObject(boolean unshared) throws OptionalDataException, ClassNotFoundException, IOException { boolean restoreInput = (primitiveData == input); if (restoreInput) { primitiveData = emptyStream; } // This is the spec'ed behavior in JDK 1.2. Very bizarre way to allow // behavior overriding. if (subclassOverridingImplementation && !unshared) { return readObjectOverride(); } // If we still had primitive types to read, should we discard them // (reset the primitiveTypes stream) or leave as is, so that attempts to // read primitive types won't read 'past data' ??? Object result; try { // We need this so we can tell when we are returning to the // original/outside caller if (++nestedLevels == 1) { // Remember the caller's class loader // BEGIN android-changed callerClassLoader = getClosestUserClassLoader(); // END android-changed } result = readNonPrimitiveContent(unshared); if (restoreInput) { primitiveData = input; } } finally { // We need this so we can tell when we are returning to the // original/outside caller if (--nestedLevels == 0) { // We are going to return to the original caller, perform // cleanups. // No more need to remember the caller's class loader callerClassLoader = null; } } // Done reading this object. Is it time to return to the original // caller? If so we need to perform validations first. if (nestedLevels == 0 && validations != null) { // We are going to return to the original caller. If validation is // enabled we need to run them now and then cleanup the validation // collection try { for (InputValidationDesc element : validations) { element.validator.validateObject(); } } finally { // Validations have to be renewed, since they are only called // from readObject validations = null; } } return result; } // BEGIN android-added private static final ClassLoader bootstrapLoader = Object.class.getClassLoader(); private static final ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); /** * Searches up the call stack to find the closest user-defined class loader. * * @return a user-defined class loader or null if one isn't found */ private static ClassLoader getClosestUserClassLoader() { Class<?>[] stackClasses = VMStack.getClasses(-1, false); for (Class<?> stackClass : stackClasses) { ClassLoader loader = stackClass.getClassLoader(); if (loader != null && loader != bootstrapLoader && loader != systemLoader) { return loader; } } return null; } // END android-added /** * Method to be overriden by subclasses to read the next object from the * source stream. * * @return the object read from the source stream. * @throws ClassNotFoundException * if the class of one of the objects in the object graph cannot * be found. * @throws IOException * if an error occurs while reading from the source stream. * @throws OptionalDataException * if primitive data types were found instead of an object. * @see ObjectOutputStream#writeObjectOverride */ protected Object readObjectOverride() throws OptionalDataException, ClassNotFoundException, IOException { if (input == null) { return null; } // Subclasses must override. throw new IOException(); } /** * Reads a short (16 bit) from the source stream. * * @return the short value read from the source stream. * @throws IOException * if an error occurs while reading from the source stream. */ public short readShort() throws IOException { return primitiveTypes.readShort(); } /** * Reads and validates the ObjectInputStream header from the source stream. * * @throws IOException * if an error occurs while reading from the source stream. * @throws StreamCorruptedException * if the source stream does not contain readable serialized * objects. */ protected void readStreamHeader() throws IOException, StreamCorruptedException { if (input.readShort() == STREAM_MAGIC && input.readShort() == STREAM_VERSION) { return; } throw new StreamCorruptedException(); } /** * Reads an unsigned byte (8 bit) from the source stream. * * @return the unsigned byte value read from the source stream packaged in * an integer. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public int readUnsignedByte() throws IOException { return primitiveTypes.readUnsignedByte(); } /** * Reads an unsigned short (16 bit) from the source stream. * * @return the unsigned short value read from the source stream packaged in * an integer. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public int readUnsignedShort() throws IOException { return primitiveTypes.readUnsignedShort(); } /** * Reads a string encoded in {@link DataInput modified UTF-8} from the * source stream. * * @return the string encoded in {@link DataInput modified UTF-8} read from * the source stream. * @throws EOFException * if the end of the input is reached before the read * request can be satisfied. * @throws IOException * if an error occurs while reading from the source stream. */ public String readUTF() throws IOException { return primitiveTypes.readUTF(); } /** * Return the object previously read tagged with handle {@code handle}. * * @param handle * The handle that this object was assigned when it was read. * @return the object previously read. * * @throws InvalidObjectException * If there is no previously read object with this handle */ private Object registeredObjectRead(Integer handle) throws InvalidObjectException { Object res = objectsRead.get(handle); if (res == UNSHARED_OBJ) { throw new InvalidObjectException(Msg.getString("KA010")); //$NON-NLS-1$ } return res; } /** * Assume object {@code obj} has been read, and assign a handle to * it, {@code handle}. * * @param obj * Non-null object being loaded. * @param handle * An Integer, the handle to this object * @param unshared * Boolean, indicates that caller is reading in unshared mode * * @see #nextHandle */ private void registerObjectRead(Object obj, Integer handle, boolean unshared) { objectsRead.put(handle, unshared ? UNSHARED_OBJ : obj); } /** * Registers a callback for post-deserialization validation of objects. It * allows to perform additional consistency checks before the {@code * readObject()} method of this class returns its result to the caller. This * method can only be called from within the {@code readObject()} method of * a class that implements "special" deserialization rules. It can be called * multiple times. Validation callbacks are then done in order of decreasing * priority, defined by {@code priority}. * * @param object * an object that can validate itself by receiving a callback. * @param priority * the validator's priority. * @throws InvalidObjectException * if {@code object} is {@code null}. * @throws NotActiveException * if this stream is currently not reading objects. In that * case, calling this method is not allowed. * @see ObjectInputValidation#validateObject() */ public synchronized void registerValidation(ObjectInputValidation object, int priority) throws NotActiveException, InvalidObjectException { // Validation can only be registered when inside readObject calls Object instanceBeingRead = this.currentObject; // We can't be called from just anywhere. There are rules. if (instanceBeingRead == null && nestedLevels == 0) { throw new NotActiveException(); } if (object == null) { throw new InvalidObjectException(Msg.getString("K00d9")); //$NON-NLS-1$ } // From now on it is just insertion in a SortedCollection. Since // the Java class libraries don't provide that, we have to // implement it from scratch here. InputValidationDesc desc = new InputValidationDesc(); desc.validator = object; desc.priority = priority; // No need for this, validateObject does not take a parameter // desc.toValidate = instanceBeingRead; if (validations == null) { validations = new InputValidationDesc[1]; validations[0] = desc; } else { int i = 0; for (; i < validations.length; i++) { InputValidationDesc validation = validations[i]; // Sorted, higher priority first. if (priority >= validation.priority) { break; // Found the index where to insert } } InputValidationDesc[] oldValidations = validations; int currentSize = oldValidations.length; validations = new InputValidationDesc[currentSize + 1]; System.arraycopy(oldValidations, 0, validations, 0, i); System.arraycopy(oldValidations, i, validations, i + 1, currentSize - i); validations[i] = desc; } } /** * Reset the collection of objects already loaded by the receiver. */ private void resetSeenObjects() { objectsRead = new HashMap<Integer, Object>(); currentHandle = baseWireHandle; primitiveData = emptyStream; } /** * Reset the receiver. The collection of objects already read by the * receiver is reset, and internal structures are also reset so that the * receiver knows it is in a fresh clean state. */ private void resetState() { resetSeenObjects(); hasPushbackTC = false; pushbackTC = 0; // nestedLevels = 0; } /** * Loads the Java class corresponding to the class descriptor {@code * osClass} that has just been read from the source stream. * * @param osClass * an ObjectStreamClass read from the source stream. * @return a Class corresponding to the descriptor {@code osClass}. * @throws ClassNotFoundException * if the class for an object cannot be found. * @throws IOException * if an I/O error occurs while creating the class. * @see ObjectOutputStream#annotateClass(Class) */ protected Class<?> resolveClass(ObjectStreamClass osClass) throws IOException, ClassNotFoundException { // fastpath: obtain cached value Class<?> cls = osClass.forClass(); if (null == cls) { // slowpath: resolve the class String className = osClass.getName(); // if it is primitive class, for example, long.class cls = PRIMITIVE_CLASSES.get(className); if (null == cls) { // not primitive class // Use the first non-null ClassLoader on the stack. If null, use // the system class loader cls = Class.forName(className, true, callerClassLoader); } } return cls; } /** * Allows trusted subclasses to substitute the specified original {@code * object} with a new object. Object substitution has to be activated first * with calling {@code enableResolveObject(true)}. This implementation just * returns {@code object}. * * @param object * the original object for which a replacement may be defined. * @return the replacement object for {@code object}. * @throws IOException * if any I/O error occurs while creating the replacement * object. * @see #enableResolveObject * @see ObjectOutputStream#enableReplaceObject * @see ObjectOutputStream#replaceObject */ protected Object resolveObject(Object object) throws IOException { // By default no object replacement. Subclasses can override return object; } // BEGIN android-added /* * These methods set the value of a field named fieldName of instance. The * field is declared by declaringClass. The field is the same type as the * value parameter. * * these methods could be implemented non-natively on top of * java.lang.reflect at the expense of extra object creation * (java.lang.reflect.Field). Otherwise Serialization could not fetch * private fields, except by the use of a native method like this one. * * @throws NoSuchFieldError If the field does not exist. */ private static native void setField(Object instance, Class<?> declaringClass, String fieldName, byte value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, char value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, double value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, float value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, int value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, long value) throws NoSuchFieldError; private static native void objSetField(Object instance, Class<?> declaringClass, String fieldName, String fieldTypeName, Object value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, short value) throws NoSuchFieldError; private static native void setField(Object instance, Class<?> declaringClass, String fieldName, boolean value) throws NoSuchFieldError; // END android-added /** * Skips {@code length} bytes on the source stream. This method should not * be used to skip bytes at any arbitrary position, just when reading * primitive data types (int, char etc). * * @param length * the number of bytes to skip. * @return the number of bytes actually skipped. * @throws IOException * if an error occurs while skipping bytes on the source stream. * @throws NullPointerException * if the source stream is {@code null}. */ public int skipBytes(int length) throws IOException { // To be used with available. Ok to call if reading primitive buffer if (input == null) { throw new NullPointerException(); } int offset = 0; while (offset < length) { checkReadPrimitiveTypes(); long skipped = primitiveData.skip(length - offset); if (skipped == 0) { return offset; } offset += (int) skipped; } return length; } /** * Verify if the SUID & the base name for descriptor * <code>loadedStreamClass</code>matches * the SUID & the base name of the corresponding loaded class and * init private fields. * * @param loadedStreamClass * An ObjectStreamClass that was loaded from the stream. * * @throws InvalidClassException * If the SUID of the stream class does not match the VM class */ private void verifyAndInit(ObjectStreamClass loadedStreamClass) throws InvalidClassException { Class<?> localClass = loadedStreamClass.forClass(); ObjectStreamClass localStreamClass = ObjectStreamClass .lookupStreamClass(localClass); if (loadedStreamClass.getSerialVersionUID() != localStreamClass .getSerialVersionUID()) { throw new InvalidClassException(loadedStreamClass.getName(), Msg .getString("K00da", loadedStreamClass, //$NON-NLS-1$ localStreamClass)); } String loadedClassBaseName = getBaseName(loadedStreamClass.getName()); String localClassBaseName = getBaseName(localStreamClass.getName()); if (!loadedClassBaseName.equals(localClassBaseName)) { throw new InvalidClassException(loadedStreamClass.getName(), Msg .getString("KA015", loadedClassBaseName, //$NON-NLS-1$ localClassBaseName)); } loadedStreamClass.initPrivateFields(localStreamClass); } private static String getBaseName(String fullName) { int k = fullName.lastIndexOf('.'); if (k == -1 || k == (fullName.length() - 1)) { return fullName; } return fullName.substring(k + 1); } // Avoid recursive defining. private static void checkedSetSuperClassDesc(ObjectStreamClass desc, ObjectStreamClass superDesc) throws StreamCorruptedException { if (desc.equals(superDesc)) { throw new StreamCorruptedException(); } desc.setSuperclass(superDesc); } }
true
false
null
null
diff --git a/src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java b/src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java index 994c5b1..2802879 100644 --- a/src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java +++ b/src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java @@ -1,575 +1,580 @@ package org.agmip.translators.dssat; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.agmip.translators.dssat.DssatCommonInput.getSectionDataWithNocopy; import static org.agmip.translators.dssat.DssatCommonOutput.revisePath; import static org.agmip.util.MapUtil.*; import org.agmip.util.MapUtil.BucketEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Meng Zhang */ public class DssatControllerOutput extends DssatCommonOutput { private HashMap<String, File> files = new HashMap(); private ArrayList<Future<File>> futFiles = new ArrayList(); // private HashMap<String, Future<File>> soilFiles = new HashMap(); // private HashMap<String, Future<File>> wthFiles = new HashMap(); private HashMap<String, Map> soilData = new HashMap(); private HashMap<String, Map> wthData = new HashMap(); private ExecutorService executor = Executors.newFixedThreadPool(64); private static final Logger LOG = LoggerFactory.getLogger(DssatControllerOutput.class); + + public DssatControllerOutput() { + soilHelper = new DssatSoilFileHelper(); + wthHelper = new DssatWthFileHelper(); + } /** * ALL DSSAT Data Output method * * @param arg0 file output path * @param result data holder object * * @throws FileNotFoundException * @throws IOException */ private void writeMultipleExp(String arg0, Map result) throws FileNotFoundException, IOException { arg0 = revisePath(arg0); ArrayList<HashMap> expArr = getObjectOr(result, "experiments", new ArrayList()); HashMap expData; ArrayList<HashMap> soilArr = getObjectOr(result, "soils", new ArrayList()); ArrayList<HashMap> wthArr = getObjectOr(result, "weathers", new ArrayList()); // Setup output file Calendar cal = Calendar.getInstance(); if (!expArr.isEmpty() && soilArr.isEmpty() && wthArr.isEmpty()) { outputFile = new File(arg0 + "AGMIP_DSSAT_EXPERIMENTS_" + cal.getTimeInMillis() + ".zip"); } else if (expArr.isEmpty() && !soilArr.isEmpty() && wthArr.isEmpty()) { outputFile = new File(arg0 + "AGMIP_DSSAT_SOILS_" + cal.getTimeInMillis() + ".zip"); } else if (expArr.isEmpty() && soilArr.isEmpty() && !wthArr.isEmpty()) { outputFile = new File(arg0 + "AGMIP_DSSAT_WEATHERS_" + cal.getTimeInMillis() + ".zip"); } else { outputFile = new File(arg0 + "AGMIP_DSSAT_" + cal.getTimeInMillis() + ".zip"); } // Write files String soil_id; String wth_id; expArr = combineExps(expArr); for (int i = 0; i < expArr.size(); i++) { expData = expArr.get(i); ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList()); if (rootArr.isEmpty()) { soil_id = getObjectOr(expData, "soil_id", ""); wth_id = getObjectOr(expData, "wst_id", ""); expData.put("soil", getSectionDataWithNocopy(soilArr, "soil_id", soil_id)); expData.put("weather", getSectionDataWithNocopy(wthArr, "wst_id", wth_id)); recordSWData(expData, new DssatSoilOutput()); recordSWData(expData, new DssatWeatherOutput()); } else { ArrayList<HashMap> soilArrTmp = new ArrayList(); ArrayList<HashMap> wthArrTmp = new ArrayList(); for (int j = 0; j < rootArr.size(); j++) { soil_id = getObjectOr(rootArr.get(j), "soil_id", ""); wth_id = getObjectOr(rootArr.get(j), "wst_id", ""); HashMap soilTmp = new HashMap(); HashMap wthTmp = new HashMap(); soilTmp.put("soil", getSectionDataWithNocopy(soilArr, "soil_id", soil_id)); soilTmp.put("soil_id", soil_id); soilTmp.put("exname", rootArr.get(j).get("exname")); soilTmp.put("id", rootArr.get(j).get("id")); wthTmp.put("weather", getSectionDataWithNocopy(wthArr, "wst_id", wth_id)); wthTmp.put("wst_id", wth_id); recordSWData(soilTmp, new DssatSoilOutput()); recordSWData(wthTmp, new DssatWeatherOutput()); soilArrTmp.add((HashMap) soilTmp.get("soil")); wthArrTmp.add(wthTmp); rootArr.get(j).put("wst_id", getObjectOr(wthTmp, "wst_id", wth_id)); } expData.put("soil", soilArrTmp); expData.put("weather", wthArrTmp); } DssatCommonOutput[] outputs = { new DssatXFileOutput(), new DssatAFileOutput(), new DssatTFileOutput(), new DssatCulFileOutput(),}; writeSingleExp(arg0, expData, outputs); } // If experiment data is included if (!expArr.isEmpty()) { // Write all batch files futFiles.add(executor.submit(new DssatTranslateRunner(new DssatBatchFileOutput(), expArr, arg0))); futFiles.add(executor.submit(new DssatTranslateRunner(new DssatRunFileOutput(), expArr, arg0))); } // If only weather or soil data is included else { for (int i = 0; i < soilArr.size(); i++) { HashMap tmp = new HashMap(); tmp.put("soil", soilArr.get(i)); tmp.put("soil_id", getObjectOr(soilArr.get(i), "soil_id", "")); recordSWData(tmp, new DssatSoilOutput()); } for (int i = 0; i < wthArr.size(); i++) { HashMap tmp = new HashMap(); tmp.put("weather", wthArr.get(i)); tmp.put("wst_id", getObjectOr(wthArr.get(i), "wst_id", "")); recordSWData(tmp, new DssatWeatherOutput()); } } // Write soil and weather files writeWthFiles(arg0); writeSoilFiles(arg0); // compress all output files into one zip file createZip(); } /** * ALL DSSAT Data Output method * * @param arg0 file output path * @param result data holder object * */ @Override public void writeFile(String arg0, Map result) { try { if (getObjectOr(result, "experiments", new ArrayList()).isEmpty() && getObjectOr(result, "soils", new ArrayList()).isEmpty() && getObjectOr(result, "weathers", new ArrayList()).isEmpty()) { // Write files DssatCommonOutput[] outputs = { new DssatXFileOutput(), new DssatAFileOutput(), new DssatTFileOutput(), new DssatCulFileOutput(), new DssatBatchFileOutput(), new DssatRunFileOutput() }; recordSWData(result, new DssatSoilOutput()); recordSWData(result, new DssatWeatherOutput()); writeWthFiles(arg0); writeSoilFiles(arg0); writeSingleExp(arg0, result, outputs); // compress all output files into one zip file outputFile = new File(revisePath(arg0) + getZipFileName(outputs)); createZip(); } else { writeMultipleExp(arg0, result); } executor.shutdown(); while (!executor.isTerminated()) { } executor = null; } catch (FileNotFoundException e) { LOG.error(getStackTrace(e)); } catch (IOException e) { LOG.error(getStackTrace(e)); } } /** * Write files and add file objects in the array * * @param arg0 file output path * @param result data holder object * @param outputs DSSAT Output objects */ private void writeSingleExp(String arg0, Map result, DssatCommonOutput... outputs) { for (int i = 0; i < outputs.length; i++) { futFiles.add(executor.submit(new DssatTranslateRunner(outputs[i], result, arg0))); } } /** * write soil/weather files * * @param expData The holder for experiment data include soil/weather data * @param output The DSSAT Writer object */ private void recordSWData(Map expData, DssatCommonOutput output) { String id; HashMap<String, Map> swData; try { if (output instanceof DssatSoilOutput) { Map soilTmp = getObjectOr(expData, "soil", new HashMap()); if (soilTmp.isEmpty()) { id = getObjectOr(expData, "soil_id", ""); } else { id = soilHelper.getSoilID(soilTmp); } // id = id.substring(0, 2); swData = soilData; expData.put("soil_id", id); } else { // id = getObjectOr(expData, "wst_id", ""); // id = getWthFileName(getObjectOr(expData, "weather", new HashMap())); Map wthTmp = getObjectOr(expData, "weather", new HashMap()); if (wthTmp.isEmpty()) { id = getObjectOr(expData, "wst_id", ""); } else { id = wthHelper.createWthFileName(wthTmp); } swData = wthData; expData.put("wst_id", id); } if (!id.equals("") && !swData.containsKey(id)) { swData.put(id, expData); // Future fut = executor.submit(new DssatTranslateRunner(output, expData, arg0)); // swfiles.put(id, fut); // futFiles.add(fut); } } catch (Exception e) { LOG.error(getStackTrace(e)); } } private void writeWthFiles(String arg0) { for (Map data : wthData.values()) { writeSingleExp(arg0, data, new DssatWeatherOutput()); } } private void writeSoilFiles(String arg0) { Map<String, ArrayList<Map>> soilTmp = new HashMap(); for (Map data : soilData.values()) { String soil_id = getObjectOr(data, "soil_id", ""); if (soil_id.length() < 2) { soil_id = ""; } else { soil_id = soil_id.substring(0, 2); } Map soil = (Map) data.get("soil"); if (soil == null || soil.isEmpty()) { continue; } if (soilTmp.containsKey(soil_id)) { soilTmp.get(soil_id).add(data); } else { ArrayList<Map> arr = new ArrayList(); arr.add(data); soilTmp.put(soil_id, arr); } } for (ArrayList arr : soilTmp.values()) { HashMap data = new HashMap(); data.put("soils", arr); writeSingleExp(arg0, data, new DssatSoilOutput()); } } /** * Compress the files in one zip * * @throws FileNotFoundException * @throws IOException */ private void createZip() throws FileNotFoundException, IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile)); ZipEntry entry; BufferedInputStream bis; byte[] data = new byte[1024]; // Get output result files into output array for zip package for (int i = 0; i < futFiles.size(); i++) { try { File f = futFiles.get(i).get(); if (f != null) { files.put(f.getPath(), f); } } catch (InterruptedException ex) { LOG.error(getStackTrace(ex)); } catch (ExecutionException ex) { if (!ex.getMessage().contains("NoOutputFileException")) { LOG.error(getStackTrace(ex)); } } } LOG.info("Start zipping all the files..."); // Check if there is file been created if (files == null) { LOG.warn("No files here for zipping"); return; } for (File file : files.values()) { if (file == null) { continue; } if (outputFile.getParent() != null) { entry = new ZipEntry(file.getPath().substring(outputFile.getParent().length() + 1)); } else { entry = new ZipEntry(file.getPath()); } out.putNextEntry(entry); bis = new BufferedInputStream(new FileInputStream(file)); int count; while ((count = bis.read(data)) != -1) { out.write(data, 0, count); } bis.close(); file.delete(); } out.close(); LOG.info("End zipping"); } /** * Get all output files */ public ArrayList<File> getOutputFiles() { return new ArrayList(files.values()); } /** * Get output zip file name by using experiment file name * * @param outputs DSSAT Output objects */ private String getZipFileName(DssatCommonOutput[] outputs) { for (int i = 0; i < outputs.length; i++) { if (outputs[i] instanceof DssatXFileOutput) { if (outputs[i].getOutputFile() != null) { return outputs[i].getOutputFile().getName().replaceAll("\\.", "_") + ".ZIP"; } else { break; } } } return "OUTPUT.ZIP"; } /** * Get output zip file */ public File getOutputZipFile() { return outputFile; } private ArrayList<HashMap> combineExps(ArrayList<HashMap> expArr) { // Set experiment groups with same exname ArrayList<HashMap> ret = new ArrayList(); LinkedHashMap<String, ArrayList<HashMap>> expGroupMap = new LinkedHashMap(); ArrayList<HashMap> subExpArr; String exname; for (int i = 0; i < expArr.size(); i++) { exname = getValueOr(expArr.get(i), "exname", ""); if (exname.equals("")) { subExpArr = new ArrayList(); subExpArr.add(expArr.get(i)); expGroupMap.put("Experiment_" + i, subExpArr); } else { exname = getFileName(expArr.get(i), ""); subExpArr = expGroupMap.get(exname); if (subExpArr == null) { subExpArr = new ArrayList(); expGroupMap.put(exname, subExpArr); } subExpArr.add(expArr.get(i)); } } // Combine the experiments in the same group Set<Entry<String, ArrayList<HashMap>>> expGroups = expGroupMap.entrySet(); for (Entry<String, ArrayList<HashMap>> expGroup : expGroups) { if (expGroup.getValue().size() == 1) { ret.add(expGroup.getValue().get(0)); } else { HashMap tmp = DssatCommonInput.CopyList(expGroup.getValue().get(0)); if (!tmp.containsKey("dssat_sequence")) { HashMap seq = new HashMap(); ArrayList<HashMap> seqArr = new ArrayList(); HashMap seqData = new HashMap(); String trt_name = getValueOr(tmp, "trt_name", getValueOr(tmp, "exname", "")); if (!trt_name.equals("")) { seqData.put("trt_name", trt_name); } seqArr.add(seqData); tmp.put("dssat_sequence", seq); seq.put("data", seqArr); } ArrayList rootArr = new ArrayList(); tmp.put("dssat_root", rootArr); rootArr.add(combinaRoot(tmp)); for (int i = 1; i < expGroup.getValue().size(); i++) { HashMap exp = expGroup.getValue().get(i); rootArr.add(combinaRoot(exp)); updateGroupExps(tmp, exp, i + 1); } ret.add(tmp); } } return ret; } private HashMap combinaRoot(Map m) { Set<Entry<String, Object>> entries = m.entrySet(); HashMap items = new HashMap(); for (Entry<String, Object> e : entries) { if (e.getValue() instanceof String || e.getKey().equals("dssat_info") || e.getKey().equals("initial_conditions")) { items.put(e.getKey(), e.getValue()); } } return items; } private void updateGroupExps(HashMap out, HashMap expData, int trno) { int baseId = trno * 1000; int seqid; int sm; int em; // Update dssat_sequence data ArrayList<HashMap<String, String>> seqArr = new BucketEntry(getObjectOr(expData, "dssat_sequence", new HashMap())).getDataList(); if (seqArr.isEmpty()) { seqArr.add(new HashMap()); } for (int i = 0; i < seqArr.size(); i++) { HashMap tmp = seqArr.get(i); try { seqid = Integer.parseInt(getValueOr(tmp, "seqid", "0")) + baseId; sm = Integer.parseInt(getValueOr(tmp, "sm", "0")) + baseId; em = Integer.parseInt(getValueOr(tmp, "em", "0")) + baseId; } catch (NumberFormatException e) { seqid = baseId; sm = baseId; em = baseId; } tmp.put("seqid", seqid + ""); tmp.put("sm", sm + ""); tmp.put("em", em + ""); tmp.put("trno", trno + ""); if (tmp.get("trt_name") == null) { String trt_name = getValueOr(expData, "trt_name", getValueOr(expData, "exname", "")); if (!trt_name.equals("")) { tmp.put("trt_name", trt_name); } } } combineData(out, seqArr, "dssat_sequence"); // Update management events data ArrayList<HashMap<String, String>> evtArr = new BucketEntry(getObjectOr(expData, "management", new HashMap())).getDataList(); for (int i = 0; i < evtArr.size(); i++) { HashMap tmp = evtArr.get(i); try { seqid = Integer.parseInt(getValueOr(tmp, "seqid", "0")) + baseId; } catch (NumberFormatException e) { seqid = baseId; } tmp.put("seqid", seqid + ""); } combineData(out, evtArr, "management"); // Update dssat_environment_modification data ArrayList<HashMap<String, String>> emArr = new BucketEntry(getObjectOr(expData, "dssat_environment_modification", new HashMap())).getDataList(); for (int i = 0; i < emArr.size(); i++) { HashMap tmp = emArr.get(i); try { em = Integer.parseInt(getValueOr(tmp, "em", "0")) + baseId; } catch (NumberFormatException e) { em = baseId; } tmp.put("em", em + ""); } combineData(out, emArr, "dssat_environment_modification"); // Update dssat_simulation_control data ArrayList<HashMap<String, String>> smArr = new BucketEntry(getObjectOr(expData, "dssat_simulation_control", new HashMap())).getDataList(); for (int i = 0; i < smArr.size(); i++) { HashMap tmp = smArr.get(i); try { sm = Integer.parseInt(getValueOr(tmp, "sm", "0")) + baseId; } catch (NumberFormatException e) { sm = baseId; } tmp.put("sm", sm + ""); } combineData(out, smArr, "dssat_simulation_control"); // Update observation data HashMap obvData = getObjectOr(expData, "observed", new HashMap()); obvData.put("trno", trno + ""); Object outObvData = getObjectOr(out, "observed", new Object()); if (outObvData instanceof HashMap) { ((HashMap) outObvData).put("trno", "1"); ArrayList obvArr = new ArrayList(); obvArr.add(outObvData); obvArr.add(obvData); out.put("observed", obvArr); } else if (outObvData instanceof ArrayList) { ((ArrayList) outObvData).add(obvData); } else { ArrayList obvArr = new ArrayList(); obvArr.add(obvData); out.put("observed", obvArr); } } private void combineData(HashMap out, ArrayList arr, String secName) { ArrayList<HashMap<String, String>> seqArrOut; // combine the array of data // seqArrOut = new BucketEntry(getObjectOr(out, secName, new HashMap())).getDataList(); if (!arr.isEmpty()) { HashMap data = getObjectOr(out, secName, new HashMap()); if (data.isEmpty()) { out.put(secName, data); } String subSecName; if (secName.equals("management")) { subSecName = "events"; } else { subSecName = "data"; } seqArrOut = getObjectOr(data, subSecName, new ArrayList()); if (seqArrOut.isEmpty()) { data.put(subSecName, seqArrOut); } seqArrOut.addAll(arr); } } }
true
false
null
null
diff --git a/src/harris/GiantBomb/GBObject.java b/src/harris/GiantBomb/GBObject.java index f11949a..7812699 100644 --- a/src/harris/GiantBomb/GBObject.java +++ b/src/harris/GiantBomb/GBObject.java @@ -1,189 +1,187 @@ package harris.GiantBomb; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class GBObject implements api { public enum ObjectType { GAME, FRANCHISE, CHARACTER, CONCEPT, OBJECT, LOCATION, PERSON, COMPANY }; private ObjectType type; private String name; private String id; private String description; private String url; private List<GBObject> related; public GBObject() { setRelated(new ArrayList<GBObject>()); } public ObjectType getType() { return type; } public void setType(ObjectType type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public void setRelated(List<GBObject> related) { this.related = related; } public List<GBObject> getRelated() { return related; } public List<GBObject> getRelated(ObjectType type) { List<GBObject> result = new ArrayList<GBObject>(); for (GBObject o : related) { if (o.getType() == type) { result.add(o); } } return result; } public static GBObject getGBObject(String id, ObjectType type) throws ParserConfigurationException, FactoryConfigurationError, SAXException, IOException { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); URL url = new URL( "http://api.giantbomb.com/" + type.toString().toLowerCase() + "/" + id + "/?api_key=" + API_KEY + "&field_list=id,name,description,site_detail_url,games,franchises,characters,concepts,objects,locations,people,companies&format=xml"); Document doc = docBuilder.parse(url.openConnection().getInputStream()); return parseObject((Element) doc.getElementsByTagName("results") .item(0), type); } public static GBObject parseObject(Element el, ObjectType type) { GBObject item = new GBObject(); NodeList nodes = el.getChildNodes(); - try { - for (int i = 0; i <= nodes.getLength(); i++) { - String nodeName = nodes.item(i).getNodeName(); - - if (nodeName.equals("name")) { - item.setName(nodes.item(i).getFirstChild().getNodeValue()); - } else if (nodeName.equals("id")) { - item.setId(nodes.item(i).getFirstChild().getNodeValue()); - } else if (nodeName.equals("description")) { - item.setDescription(nodes.item(i).getFirstChild().getNodeValue()); - } else if (nodeName.equals("site_detail_url")) { - item.setUrl(nodes.item(i).getFirstChild().getNodeValue()); - } + for (int i = 0; i < nodes.getLength(); i++) { + String nodeName = nodes.item(i).getNodeName(); + + if (nodeName.equals("name")) { + item.setName(nodes.item(i).getFirstChild().getNodeValue()); + } else if (nodeName.equals("id")) { + item.setId(nodes.item(i).getFirstChild().getNodeValue()); + } else if (nodeName.equals("description")) { + item.setDescription(nodes.item(i).getFirstChild().getNodeValue()); + } else if (nodeName.equals("site_detail_url")) { + item.setUrl(nodes.item(i).getFirstChild().getNodeValue()); } - } catch (Exception e) {} + } // item.setName(el.getElementsByTagName("name").item(0).getFirstChild() // .getNodeValue()); // item.setId(el.getElementsByTagName("id").item(0).getFirstChild() // .getNodeValue()); // // try { // item.setDescription(el.getElementsByTagName("description").item(0) // .getFirstChild().getNodeValue()); // } catch (Exception e) { // } // ; // // try { // item.setUrl(el.getElementsByTagName("site_detail_url").item(0) // .getFirstChild().getNodeValue()); // } catch (Exception e) { // } // ; for (ObjectType ot : ObjectType.values()) { try { NodeList nl = el.getElementsByTagName(ot.toString().toLowerCase()); for (int i = 0; i < (nl.getLength() < 5 ? nl.getLength() : 5); i++) { Element el2 = (Element)nl.item(i); GBObject ri = new GBObject(); ri.setName(el2.getElementsByTagName("name").item(0).getFirstChild() .getNodeValue()); ri.setId(el2.getElementsByTagName("id").item(0).getFirstChild() .getNodeValue()); ri.setType(ot); if (item.getId() != ri.getId() && item.getType() != ri.getType()) { item.getRelated().add(ri); } } } catch (Exception e) { } } item.setType(type); return item; } public GBObject clone() { GBObject obj = new GBObject(); obj.setId(this.id); obj.setName(this.name); obj.setType(this.type); obj.setUrl(this.url); obj.setDescription(this.description); obj.setRelated(this.related); return obj; } }
false
false
null
null
diff --git a/src/elka/clouddir/client/ServerCommunicationThread.java b/src/elka/clouddir/client/ServerCommunicationThread.java index fc8e473..c7b410d 100644 --- a/src/elka/clouddir/client/ServerCommunicationThread.java +++ b/src/elka/clouddir/client/ServerCommunicationThread.java @@ -1,115 +1,115 @@ package elka.clouddir.client; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; +import java.io.*; import java.net.Socket; import java.util.concurrent.BlockingQueue; import elka.clouddir.client.clientEvents.ClientEvent; import elka.clouddir.client.clientEvents.LoginAcceptedEvent; import elka.clouddir.client.clientEvents.LoginRejectedEvent; import elka.clouddir.shared.Message; /** * Class for communication with server * @author bogdan */ public class ServerCommunicationThread extends Thread { private final ObjectOutputStream out; private final ObjectInputStream in; private Socket clientSocket; private static final int PORT = 3333; private final BlockingQueue<ClientEvent> clientEventQueue; /** * Creating the socket and connecting with server * @param clientEventQueue * @throws IOException - server is down */ public ServerCommunicationThread(BlockingQueue<ClientEvent> clientEventQueue) throws IOException { this.clientEventQueue = clientEventQueue; clientSocket = new Socket("localhost", PORT); out = new ObjectOutputStream(clientSocket.getOutputStream()); out.flush(); in = new ObjectInputStream(clientSocket.getInputStream()); System.out.println("Connection established"); } /** * Listening for the incoming messages from server */ @Override public void run() { try { while (true) { Message message = (Message)in.readObject(); ClientEvent event = processMessage(message); // TransmissionEnd transmissionEnd = (TransmissionEnd)in.readObject(); clientEventQueue.add(event); } + } catch (EOFException e) { + System.out.println("Server disconnected"); } catch (Exception e) { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } e.printStackTrace(); } + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } /** * Sending the object to server * @param file * @throws IOException */ public void sendObject(final Serializable file) throws IOException { out.writeObject(file); out.flush(); } /** * Processing the Message depending on the type * @param message * @return * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ private ClientEvent processMessage(final Message message) throws IOException, ClassNotFoundException, InterruptedException { switch (message) { case LOGIN_OK: return new LoginAcceptedEvent(); case LOGIN_FAILED: return new LoginRejectedEvent(); default: throw new UnsupportedOperationException("Operation not implemented"); } } /** * Sending the type of the message * @param message * @throws IOException */ public void sendMessage(Message message) throws IOException { out.writeObject(message); out.flush(); } } diff --git a/src/elka/clouddir/server/communication/ClientCommunicationThread.java b/src/elka/clouddir/server/communication/ClientCommunicationThread.java index 4cf6c86..90b0d95 100644 --- a/src/elka/clouddir/server/communication/ClientCommunicationThread.java +++ b/src/elka/clouddir/server/communication/ClientCommunicationThread.java @@ -1,113 +1,120 @@ package elka.clouddir.server.communication; import elka.clouddir.server.model.AbstractFileInfo; import elka.clouddir.server.serverevents.*; import elka.clouddir.shared.*; import java.io.*; import java.net.Socket; import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; /** * Wątek odpowiadający za komunikację z klientem * @author Michał Toporowski */ public class ClientCommunicationThread extends Thread { private final ObjectOutputStream out; private final ObjectInputStream in; private final BlockingQueue<ServerEvent> serverEventQueue; private boolean running; // static Map<Message, MessageProcesser> processerMap; // static { // initMap(); // } public ClientCommunicationThread(Socket clientSocket, BlockingQueue<ServerEvent> serverEventQueue) throws IOException { this.serverEventQueue = serverEventQueue; out = new ObjectOutputStream(clientSocket.getOutputStream()); in = new ObjectInputStream(clientSocket.getInputStream()); } @Override public void run() { running = true; while (running) { try { Message message = (Message)in.readObject(); //pobranie dodatkowych danych ServerEvent event = processMessage(message); //to po to, aby sprawdzić, że poprawnie zakończono transmisję // TransmissionEnd transmissionEnd = (TransmissionEnd)in.readObject(); //ok - wyślij do serwera serverEventQueue.put(event); } catch (EOFException e) { running = false; System.out.println("Transmission ended, connection closed"); } catch (ClassCastException | ClassNotFoundException e) { System.out.println("Received incompatible object"); } catch (InterruptedException e) { running = false; System.out.println("Thread interrupted"); } catch (IOException e) { running = false; System.out.println("IO exception"); } + } + + try { + in.close(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); } } /** * Wysyła obiekt do klienta * @param object * @throws IOException */ public void sendObject(final Serializable object) throws IOException { out.writeObject(object); } private ServerEvent processMessage(final Message message) throws IOException, ClassNotFoundException, InterruptedException { System.out.println("Received message \"" + message.toString() + "\""); switch (message) { case LOGIN_REQUEST: LoginInfo loginInfo = (LoginInfo) in.readObject(); return new LoginRequestEvent(this, loginInfo); case FILE_CHANGED: { AbstractFileInfo metadata = (AbstractFileInfo) in.readObject(); return new FileChangedEvent(this, metadata); } case FILE_DELETED: { AbstractFileInfo metadata = (AbstractFileInfo) in.readObject(); return new FileDeletedEvent(this, metadata); } case FILEPATH_CHANGED: { RenameInfo renameInfo = (RenameInfo) in.readObject(); return new FilePathChangedEvent(this, renameInfo); } case FULL_METADATA_TRANSFER: { FilesMetadata metadata = (FilesMetadata) in.readObject(); return new FullMetadataTransferEvent(this, metadata); } case FILE_TRANSFER: AbstractFileInfo metadata = (AbstractFileInfo) in.readObject(); byte[] data = (byte[]) in.readObject(); return new FileTransferEvent(this, metadata, data); default: throw new UnsupportedOperationException("Operation not implemented"); } } }
false
false
null
null
diff --git a/FruitStandTracker/src/edu/upenn/cis350/project/InfoActivity.java b/FruitStandTracker/src/edu/upenn/cis350/project/InfoActivity.java index b95833f..a50528d 100644 --- a/FruitStandTracker/src/edu/upenn/cis350/project/InfoActivity.java +++ b/FruitStandTracker/src/edu/upenn/cis350/project/InfoActivity.java @@ -1,364 +1,364 @@ package edu.upenn.cis350.project; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; public class InfoActivity extends Activity { //TODO everything has been made public for testing purposes. //Change that later public String school; TextView saleDisplayDate; Button changeDate; //variables for the date public int year; public int month; public int day; static final int DATE_DIALOG_ID = 999; //variables for adding volunteers Button addVol; LinearLayout volLayout; int id; public String vol1; public String vol2; public String vol3; public String vol4; public String vol5; public String vol6; public String vol7; public String vol8; //variables for adding staff members public Button addStaff; LinearLayout staffLayout; int sId; public String staff1; public String staff2; public String staff3; public String staff4; LinearLayout schoolLayout; EditText addedSchool; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); final Spinner spinner = (Spinner) findViewById(R.id.school); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.school_list, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { int i = (int) id; if(i == 20){ school = "check"; Log.i("adding", "This is indeed the add a school option"); schoolLayout = (LinearLayout) findViewById(R.id.additional_school); addedSchool = new EditText(InfoActivity.this); addedSchool.setId(100);//completely arbitrary, still don't know what to do with ids addedSchool.setWidth(LayoutParams.MATCH_PARENT); addedSchool.setHeight(LayoutParams.WRAP_CONTENT); addedSchool.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); addedSchool.setHint(R.string.school_hint); schoolLayout.addView(addedSchool); } else{ school = (String)spinner.getSelectedItem(); } } public void onNothingSelected(AdapterView<?> parent) { } }); //for the date picker setCurrentDateOnView(); addListenerOnButton(); //for the volunteer adder addListenerAddVol(); volLayout = (LinearLayout) findViewById(R.id.volunteer_list); //for the staff adder addListenerAddStaff(); staffLayout = (LinearLayout) findViewById(R.id.staff_list); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_start, menu); return true; } // display current date public void setCurrentDateOnView() { saleDisplayDate = (TextView) findViewById(R.id.saleDate); //auto populating the date final Calendar c = Calendar.getInstance(); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DAY_OF_MONTH); // set current date into textview saleDisplayDate.setText(new StringBuilder() // Month is 0 based, just add 1 .append(month + 1).append("-").append(day).append("-") .append(year).append(" ")); } public void addListenerOnButton() { changeDate = (Button) findViewById(R.id.change_date); changeDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: // set date picker as current date return new DatePickerDialog(this, datePickerListener, year, month,day); } return null; } private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { year = selectedYear; month = selectedMonth; day = selectedDay; // set selected date into textview saleDisplayDate.setText(new StringBuilder().append(month + 1) .append("-").append(day).append("-").append(year) .append(" ")); } }; //listener for button that should add an edittext for another volunteer public void addListenerAddVol(){ id = 4; addVol = (Button) findViewById(R.id.add_volunteer); addVol.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //I'm only going to allow for 8 volunteers at this time //four original volunteers, plus 4 volunteers that may be added //in addition if(id < 9){ moreVolunteers(); } } }); } //method that actually adds another edittext for another volunteer private void moreVolunteers(){ EditText newVol = new EditText(this); newVol.setId(id); id++; newVol.setWidth(LayoutParams.MATCH_PARENT); newVol.setHeight(LayoutParams.WRAP_CONTENT); newVol.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); newVol.setHint(R.string.names); volLayout.addView(newVol); } //listener for button that should add an edittext for another staff member public void addListenerAddStaff(){ sId = -2; addStaff = (Button) findViewById(R.id.add_staff); addStaff.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ //I'm only going to allow for 4 staff members at this time //two original staff members, plus 2 staff members that may be //added in addition if(sId > -5){ Log.i("sID is ", "" + sId); moreStaff(); } } }); } //method that actually adds another edittext for another staff member private void moreStaff(){ EditText newStaff = new EditText(this); newStaff.setId(sId); sId--; newStaff.setWidth(LayoutParams.MATCH_PARENT); newStaff.setHeight(LayoutParams.WRAP_CONTENT); newStaff.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); newStaff.setHint(R.string.names); staffLayout.addView(newStaff); } //if a request has been made to add a school, change the //value of school to the value in the text box //this can be determined by the current value of school -> "check" //else, do nothing public void getSchool(){ if(!school.equals("check")){ return; } if(addedSchool.getText() != null) school = addedSchool.getText().toString(); } public void fillVolunteers(){ if(((EditText) findViewById(R.id.volunteer1)).getText() != null) vol1 = ((EditText) findViewById(R.id.volunteer1)).getText().toString(); if(((EditText) findViewById(R.id.volunteer2)).getText() != null) vol2 = ((EditText) findViewById(R.id.volunteer2)).getText().toString(); if(((EditText) findViewById(R.id.volunteer3)).getText() != null) vol3 = ((EditText) findViewById(R.id.volunteer3)).getText().toString(); if(((EditText) findViewById(R.id.volunteer4)).getText() != null) vol4 = ((EditText) findViewById(R.id.volunteer4)).getText().toString(); if(id > 5 && ((EditText) findViewById(5)).getText() != null) vol5 = ((EditText) findViewById(5)).getText().toString(); if(id > 6 && ((EditText) findViewById(6)).getText() != null) vol6 = ((EditText) findViewById(6)).getText().toString(); if(id > 7 && ((EditText) findViewById(7)).getText() != null) vol7 = ((EditText) findViewById(7)).getText().toString(); if(id > 8 && ((EditText) findViewById(8)).getText() != null) vol8 = ((EditText) findViewById(8)).getText().toString(); } public void fillStaff(){ if(((EditText) findViewById(R.id.staff1)).getText() != null) staff1 = ((EditText) findViewById(R.id.staff1)).getText().toString(); if(((EditText) findViewById(R.id.staff2)).getText() != null) staff2 = ((EditText) findViewById(R.id.staff2)).getText().toString(); if(sId < -3 && ((EditText) findViewById(-3)).getText() != null) staff3 = ((EditText) findViewById(-3)).getText().toString(); if(sId < -4 && ((EditText) findViewById(-4)).getText() != null) staff4 = ((EditText) findViewById(-4)).getText().toString(); } public String getYear(){ return Integer.toString(year); } public String getMonth(){ - return Integer.toString(month); + return Integer.toString(month + 1) ; } public String getDay(){ return Integer.toString(day); } public void continueToWeather(View v){ //Launch to weather Intent i = new Intent(this, WeatherActivity.class); //Save our info i.putExtra("herma", "derp"); //save school information for later use //only want to move on if a volunteer and a staff member have been inputed fillVolunteers(); fillStaff(); //Log.i("school 1 is", "" + school); getSchool(); //Log.i("school 2 is", "" + school); if(vol1 != null && vol1.length() > 1 && staff1 != null && staff1.length() > 1 && school != null && school.length() > 1){ DataBaser dataBaser = DataBaser.getInstance(); //Log.i("school 3 is", "" + school); dataBaser.addInfo("school", school); dataBaser.addInfo("year", getYear()); dataBaser.addInfo("month", getMonth()); dataBaser.addInfo("day", getDay()); dataBaser.addInfo("vol1", vol1); dataBaser.addInfo("vol2", vol2); dataBaser.addInfo("vol3", vol3); dataBaser.addInfo("vol4", vol4); if(id > 5) dataBaser.addInfo("vol5", vol5); if(id > 6) dataBaser.addInfo("vol6", vol6); if(id > 7) dataBaser.addInfo("vol7", vol7); if(id > 8) dataBaser.addInfo("vol8", vol8); dataBaser.addInfo("staff1", staff1); dataBaser.addInfo("staff2", staff2); if(sId < -3) dataBaser.addInfo("staff3", staff3); if(sId < -4) dataBaser.addInfo("staff4", staff4); this.startActivity(i); } } }
true
false
null
null
diff --git a/src/ch/unibe/scg/cc/GitPopulatorTest.java b/src/ch/unibe/scg/cc/GitPopulatorTest.java index a99af46..4cb730a 100644 --- a/src/ch/unibe/scg/cc/GitPopulatorTest.java +++ b/src/ch/unibe/scg/cc/GitPopulatorTest.java @@ -1,294 +1,293 @@ package ch.unibe.scg.cc; import static com.google.common.io.BaseEncoding.base16; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.inject.Qualifier; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Assert; import org.junit.Test; import ch.unibe.scg.cc.Annotations.Populator; import ch.unibe.scg.cc.Protos.CloneType; import ch.unibe.scg.cc.Protos.CodeFile; import ch.unibe.scg.cc.Protos.Function; import ch.unibe.scg.cc.Protos.GitRepo; import ch.unibe.scg.cc.Protos.Project; import ch.unibe.scg.cc.Protos.Snippet; import ch.unibe.scg.cc.Protos.Version; import ch.unibe.scg.cc.javaFrontend.JavaModule; import ch.unibe.scg.cells.CellsModule; import ch.unibe.scg.cells.InMemoryStorage; import ch.unibe.scg.cells.Sink; import ch.unibe.scg.cells.Source; import ch.unibe.scg.cells.TableModule.DefaultTableModule; import com.google.common.collect.Iterables; import com.google.common.io.ByteStreams; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.protobuf.ByteString; @SuppressWarnings("javadoc") public final class GitPopulatorTest { private static final String TESTREPO = "testrepo.zip"; @Test public void testProjnameRegex() throws IOException { try(GitPopulator gitWalker = new GitPopulator(null, null)) { String fullPathString = "har://hdfs-haddock.unibe.ch/projects/testdata.har" + "/apfel/.git/objects/pack/pack-b017c4f4e226868d8ccf4782b53dd56b5187738f.pack"; String projName = gitWalker.extractProjectName(fullPathString); assertThat(projName, is("apfel")); fullPathString = "har://hdfs-haddock.unibe.ch/projects/dataset.har/dataset/sensei/objects/pack/pack-a33a3daca1573e82c6fbbc95846a47be4690bbe4.pack"; projName = gitWalker.extractProjectName(fullPathString); assertThat(projName, is("sensei")); } } @Test public void testPopulate() throws IOException, InterruptedException { Injector i = walkRepo(parseZippedGit(TESTREPO)); try(Source<Project> projectPartitions = i.getInstance( Key.get(new TypeLiteral<Source<Project>>() {}, Populator.class)); Source<Str<Function>> functionStringPartitions = i.getInstance(Key.get(new TypeLiteral<Source<Str<Function>>>() {}, Populator.class)); Source<Snippet> snippet2FuncsPartitions = i.getInstance(Key.get(new TypeLiteral<Source<Snippet>>() {}, TestSink.class)); Source<Version> versionPartitions = i.getInstance( Key.get(new TypeLiteral<Source<Version>>() {}, Populator.class)); Source<CodeFile> filePartitions = i.getInstance( Key.get(new TypeLiteral<Source<CodeFile>>() {}, Populator.class)); Source<Function> functionPartitions = i.getInstance( Key.get(new TypeLiteral<Source<Function>>() {}, Populator.class)); Source<Snippet> snippetPartitions = i.getInstance( Key.get(new TypeLiteral<Source<Snippet>>() {}, Populator.class))) { assertThat(Iterables.size(projectPartitions), is(1)); Iterable<Project> projects = Iterables.getOnlyElement(projectPartitions); assertThat(Iterables.size(projects), is(1)); Project p = Iterables.getOnlyElement(projects); assertThat(p.getName(), is("testrepo.zip")); assertThat(Iterables.size(versionPartitions), is(1)); Iterable<Version> versions = Iterables.getOnlyElement(versionPartitions); assertThat(Iterables.size(versions), is(1)); Version v = Iterables.getOnlyElement(versions); assertThat(v.getName(), is("master")); assertThat(v.getProject(), is(p.getHash())); assertThat(Iterables.size(filePartitions), is(1)); Iterable<CodeFile> files = Iterables.getOnlyElement(filePartitions); assertThat(Iterables.size(files), is(1)); CodeFile cf = Iterables.getOnlyElement(files); assertThat(cf.getPath(), is("GitTablePopulatorTest.java")); assertThat(cf.getVersion(), is(v.getHash())); assertThat(cf.getContents().indexOf("package ch.unibe.scg.cc.mappers;"), is(0)); assertThat(Iterables.size(functionPartitions), is(1)); Iterable<Function> functions = Iterables.getOnlyElement(functionPartitions); assertThat(Iterables.size(functions), is(1)); Function fn = Iterables.getOnlyElement(functions); assertThat(fn.getCodeFile(), is(cf.getHash())); assertThat(fn.getBaseLine(), is(10)); assertThat(fn.getContents().indexOf("public void testProjname"), is(1)); assertThat(Iterables.size(snippetPartitions), is(1)); // means we have only one function Iterable<Snippet> snippets = Iterables.getOnlyElement(snippetPartitions); assertThat(Iterables.size(snippets), is(24)); Snippet s0 = Iterables.get(snippets, 0); Snippet s1 = Iterables.get(snippets, 1); Snippet s7 = Iterables.get(snippets, 7); assertThat(s0.getFunction(), is(fn.getHash())); assertThat(s0.getLength(), is(5)); assertThat(s0.getPosition(), is(0)); assertThat(s1.getPosition(), is(1)); assertThat(s1.getFunction(), is(fn.getHash())); assertThat(s7.getPosition(), is(7)); assertThat(s7.getFunction(), is(fn.getHash())); // Check FunctionString Iterable<Str<Function>> functionStringRow = Iterables.getOnlyElement(functionStringPartitions); Str<Function> functionString = Iterables.getOnlyElement(functionStringRow); assertThat(functionString.contents.indexOf("public void testProjnameRegex"), is(1)); - assertThat(Iterables.size(snippet2FuncsPartitions), is(24 - 2)); // 2 collisions Iterable<Snippet> snippets2Funcs = Iterables.get(snippet2FuncsPartitions, 0); assertThat(Iterables.size(snippets2Funcs), is(1)); } } @Test public void testPaperExampleFile2Function() throws IOException, InterruptedException { Injector i = walkRepo(GitPopulatorTest.parseZippedGit("paperExample.zip")); try(Source<Function> decodedPartitions = i.getInstance(Key.get(new TypeLiteral<Source<Function>>() {}, Populator.class))) { Iterable<Function> funs = Iterables.concat(decodedPartitions); assertThat(Iterables.size(funs), is(15)); Set<ByteString> funHashes = new HashSet<>(); for (Function fun : funs) { funHashes.add(fun.getHash()); } assertThat(funHashes.size(), is(9)); Set<String> fileHashes = new HashSet<>(); for (Iterable<Function> partition : decodedPartitions) { String cur = base16().encode(Iterables.get(partition, 0).getCodeFile().toByteArray()); Assert.assertFalse(cur + fileHashes, fileHashes.contains(cur)); fileHashes.add(cur); // Check that every partition shares the same file. for (Function f : partition) { assertThat(base16().encode(f.getCodeFile().toByteArray()), is(cur)); } } assertThat(fileHashes.size(), is(3)); } } @Test public void testPaperExampleSnippet2Functions() throws IOException, InterruptedException { Injector i = walkRepo(GitPopulatorTest.parseZippedGit("paperExample.zip")); try(Source<Snippet> snippet2Function = i.getInstance(Key.get(new TypeLiteral<Source<Snippet>>() {}, TestSink.class))) { assertThat(Iterables.size(snippet2Function), is(145)); // Numbers are taken from paper. See table II. ByteString row03D8 = ByteString.copyFrom(new byte[] {0x03, (byte) 0xd8}); Iterable<Snippet> partition03D8 = null; for(Iterable<Snippet> s2fPartition : snippet2Function) { if(Bytes.startsWith(Iterables.get(s2fPartition, 0).getHash().toByteArray(), row03D8.toByteArray())) { partition03D8 = s2fPartition; break; } } Assert.assertNotNull(partition03D8); assertThat(Iterables.size(partition03D8), is(2)); int actualDistance = Math.abs(Iterables.get(partition03D8, 0).getPosition() - Iterables.get(partition03D8, 1).getPosition()); assertThat(actualDistance, is(3)); } } @Test public void testPaperExampleFunction2Snippets() throws IOException, InterruptedException { Injector i = walkRepo(GitPopulatorTest.parseZippedGit("paperExample.zip")); try(Source<Snippet> function2snippetsPartitions = i.getInstance( Key.get(new TypeLiteral<Source<Snippet>>() {}, Populator.class))) { // Num partitions is the number of functions. As per populator test, that's 9. assertThat(Iterables.size(function2snippetsPartitions), is(9)); // We'll examine this row further in Function2RoughClones Iterable<Snippet> aaa0 = null; for (Iterable<Snippet> row : function2snippetsPartitions) { if (base16().encode(Iterables.get(row, 0).getFunction().toByteArray()).startsWith("AAA0")) { aaa0 = row; break; } } assert aaa0 != null; // Null analysis insists ... assertNotNull(aaa0); List<String> snippetHashes = new ArrayList<>(); for (Snippet s : aaa0) { if (s.getCloneType() == CloneType.GAPPED) { snippetHashes.add(base16().encode(s.getHash().toByteArray())); } } // These snippets were only partially checked. assertThat(snippetHashes, is(d618SnippetHashes())); } } static Collection<String> d618SnippetHashes() { return Arrays.asList("58BA4690385740B2C9F8FCBF890A1ECF3BDC17C4", "0FA256C80C3AF5E1AC1FE54F5F0AF85D8752F474", "0FA256C80C3AF5E1AC1FE54F5F0AF85D8752F474", "A9BBB1B13ECC261749436CAF9DC5DC20E9C2F68B", "98DB4D210584D3033A1E26785A6721C609B54D14", "BB3E14556ABA10796131584A07979C50470B4DBA", "38C303121D329190DA79CE955F0E790569D168D3", "598571B72AE83C72E299F3747B9C025848C45014", "301729FB42E326C3CE1130994C16BD4C9DF14A79", "A4A8B82E4ABE99EBF67D12A1FF190B61FF6E6520", "5F72E12E161EF9991A85572864F5FBE6C3DF72EB", "9C628251AE1C7A39F3265D1AACA3630B69DA3655", "1474378C2B8FDE56C8A835AFD8F7DFB46F1E59DC", "20A4E2A38A590E7D29978E7A3FF308EE15B6DC63", "6F4533745BDB2D84648440CE9D2826DECAEA72EE", "278629562C3404A50795A832EE4E81722319D775", "48C31A2277EF29216311E8FC7366A7ACE9F3A59B", "48C31A2277EF29216311E8FC7366A7ACE9F3A59B", "24D6FB97266FFFCC409DD4F57CDC938EE6423C5F"); } private static Injector walkRepo(GitRepo repo) throws IOException, InterruptedException { Injector i = Guice.createInjector(new CCModule(new InMemoryStorage()), new JavaModule(), new CellsModule() { @Override protected void configure() { installTable(TestSink.class, new TypeLiteral<Snippet>() {}, Snippet2FunctionsCodec.class, new InMemoryStorage(), new DefaultTableModule("rofl", ByteString.EMPTY)); } }); try (GitPopulator gitPopulator = i.getInstance(GitPopulator.class); Sink<Snippet> snippetSink = i.getInstance(Key.get(new TypeLiteral<Sink<Snippet>>() {}, TestSink.class))) { gitPopulator.map(repo, Arrays.asList(repo), snippetSink); } return i; } @Qualifier @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) private static @interface TestSink {} static GitRepo parseZippedGit(String pathToZip) throws IOException { try(ZipInputStream packFile = new ZipInputStream(GitPopulatorTest.class.getResourceAsStream(pathToZip)); ZipInputStream packedRefs = new ZipInputStream(GitPopulatorTest.class.getResourceAsStream(pathToZip))) { for (ZipEntry entry; (entry = packFile.getNextEntry()) != null;) { if (entry.getName().endsWith(".pack")) { break; } } for (ZipEntry entry; (entry = packedRefs.getNextEntry()) != null;) { if (entry.getName().endsWith("packed-refs")) { break; } } return GitRepo.newBuilder() .setProjectName(pathToZip) .setPackFile(ByteString.copyFrom(ByteStreams.toByteArray(packFile))) .setPackRefs(ByteString.copyFrom(ByteStreams.toByteArray(packedRefs))) .build(); } } } \ No newline at end of file diff --git a/src/ch/unibe/scg/cells/hadoop/HadoopPipelineTest.java b/src/ch/unibe/scg/cells/hadoop/HadoopPipelineTest.java index 1239614..3cb4b9f 100644 --- a/src/ch/unibe/scg/cells/hadoop/HadoopPipelineTest.java +++ b/src/ch/unibe/scg/cells/hadoop/HadoopPipelineTest.java @@ -1,233 +1,235 @@ package ch.unibe.scg.cells.hadoop; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Qualifier; import org.apache.hadoop.conf.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; import ch.unibe.scg.cc.mappers.ConfigurationProvider; import ch.unibe.scg.cells.Cell; import ch.unibe.scg.cells.CellsModule; import ch.unibe.scg.cells.Codec; import ch.unibe.scg.cells.Mapper; import ch.unibe.scg.cells.Pipeline; import ch.unibe.scg.cells.Sink; import ch.unibe.scg.cells.Source; import ch.unibe.scg.cells.TableModule.DefaultTableModule; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.common.io.Closer; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.protobuf.ByteString; @SuppressWarnings("javadoc") public final class HadoopPipelineTest { private final static String TABLE_NAME_IN = "richard-3"; private final static String TABLE_NAME_EFF = "richard-wc"; private final static ByteString fam = ByteString.copyFromUtf8("f"); private Table<Act> in; private Table<WordCount> eff; private TableAdmin tableAdmin; private Configuration configuration; private Injector injector; @Before public void loadRichardIII() throws IOException, InterruptedException { String richard = CharStreams.toString(new InputStreamReader(this.getClass().getResourceAsStream( "richard-iii.txt"), Charsets.UTF_8)); String[] actStrings = richard.split("\\bACT\\s[IVX]+"); final Module configurationModule = new AbstractModule() { @Override protected void configure() { bind(Configuration.class).toProvider(ConfigurationProvider.class); } }; Module tab = new CellsModule() { @Override protected void configure() { installTable( In.class, new TypeLiteral<Act>() {}, ActCodec.class, new HBaseStorage(), new DefaultTableModule(TABLE_NAME_IN, fam)); installTable( Eff.class, new TypeLiteral<WordCount>() {}, WordCountCodec.class, new HBaseStorage(), new DefaultTableModule(TABLE_NAME_EFF, fam)); } }; injector = Guice.createInjector(tab, configurationModule); configuration = injector.getInstance(Configuration.class); tableAdmin = injector.getInstance(TableAdmin.class); in = tableAdmin.createTable(TABLE_NAME_IN, fam); try (Sink<Act> sink = injector.getInstance(Key.get(new TypeLiteral<Sink<Act>>() {}, In.class))) { for (int i = 0; i < actStrings.length; i++) { sink.write(new Act(i, actStrings[i])); } } eff = tableAdmin.createTable(TABLE_NAME_EFF, fam); } @After public void deleteRichardIII() throws Exception { try (Closer c = Closer.create()) { if (in != null) { c.register(in); } if (eff != null) { c.register(eff); } } - tableAdmin.deleteTable(in.getTableName()); + if (in != null) { + tableAdmin.deleteTable(in.getTableName()); + } if (eff != null) { tableAdmin.deleteTable(eff.getTableName()); } } @Test public void testOhhh() throws IOException, InterruptedException { run(HadoopPipeline.fromTableToTable(configuration, fam, in, eff)); try(Source<WordCount> src = injector.getInstance(Key.get(new TypeLiteral<Source<WordCount>>() {}, Eff.class))) { for (Iterable<WordCount> wcs : src) { for (WordCount wc : wcs) { System.out.println(wc.word + " " + wc.count); } } } } void run(Pipeline<Act, WordCount> pipeline) throws IOException, InterruptedException { pipeline.influx(new ActCodec()) .mapper(new WordParseMapper()) .shuffle(new WordCountCodec()) .efflux(new WordAdderMapper(), new WordCountCodec()); // TODO: Rename efflux to mapAndEfflux } @Qualifier @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public static @interface In {} @Qualifier @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public static @interface Eff {} static class Act { final int number; final String content; Act(int number, String content) { this.number = number; this.content = content; } } private static class ActCodec implements Codec<Act> { private static final long serialVersionUID = 1L; @Override public Cell<Act> encode(Act act) { return Cell.make(ByteString.copyFrom(Ints.toByteArray(act.number)), ByteString.copyFromUtf8("t"), ByteString.copyFromUtf8(act.content)); } @Override public Act decode(Cell<Act> encoded) throws IOException { return new Act(Ints.fromByteArray(encoded.getRowKey().toByteArray()), encoded.getCellContents() .toStringUtf8()); } } private static class WordCount { final String word; final long count; WordCount(String word, long count) { this.word = word; this.count = count; } } static class WordCountCodec implements Codec<WordCount> { private static final long serialVersionUID = 1L; @Override public Cell<WordCount> encode(WordCount s) { return Cell.make(ByteString.copyFromUtf8(s.word), ByteString.copyFromUtf8("1"), ByteString.copyFrom(Longs.toByteArray(s.count))); } @Override public WordCount decode(Cell<WordCount> encoded) throws IOException { return new WordCount(encoded.getRowKey().toStringUtf8(), Longs.fromByteArray(encoded.getCellContents().toByteArray())); } } static class WordParseMapper implements Mapper<Act, WordCount> { private static final long serialVersionUID = 1L; @Override public void close() { } @Override public void map(Act first, Iterable<Act> row, Sink<WordCount> sink) throws IOException, InterruptedException { for(Act act : row) { Matcher matcher = Pattern.compile("\\w+").matcher(act.content); while (matcher.find()) { sink.write(new WordCount(matcher.group(), 1L)); } } } } static class WordAdderMapper implements Mapper<WordCount, WordCount> { private static final long serialVersionUID = 1L; @Override public void close() { } @Override public void map(WordCount first, Iterable<WordCount> row, Sink<WordCount> sink) throws IOException, InterruptedException { long total = 0L; for (WordCount wc : row) { total += wc.count; } sink.write(new WordCount(first.word, total)); } } }
false
false
null
null
diff --git a/src/org/reader/Instruction.java b/src/org/reader/Instruction.java index 76e1006..83b3ef6 100644 --- a/src/org/reader/Instruction.java +++ b/src/org/reader/Instruction.java @@ -1,83 +1,83 @@ package org.reader; import org.reader.blocks.ForLoop; import org.reader.blocks.IfStatement; import org.reader.blocks.WhileLoop; import org.reader.instruction.Declaration; import org.reader.instruction.Method; /** * Basic statement that does something when used. * * @author joel */ public abstract class Instruction extends Statement { /** * Hide this method to use the class. <i><b>This method is meant to be * hidden by it's subclasses. It is called in a tree-like structure down the * children of {@link Statement}.</i></b> * * @param statement the statement to analyze * @return whether it is a valid instruction */ public static boolean isValid(String statement) { return statement.endsWith(";") || statement.endsWith("{") || statement.equals("}"); } /** * Hide this method to use the class. <i><b>This method is meant to be * hidden by it's subclasses. It is called in a tree-like structure down the * children of {@link Statement}.</i></b> * * <p> It is very important to verify that the statement is valid before * using this method. If it is not valid, it will throw * {@link InvalidStatementException}. </p> * * @param statement the statement to analyze * @return a {@link Statement} object of the type * @throws org.reader.Statement.InvalidStatementException */ public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); - } else if (Declaration.isValid(statement)) { - return Declaration.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); + } else if (Declaration.isValid(statement)) { + return Declaration.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { - throw new InvalidStatementException(statement + " is not a statement type."); + throw new InvalidStatementException(Method.getMethodName(statement) + " is not a recognized method."); } } private final String instruction; /** * Creates instruction by a string. * * @param instruction full code snippet */ public Instruction(String instruction) { this.instruction = instruction; } /** * The instruction in the text file. * * @return instruction as a string */ public String getInstruction() { return instruction; } /** * Method to run the instruction. */ public abstract void run(); }
false
true
public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); } else if (Declaration.isValid(statement)) { return Declaration.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { throw new InvalidStatementException(statement + " is not a statement type."); } }
public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); } else if (Declaration.isValid(statement)) { return Declaration.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { throw new InvalidStatementException(Method.getMethodName(statement) + " is not a recognized method."); } }
diff --git a/main/src/cgeo/geocaching/activity/AbstractViewPagerActivity.java b/main/src/cgeo/geocaching/activity/AbstractViewPagerActivity.java index 049fc7d00..c7d450772 100644 --- a/main/src/cgeo/geocaching/activity/AbstractViewPagerActivity.java +++ b/main/src/cgeo/geocaching/activity/AbstractViewPagerActivity.java @@ -1,322 +1,324 @@ package cgeo.geocaching.activity; import cgeo.geocaching.R; import cgeo.geocaching.utils.Log; import com.viewpagerindicator.TitlePageIndicator; import com.viewpagerindicator.TitleProvider; import org.apache.commons.lang3.tuple.Pair; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import android.app.Activity; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract activity with the ability to manage pages in a view pager. * * @param <Page> * Enum listing all available pages of this activity. The pages available at a certain point of time are * defined by overriding {@link #getOrderedPages()}. */ public abstract class AbstractViewPagerActivity<Page extends Enum<Page>> extends AbstractActivity { /** * A {@link List} of all available pages. * * TODO Move to adapter */ private final List<Page> pageOrder = new ArrayList<Page>(); /** * Instances of all {@link PageViewCreator}. */ private final Map<Page, PageViewCreator> viewCreators = new HashMap<Page, PageViewCreator>(); /** * Store the states of the page views to be able to persist them when destroyed and reinstantiated again */ private final Map<Page, Bundle> viewStates = new HashMap<Page, Bundle>(); /** * The {@link ViewPager} for this activity. */ private ViewPager viewPager; /** * The {@link ViewPagerAdapter} for this activity. */ private ViewPagerAdapter viewPagerAdapter; /** * The {@link TitlePageIndicator} for this activity. */ private TitlePageIndicator titleIndicator; public interface PageViewCreator { /** * Returns a validated view. * * @return */ public View getDispatchedView(); /** * Returns a (maybe cached) view. * * @return */ public View getView(); /** * Handles changed data-sets. */ public void notifyDataSetChanged(); /** * Gets state of the view */ public @Nullable Bundle getViewState(); /** * Set the state of the view */ public void setViewState(@NonNull Bundle state); } /** * Page selection interface for the view pager. * */ protected interface OnPageSelectedListener { public void onPageSelected(int position); } /** * The ViewPagerAdapter for scrolling through pages of the CacheDetailActivity. */ private class ViewPagerAdapter extends PagerAdapter implements TitleProvider { @Override public void destroyItem(ViewGroup container, int position, Object object) { - + if (position >= pageOrder.size()) { + return; + } final Page page = pageOrder.get(position); // Store the state of the view if the page supports it PageViewCreator creator = viewCreators.get(page); if (creator != null) { @Nullable Bundle state = creator.getViewState(); if (state != null) { viewStates.put(page, state); } } container.removeView((View) object); } @Override public void finishUpdate(ViewGroup container) { } @Override public int getCount() { return pageOrder.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { final Page page = pageOrder.get(position); PageViewCreator creator = viewCreators.get(page); if (null == creator && null != page) { creator = AbstractViewPagerActivity.this.createViewCreator(page); viewCreators.put(page, creator); viewStates.put(page, new Bundle()); } View view = null; try { if (null != creator) { // Result from getView() is maybe cached, but it should be valid because the // creator should be informed about data-changes with notifyDataSetChanged() view = creator.getView(); // Restore the state of the view if the page supports it Bundle state = viewStates.get(page); if (state != null) { creator.setViewState(state); } container.addView(view, 0); } } catch (Exception e) { Log.e("ViewPagerAdapter.instantiateItem ", e); } return view; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(ViewGroup arg0) { } @Override public int getItemPosition(Object object) { // We are doing the caching. So pretend that the view is gone. // The ViewPager will get it back in instantiateItem() return POSITION_NONE; } @Override public String getTitle(int position) { final Page page = pageOrder.get(position); if (null == page) { return ""; } return AbstractViewPagerActivity.this.getTitle(page); } } /** * Create the view pager. Call this from the {@link Activity#onCreate} implementation. * * @param startPageIndex * index of the page shown first * @param pageSelectedListener * page selection listener or <code>null</code> */ protected final void createViewPager(int startPageIndex, final OnPageSelectedListener pageSelectedListener) { // initialize ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPagerAdapter = new ViewPagerAdapter(); viewPager.setAdapter(viewPagerAdapter); titleIndicator = (TitlePageIndicator) findViewById(R.id.pager_indicator); titleIndicator.setViewPager(viewPager); if (pageSelectedListener != null) { titleIndicator.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { pageSelectedListener.onPageSelected(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } }); } // switch to entry page (last used or 2) if (viewPagerAdapter.getCount() < startPageIndex) { for (int i = 0; i <= startPageIndex; i++) { // we can't switch to a page that is out of bounds, so we add null-pages pageOrder.add(null); } } viewPagerAdapter.notifyDataSetChanged(); viewPager.setCurrentItem(startPageIndex, false); } /** * create the view creator for the given page * * @return new view creator */ protected abstract PageViewCreator createViewCreator(Page page); /** * get the title for the given page */ protected abstract String getTitle(Page page); protected final void reinitializeViewPager() { // notify all creators that the data has changed for (PageViewCreator creator : viewCreators.values()) { creator.notifyDataSetChanged(); } // reset the stored view states of all pages for (Bundle state : viewStates.values()) { state.clear(); } pageOrder.clear(); final Pair<List<? extends Page>, Integer> pagesAndIndex = getOrderedPages(); pageOrder.addAll(pagesAndIndex.getLeft()); // Since we just added pages notifyDataSetChanged needs to be called before we possibly setCurrentItem below. // But, calling it will reset current item and we won't be able to tell if we would have been out of bounds final int currentItem = getCurrentItem(); // notify the adapter that the data has changed viewPagerAdapter.notifyDataSetChanged(); // switch to details page, if we're out of bounds final int defaultPage = pagesAndIndex.getRight(); if (currentItem < 0 || currentItem >= viewPagerAdapter.getCount()) { viewPager.setCurrentItem(defaultPage, false); } // notify the indicator that the data has changed titleIndicator.notifyDataSetChanged(); } /** * @return the currently available list of ordered pages, together with the index of the default page */ protected abstract Pair<List<? extends Page>, Integer> getOrderedPages(); public final Page getPage(int position) { return pageOrder.get(position); } protected final int getPageIndex(Page page) { return pageOrder.indexOf(page); } protected final PageViewCreator getViewCreator(Page page) { return viewCreators.get(page); } protected final boolean isCurrentPage(Page page) { return getCurrentItem() == getPageIndex(page); } protected int getCurrentItem() { return viewPager.getCurrentItem(); } }
true
false
null
null
diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java index 595ca9ad9..fc880d5db 100644 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java +++ b/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java @@ -1,287 +1,287 @@ /* ==================================================================== 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.poi.hdgf.chunks; import java.util.ArrayList; import org.apache.poi.hdgf.chunks.ChunkFactory.CommandDefinition; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.util.StringUtil; /** * Base of all chunks, which hold data, flags etc */ public final class Chunk { /** * The contents of the chunk, excluding the header, * trailer and separator */ private byte[] contents; private ChunkHeader header; /** May be null */ private ChunkTrailer trailer; /** May be null */ private ChunkSeparator separator; /** The possible different commands we can hold */ protected CommandDefinition[] commandDefinitions; /** The command+value pairs we hold */ private Command[] commands; /** The blocks (if any) we hold */ //private Block[] blocks /** The name of the chunk, as found from the commandDefinitions */ private String name; /** For logging warnings about the structure of the file */ private POILogger logger = POILogFactory.getLogger(Chunk.class); public Chunk(ChunkHeader header, ChunkTrailer trailer, ChunkSeparator separator, byte[] contents) { this.header = header; this.trailer = trailer; this.separator = separator; this.contents = contents; } public byte[] _getContents() { return contents; } public ChunkHeader getHeader() { return header; } /** Gets the separator between this chunk and the next, if it exists */ public ChunkSeparator getSeparator() { return separator; } /** Gets the trailer for this chunk, if it exists */ public ChunkTrailer getTrailer() { return trailer; } /** * Gets the command definitions, which define and describe much * of the data held by the chunk. */ public CommandDefinition[] getCommandDefinitions() { return commandDefinitions; } public Command[] getCommands() { return commands; } /** * Get the name of the chunk, as found from the CommandDefinitions */ public String getName() { return name; } /** * Returns the size of the chunk, including any * headers, trailers and separators. */ public int getOnDiskSize() { int size = header.getSizeInBytes() + contents.length; if(trailer != null) { size += trailer.trailerData.length; } if(separator != null) { size += separator.separatorData.length; } return size; } /** * Uses our CommandDefinitions to process the commands * our chunk type has, and figure out the * values for them. */ protected void processCommands() { if(commandDefinitions == null) { throw new IllegalStateException("You must supply the command definitions before calling processCommands!"); } // Loop over the definitions, building the commands // and getting their values - ArrayList commands = new ArrayList(); + ArrayList<Command> commands = new ArrayList<Command>(); for(int i=0; i<commandDefinitions.length; i++) { int type = commandDefinitions[i].getType(); int offset = commandDefinitions[i].getOffset(); // Handle virtual commands if(type == 10) { name = commandDefinitions[i].getName(); continue; } else if(type == 18) { continue; } // Build the appropriate command for the type Command command; if(type == 11 || type == 21) { command = new BlockOffsetCommand(commandDefinitions[i]); } else { command = new Command(commandDefinitions[i]); } // Bizarely, many of the offsets are from the start of the // header, not from the start of the chunk body switch(type) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 11: case 21: case 12: case 16: case 17: case 18: case 28: case 29: // Offset is from start of chunk break; default: // Offset is from start of header! if(offset >= 19) { offset -= 19; } } // Check we seem to have enough data if(offset >= contents.length) { logger.log(POILogger.WARN, "Command offset " + offset + " past end of data at " + contents.length ); continue; } // Process switch(type) { // Types 0->7 = a flat at bit 0->7 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: int val = contents[offset] & (1<<type); command.value = Boolean.valueOf(val > 0); break; case 8: command.value = Byte.valueOf(contents[offset]); break; case 9: command.value = new Double( LittleEndian.getDouble(contents, offset) ); break; case 12: // A Little Endian String // Starts 8 bytes into the data segment // Ends at end of data, or 00 00 // Ensure we have enough data if(contents.length < 8) { command.value = ""; break; } // Find the end point int startsAt = 8; int endsAt = startsAt; for(int j=startsAt; j<contents.length-1 && endsAt == startsAt; j++) { if(contents[j] == 0 && contents[j+1] == 0) { endsAt = j; } } if(endsAt == startsAt) { endsAt = contents.length; } int strLen = (endsAt-startsAt) / 2; command.value = StringUtil.getFromUnicodeLE(contents, startsAt, strLen); break; case 25: command.value = Short.valueOf( LittleEndian.getShort(contents, offset) ); break; case 26: command.value = Integer.valueOf( LittleEndian.getInt(contents, offset) ); break; // Types 11 and 21 hold the offset to the blocks case 11: case 21: if(offset < contents.length - 3) { int bOffset = (int)LittleEndian.getUInt(contents, offset); BlockOffsetCommand bcmd = (BlockOffsetCommand)command; bcmd.setOffset(bOffset); } break; default: logger.log(POILogger.INFO, "Command of type " + type + " not processed!"); } // Add to the array commands.add(command); } // Save the commands we liked the look of - this.commands = (Command[])commands.toArray( + this.commands = commands.toArray( new Command[commands.size()] ); // Now build up the blocks, if we had a command that tells // us where a block is } /** * A command in the visio file. In order to make things fun, * all the chunk actually stores is the value of the command. * You have to have your own lookup table to figure out what * the commands are based on the chunk type. */ public static class Command { protected Object value; private CommandDefinition definition; private Command(CommandDefinition definition, Object value) { this.definition = definition; this.value = value; } private Command(CommandDefinition definition) { this(definition, null); } public CommandDefinition getDefinition() { return definition; } public Object getValue() { return value; } } /** * A special kind of command that is an artificat of how we * process CommandDefinitions, and so doesn't actually exist * in the chunk */ // public static class VirtualCommand extends Command { // private VirtualCommand(CommandDefinition definition) { // super(definition); // } // } /** * A special kind of command that holds the offset to * a block */ public static class BlockOffsetCommand extends Command { private int offset; private BlockOffsetCommand(CommandDefinition definition) { super(definition, null); } private void setOffset(int offset) { this.offset = offset; value = Integer.valueOf(offset); } } } diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java index 67a414176..3a571b8ed 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java @@ -1,80 +1,93 @@ /* ==================================================================== 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.poi.hdgf; import java.io.FileInputStream; import org.apache.poi.hdgf.streams.PointerContainingStream; import org.apache.poi.hdgf.streams.TrailerStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.POIDataSamples; import junit.framework.TestCase; public final class TestHDGFCore extends TestCase { private static POIDataSamples _dgTests = POIDataSamples.getDiagramInstance(); private POIFSFileSystem fs; protected void setUp() throws Exception { fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd")); } public void testCreate() throws Exception { new HDGFDiagram(fs); } public void testTrailer() throws Exception { HDGFDiagram hdgf = new HDGFDiagram(fs); assertNotNull(hdgf); assertNotNull(hdgf.getTrailerStream()); // Check it has what we'd expect TrailerStream trailer = hdgf.getTrailerStream(); assertEquals(0x8a94, trailer.getPointer().getOffset()); assertNotNull(trailer.getPointedToStreams()); assertEquals(20, trailer.getPointedToStreams().length); assertEquals(20, hdgf.getTopLevelStreams().length); // 9th one should have children assertNotNull(trailer.getPointedToStreams()[8]); assertNotNull(trailer.getPointedToStreams()[8].getPointer()); PointerContainingStream ps8 = (PointerContainingStream) trailer.getPointedToStreams()[8]; assertNotNull(ps8.getPointedToStreams()); assertEquals(8, ps8.getPointedToStreams().length); } /** * Tests that we can open a problematic file, that used to * break with a negative chunk length */ public void testNegativeChunkLength() throws Exception { fs = new POIFSFileSystem(_dgTests.openResourceAsStream("NegativeChunkLength.vsd")); HDGFDiagram hdgf = new HDGFDiagram(fs); assertNotNull(hdgf); // And another file fs = new POIFSFileSystem(_dgTests.openResourceAsStream("NegativeChunkLength2.vsd")); hdgf = new HDGFDiagram(fs); assertNotNull(hdgf); } + + /** + * Tests that we can open a problematic file that triggers + * an ArrayIndexOutOfBoundsException when processing the + * chunk commands. + * @throws Exception + */ + public void DISABLEDtestAIOOB() throws Exception { + fs = new POIFSFileSystem(_dgTests.openResourceAsStream("44501.vsd")); + + HDGFDiagram hdgf = new HDGFDiagram(fs); + assertNotNull(hdgf); + } }
false
false
null
null
diff --git a/src/com/glowman/spaceunit/game/GameScreen.java b/src/com/glowman/spaceunit/game/GameScreen.java index 03592b4..2d3c5b4 100644 --- a/src/com/glowman/spaceunit/game/GameScreen.java +++ b/src/com/glowman/spaceunit/game/GameScreen.java @@ -1,217 +1,218 @@ package com.glowman.spaceunit.game; import java.util.ArrayList; import android.util.Log; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.Game; import com.badlogic.gdx.assets.loaders.SoundLoader; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.glowman.spaceunit.Assets; import com.glowman.spaceunit.SoundPlayer; import com.glowman.spaceunit.achievements.AchievementsConrol; import com.glowman.spaceunit.core.Button; import com.glowman.spaceunit.core.FPSViewer; import com.glowman.spaceunit.core.TextButton; import com.glowman.spaceunit.data.GooglePlayData; import com.glowman.spaceunit.game.balance.SpeedCollector; import com.glowman.spaceunit.game.mapObject.Ship; import com.glowman.spaceunit.game.mapObject.enemy.behaviour.core.TouchPad; import com.glowman.spaceunit.game.score.Score; import com.glowman.spaceunit.game.score.ScoreView; import com.glowman.spaceunit.game.strategy.GameStatus; import com.glowman.spaceunit.game.strategy.GameStrategyFactory; import com.glowman.spaceunit.game.strategy.IGameStrategy; public class GameScreen implements Screen { private final Game _game; private int _gameType; private Ship _ship; private IGameStrategy _gameStrategy; private final Sprite _bkg; private final SpriteBatch _drawer; private OrthographicCamera _camera; private GameTouchListener _gameTouchListener; private BitmapFont _font; private ScoreView _scoreView; private Button _pauseButton; private TouchPad _touchPad; private TextButton _returnToMenuBtn; private float _interfaceAlpha; public GameScreen(Game game, OrthographicCamera camera) { _game = game; _camera = camera; _drawer = new SpriteBatch(); _drawer.setProjectionMatrix(_camera.combined); _bkg = new Sprite(Assets.bkg); _bkg.setSize(Assets.FULL_VIRTUAL_WIDTH, Assets.FULL_VIRTUAL_HEIGHT); _bkg.setPosition(Assets.FULL_X_OFFSET, Assets.FULL_Y_OFFSET); this.createInterface(); _gameTouchListener = new GameTouchListener(_game, _pauseButton, _touchPad, _returnToMenuBtn); } public void play(int gameType) { _gameType = gameType; Log.d("hz", "game type : " + _gameType); this.createShip(); _gameTouchListener.setShip(_ship); _gameStrategy = GameStrategyFactory.createStrategy(_ship, _gameType); _gameStrategy.startGame(); _gameTouchListener.init(_gameStrategy); _scoreView.setScoreType(Score.getScoreTypeByGameType(_gameType)); Gdx.input.setInputProcessor(_gameTouchListener); } @Override public void render(float delta) { this.clear(); if (!_gameStrategy.isPaused()) { _gameStrategy.tick(delta); } if (_gameStrategy.getGameStatus() == GameStatus.GAME_OVER) { _gameTouchListener.gameOver(); } _drawer.begin(); _interfaceAlpha = _gameStrategy.isPaused() ? 1 : Assets.GAME_INTERFACE_ALPHA; float bkgAlpha = _gameStrategy.isPaused() ? 1 : Assets.GAME_BKG_ALPHA; _bkg.draw(_drawer, bkgAlpha); ArrayList<Sprite> objects = _gameStrategy.getDrawableObjects(); for (Sprite object : objects) { object.draw(_drawer); } if (_gameStrategy.getGameStatus() == GameStatus.GAME_OVER) { this.drawGameOver(); } this.drawScore(); _pauseButton.draw(_drawer, _interfaceAlpha); if (_gameStrategy.isPaused()) _returnToMenuBtn.draw(_drawer); //_touchPad.act(delta); _touchPad.draw(_drawer, _interfaceAlpha); FPSViewer.draw(_drawer); _drawer.end(); } @Override public void resize(int width, int height) {} @Override public void show() { + _touchPad.updateKnobPosition(); SoundPlayer.playMusic(Assets.backGameSound, .5f); } @Override public void hide() { Gdx.input.setInputProcessor(null); _gameStrategy.stopGame(); this.clear(); SoundPlayer.stopMusic(Assets.backGameSound); } @Override public void pause() { _pauseButton.setClickedMode(); _gameStrategy.pauseGame(); } @Override public void resume() { } @Override public void dispose() { _gameStrategy.stopGame(); } private void createShip() { if (_ship != null) { Log.e("hz", "ship already exists!"); } _ship = new Ship(new Sprite(Assets.ship), 10); _ship.setGeneralSpeed(SpeedCollector.getHeroSpeed(_gameType)); _ship.setPosition(new Vector2(Assets.VIRTUAL_WIDTH / 2, Assets.VIRTUAL_HEIGHT / 2)); } private void drawGameOver() { this.createFont(); Score score = _gameStrategy.getScore(); if (GooglePlayData.gameHelper.isSignedIn()) { AchievementsConrol.checkUnlockAchievement(_gameType, (long)score.score); GooglePlayData.gamesClient.submitScore( GooglePlayData.getLeaderboardID(_gameType), (long)score.score); } String text = "GAME OVER\n" + score.type + " : " + score.getPrintableScore(); BitmapFont.TextBounds bounds = _font.getMultiLineBounds(text); _font.drawMultiLine(_drawer, text, Assets.VIRTUAL_WIDTH/2 - bounds.width/2, (Assets.VIRTUAL_HEIGHT - bounds.height)/2, Assets.VIRTUAL_WIDTH, BitmapFont.HAlignment.LEFT);} private void drawScore() { Score score = _gameStrategy.getScore(); _scoreView.setScore(score.getPrintableScore()); _scoreView.draw(_drawer, _interfaceAlpha); } private void createFont() { if (_font == null) { _font = new BitmapFont(Gdx.files.internal(Assets.gameFontPath), Assets.gameFontRegion, false); _font.setColor(Color.RED); _font.setScale(1f); } } private void clear() { Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } private void createInterface() { this.createTouchPad(); //score panel _scoreView = new ScoreView(); _scoreView.setPosition(Assets.VIRTUAL_WIDTH / 2 - _scoreView.getWidth() / 2, Assets.VIRTUAL_HEIGHT - _scoreView.getHeight()); //pause button _pauseButton = new Button(Assets.getPauseBtn(1), Assets.getPauseBtn(2)); _pauseButton.setPosition(Assets.VIRTUAL_WIDTH - _pauseButton.getWidth() - 15, Assets.VIRTUAL_HEIGHT - _pauseButton.getHeight() - 15); //return to menu button _returnToMenuBtn = new TextButton(Assets.getSimpleBtnRegion(1), Assets.getSimpleBtnRegion(2), "Quit"); _returnToMenuBtn.setPosition(Assets.VIRTUAL_WIDTH/2 - _returnToMenuBtn.getWidth()/2, Assets.VIRTUAL_HEIGHT/2 - _returnToMenuBtn.getHeight()/2); } private void createTouchPad() { Skin skin = new Skin(); skin.add("background", Assets.joyPadBkg); skin.add("knob", Assets.joyPad); TouchPad.TouchpadStyle style = new TouchPad.TouchpadStyle(new TextureRegionDrawable(Assets.joyPadBkg), new TextureRegionDrawable(Assets.joyPad)); _touchPad = new TouchPad(10, style); _touchPad.setPosition(20, 20); } } diff --git a/src/com/glowman/spaceunit/game/mapObject/enemy/behaviour/core/TouchPad.java b/src/com/glowman/spaceunit/game/mapObject/enemy/behaviour/core/TouchPad.java index be429ff..893b1ed 100644 --- a/src/com/glowman/spaceunit/game/mapObject/enemy/behaviour/core/TouchPad.java +++ b/src/com/glowman/spaceunit/game/mapObject/enemy/behaviour/core/TouchPad.java @@ -1,224 +1,223 @@ package com.glowman.spaceunit.game.mapObject.enemy.behaviour.core; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; /** An on-screen joystick. The movement area of the joystick is circular, centered on the touchpad, and its size determined by the * smaller touchpad dimension. * <p> * The preferred size of the touchpad is determined by the background. * <p> * {@link ChangeEvent} is fired when the touchpad knob is moved. Cancelling the event will move the knob to where it was * previously. * @author Josh Street */ public class TouchPad { private TouchpadStyle style; boolean touched; private float deadzoneRadius; private final Circle knobBounds = new Circle(0, 0, 0); private final Circle touchBounds = new Circle(0, 0, 0); private final Circle deadzoneBounds = new Circle(0, 0, 0); private final Vector2 knobPosition = new Vector2(); private final Vector2 knobPercent = new Vector2(); private Vector2 position = new Vector2(0, 0); /** @param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */ public TouchPad (float deadzoneRadius, Skin skin) { this(deadzoneRadius, skin.get(TouchpadStyle.class)); } /** @param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */ public TouchPad (float deadzoneRadius, Skin skin, String styleName) { this(deadzoneRadius, skin.get(styleName, TouchpadStyle.class)); } /** @param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */ public TouchPad (float deadzoneRadius, TouchpadStyle style) { if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0"); this.deadzoneRadius = deadzoneRadius; setStyle(style); knobBounds.set(getWidth()/2, getHeight()/2, getWidth()/2); touchBounds.set(getWidth()/2, getHeight()/2, getWidth()); - knobPosition.set(style.background.getMinWidth() / 2f, style.background.getMinHeight() / 2f); - this.updatePosition(); + this.updateKnobPosition(); //setWidth(getPrefWidth()); //setHeight(getPrefHeight()); } public void setPosition(float x, float y) { this.position.x = x; this.position.y = y; - this.updatePosition(); } public boolean hit(float x, float y) { return touchBounds.contains(x, y); } public void touchDown(float x, float y) { if (touched) return; touched = true; x -= position.x; y -= position.y; calculatePositionAndValue(x, y, false); } public void touchUp(float x, float y) { touched = false; x -= position.x; y -= position.y; calculatePositionAndValue(x, y, true); } public void touchMove(float x, float y) { x -= position.x; y -= position.y; calculatePositionAndValue(x, y, false); } private void calculatePositionAndValue (float x, float y, boolean isTouchUp) { float centerX = knobBounds.x; float centerY = knobBounds.y; knobPosition.set(centerX, centerY); knobPercent.set(0f, 0f); if (!isTouchUp) { if (!deadzoneBounds.contains(x, y)) { knobPercent.set((x - centerX) / knobBounds.radius, (y - centerY) / knobBounds.radius); float length = knobPercent.len(); if (length > 1) knobPercent.scl(1 / length); if (knobBounds.contains(x, y)) { knobPosition.set(x, y); } else { knobPosition.set(knobPercent).nor().scl(knobBounds.radius).add(knobBounds.x, knobBounds.y); } } } // if (oldPercentX != knobPercent.x || oldPercentY != knobPercent.y) { // knobPercent.set(oldPercentX, oldPercentY); // knobPosition.set(oldPositionX, oldPositionY); // } } public void setStyle (TouchpadStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null"); this.style = style; } /** Returns the touchpad's style. Modifying the returned style may not have an effect until {@link #setStyle(TouchpadStyle)} is * called. */ public TouchpadStyle getStyle () { return style; } // public void layout () { // // Recalc pad and deadzone bounds // float halfWidth = getWidth() / 2; // float halfHeight = getHeight() / 2; // float radius = Math.min(halfWidth, halfHeight); // touchBounds.set(halfWidth, halfHeight, radius); // if (style.knob != null) radius -= Math.max(style.knob.getMinWidth(), style.knob.getMinHeight()) / 2; // knobBounds.set(halfWidth, halfHeight, radius); // deadzoneBounds.set(halfWidth, halfHeight, deadzoneRadius); // // Recalc pad values and knob position // knobPosition.set(halfWidth, halfHeight); // knobPercent.set(0, 0); // } // // public void draw (SpriteBatch batch, float parentAlpha) { Color color = batch.getColor(); float oldAlpha = color.a; color.a = parentAlpha; batch.setColor(color); float x = position.x; float y = position.y; float w = style.background.getMinWidth(); float h = style.background.getMinHeight(); final Drawable bg = style.background; bg.draw(batch, x, y, w, h); final Drawable knob = style.knob; x += knobPosition.x - knob.getMinWidth() / 2f; y += knobPosition.y - knob.getMinHeight() / 2f; knob.draw(batch, x, y, knob.getMinWidth(), knob.getMinHeight()); color.a = oldAlpha; batch.setColor(color); } public boolean isTouched () { return touched; } /** @param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */ public void setDeadzone (float deadzoneRadius) { if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0"); this.deadzoneRadius = deadzoneRadius; } /** Returns the x-position of the knob relative to the center of the widget. The positive direction is right. */ public float getKnobX () { return knobPosition.x; } /** Returns the y-position of the knob relative to the center of the widget. The positive direction is up. */ public float getKnobY () { return knobPosition.y; } /** Returns the x-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement * area. The positive direction is right. */ public float getKnobPercentX () { return knobPercent.x; } /** Returns the y-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement * area. The positive direction is up. */ public float getKnobPercentY () { return knobPercent.y; } + public void updateKnobPosition() { + knobPosition.set(style.background.getMinWidth() / 2f, style.background.getMinHeight() / 2f); + } + private float getWidth() { return style.background.getMinWidth(); } private float getHeight() { return style.background.getMinHeight(); } - private void updatePosition() { - } - /** The style for a {@link TouchPad}. * @author Josh Street */ public static class TouchpadStyle { /** Stretched in both directions. Optional. */ public Drawable background; /** Optional. */ public Drawable knob; public TouchpadStyle () { } public TouchpadStyle (Drawable background, Drawable knob) { this.background = background; this.knob = knob; } public TouchpadStyle (TouchpadStyle style) { this.background = style.background; this.knob = style.knob; } } } \ No newline at end of file
false
false
null
null
diff --git a/src/com/android/contacts/ContactsApplication.java b/src/com/android/contacts/ContactsApplication.java index f0e273634..8346c04eb 100644 --- a/src/com/android/contacts/ContactsApplication.java +++ b/src/com/android/contacts/ContactsApplication.java @@ -1,99 +1,101 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import com.android.contacts.model.AccountTypeManager; import com.android.contacts.test.InjectedServices; import android.app.Application; +import android.app.LoaderManager; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.os.StrictMode; import android.preference.PreferenceManager; public final class ContactsApplication extends Application { private static InjectedServices sInjectedServices; private AccountTypeManager mAccountTypeManager; /** * Overrides the system services with mocks for testing. */ public static void injectServices(InjectedServices services) { sInjectedServices = services; } public static InjectedServices getInjectedServices() { return sInjectedServices; } @Override public ContentResolver getContentResolver() { if (sInjectedServices != null) { ContentResolver resolver = sInjectedServices.getContentResolver(); if (resolver != null) { return resolver; } } return super.getContentResolver(); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { if (sInjectedServices != null) { SharedPreferences prefs = sInjectedServices.getSharedPreferences(); if (prefs != null) { return prefs; } } return super.getSharedPreferences(name, mode); } @Override public Object getSystemService(String name) { if (sInjectedServices != null) { Object service = sInjectedServices.getSystemService(name); if (service != null) { return service; } } if (AccountTypeManager.ACCOUNT_TYPE_SERVICE.equals(name)) { if (mAccountTypeManager == null) { mAccountTypeManager = AccountTypeManager.createAccountTypeManager(this); } return mAccountTypeManager; } return super.getSystemService(name); } @Override public void onCreate() { super.onCreate(); // Priming caches to placate the StrictMode police Context context = getApplicationContext(); PreferenceManager.getDefaultSharedPreferences(context); AccountTypeManager.getInstance(context); + LoaderManager.enableDebugLogging(true); StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()); } } diff --git a/src/com/android/contacts/list/ContactEntryListFragment.java b/src/com/android/contacts/list/ContactEntryListFragment.java index e3f5e1c7d..6bdfd9741 100644 --- a/src/com/android/contacts/list/ContactEntryListFragment.java +++ b/src/com/android/contacts/list/ContactEntryListFragment.java @@ -1,948 +1,945 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.list; import com.android.common.widget.CompositeCursorAdapter.Partition; import com.android.contacts.ContactListEmptyView; import com.android.contacts.ContactsSearchManager; import com.android.contacts.R; import com.android.contacts.preference.ContactsPreferences; import com.android.contacts.widget.ContextMenuAdapter; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.Fragment; import android.app.LoaderManager; import android.app.LoaderManager.LoaderCallbacks; import android.content.ContentResolver; import android.content.Context; import android.content.CursorLoader; import android.content.IContentService; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Directory; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; /** * Common base class for various contact-related list fragments. */ public abstract class ContactEntryListFragment<T extends ContactEntryListAdapter> extends Fragment implements OnItemClickListener, OnScrollListener, OnFocusChangeListener, OnTouchListener, LoaderCallbacks<Cursor> { private static final String TAG = "ContactEntryListFragment"; // TODO: Make this protected. This should not be used from the ContactBrowserActivity but // instead use the new startActivityWithResultFromFragment API public static final int ACTIVITY_REQUEST_CODE_PICKER = 1; private static final String KEY_LIST_STATE = "liststate"; private static final String KEY_SECTION_HEADER_DISPLAY_ENABLED = "sectionHeaderDisplayEnabled"; private static final String KEY_PHOTO_LOADER_ENABLED = "photoLoaderEnabled"; private static final String KEY_QUICK_CONTACT_ENABLED = "quickContactEnabled"; private static final String KEY_SEARCH_MODE = "searchMode"; private static final String KEY_VISIBLE_SCROLLBAR_ENABLED = "visibleScrollbarEnabled"; private static final String KEY_SCROLLBAR_POSITION = "scrollbarPosition"; private static final String KEY_QUERY_STRING = "queryString"; private static final String KEY_DIRECTORY_SEARCH_MODE = "directorySearchMode"; private static final String KEY_SELECTION_VISIBLE = "selectionVisible"; private static final String KEY_REQUEST = "request"; private static final String KEY_LEGACY_COMPATIBILITY = "legacyCompatibility"; private static final String KEY_DIRECTORY_RESULT_LIMIT = "directoryResultLimit"; private static final String DIRECTORY_ID_ARG_KEY = "directoryId"; private static final int DIRECTORY_LOADER_ID = -1; private static final int DIRECTORY_SEARCH_DELAY_MILLIS = 300; private static final int DIRECTORY_SEARCH_MESSAGE = 1; private static final int DEFAULT_DIRECTORY_RESULT_LIMIT = 20; private boolean mSectionHeaderDisplayEnabled; private boolean mPhotoLoaderEnabled; private boolean mQuickContactEnabled = true; private boolean mSearchMode; private boolean mVisibleScrollbarEnabled; private int mVerticalScrollbarPosition = View.SCROLLBAR_POSITION_RIGHT; private String mQueryString; private int mDirectorySearchMode = DirectoryListLoader.SEARCH_MODE_NONE; private boolean mSelectionVisible; private ContactsRequest mRequest; private boolean mLegacyCompatibility; private boolean mEnabled = true; private T mAdapter; private View mView; private ListView mListView; /** * Used for keeping track of the scroll state of the list. */ private Parcelable mListState; private int mDisplayOrder; private int mSortOrder; private int mDirectoryResultLimit = DEFAULT_DIRECTORY_RESULT_LIMIT; private ContextMenuAdapter mContextMenuAdapter; private ContactPhotoLoader mPhotoLoader; private ContactListEmptyView mEmptyView; private ProviderStatusLoader mProviderStatusLoader; private ContactsPreferences mContactsPrefs; private boolean mForceLoad; private static final int STATUS_NOT_LOADED = 0; private static final int STATUS_LOADING = 1; private static final int STATUS_LOADED = 2; private int mDirectoryListStatus = STATUS_NOT_LOADED; /** * Indicates whether we are doing the initial complete load of data (false) or * a refresh caused by a change notification (true) */ private boolean mLoadPriorityDirectoriesOnly; private Context mContext; private LoaderManager mLoaderManager; private Handler mDelayedDirectorySearchHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == DIRECTORY_SEARCH_MESSAGE) { loadDirectoryPartition(msg.arg1, (DirectoryPartition) msg.obj); } } }; protected abstract View inflateView(LayoutInflater inflater, ViewGroup container); protected abstract T createListAdapter(); /** * @param position Please note that the position is already adjusted for * header views, so "0" means the first list item below header * views. */ protected abstract void onItemClick(int position, long id); @Override public void onAttach(Activity activity) { super.onAttach(activity); setContext(activity); setLoaderManager(super.getLoaderManager()); } /** * Sets a context for the fragment in the unit test environment. */ public void setContext(Context context) { mContext = context; configurePhotoLoader(); } public Context getContext() { return mContext; } public void setEnabled(boolean enabled) { if (mEnabled != enabled) { mEnabled = enabled; if (mAdapter != null) { if (mEnabled) { reloadData(); } else { mAdapter.clearPartitions(); } } } } /** * Overrides a loader manager for use in unit tests. */ public void setLoaderManager(LoaderManager loaderManager) { mLoaderManager = loaderManager; } @Override public LoaderManager getLoaderManager() { return mLoaderManager; } public T getAdapter() { return mAdapter; } @Override public View getView() { return mView; } public ListView getListView() { return mListView; } public ContactListEmptyView getEmptyView() { return mEmptyView; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_SECTION_HEADER_DISPLAY_ENABLED, mSectionHeaderDisplayEnabled); outState.putBoolean(KEY_PHOTO_LOADER_ENABLED, mPhotoLoaderEnabled); outState.putBoolean(KEY_QUICK_CONTACT_ENABLED, mQuickContactEnabled); outState.putBoolean(KEY_SEARCH_MODE, mSearchMode); outState.putBoolean(KEY_VISIBLE_SCROLLBAR_ENABLED, mVisibleScrollbarEnabled); outState.putInt(KEY_SCROLLBAR_POSITION, mVerticalScrollbarPosition); outState.putInt(KEY_DIRECTORY_SEARCH_MODE, mDirectorySearchMode); outState.putBoolean(KEY_SELECTION_VISIBLE, mSelectionVisible); outState.putBoolean(KEY_LEGACY_COMPATIBILITY, mLegacyCompatibility); outState.putString(KEY_QUERY_STRING, mQueryString); outState.putInt(KEY_DIRECTORY_RESULT_LIMIT, mDirectoryResultLimit); outState.putParcelable(KEY_REQUEST, mRequest); if (mListView != null) { mListState = mListView.onSaveInstanceState(); outState.putParcelable(KEY_LIST_STATE, mListState); } } @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); mContactsPrefs = new ContactsPreferences(mContext); restoreSavedState(savedState); } public void restoreSavedState(Bundle savedState) { if (savedState == null) { return; } mSectionHeaderDisplayEnabled = savedState.getBoolean(KEY_SECTION_HEADER_DISPLAY_ENABLED); mPhotoLoaderEnabled = savedState.getBoolean(KEY_PHOTO_LOADER_ENABLED); mQuickContactEnabled = savedState.getBoolean(KEY_QUICK_CONTACT_ENABLED); mSearchMode = savedState.getBoolean(KEY_SEARCH_MODE); mVisibleScrollbarEnabled = savedState.getBoolean(KEY_VISIBLE_SCROLLBAR_ENABLED); mVerticalScrollbarPosition = savedState.getInt(KEY_SCROLLBAR_POSITION); mDirectorySearchMode = savedState.getInt(KEY_DIRECTORY_SEARCH_MODE); mSelectionVisible = savedState.getBoolean(KEY_SELECTION_VISIBLE); mLegacyCompatibility = savedState.getBoolean(KEY_LEGACY_COMPATIBILITY); mQueryString = savedState.getString(KEY_QUERY_STRING); mDirectoryResultLimit = savedState.getInt(KEY_DIRECTORY_RESULT_LIMIT); mRequest = savedState.getParcelable(KEY_REQUEST); // Retrieve list state. This will be applied in onLoadFinished mListState = savedState.getParcelable(KEY_LIST_STATE); } /** * Returns the parsed intent that started the activity hosting this fragment. */ public ContactsRequest getContactsRequest() { return mRequest; } /** * Sets a parsed intent that started the activity hosting this fragment. */ public void setContactsRequest(ContactsRequest request) { mRequest = request; } @Override public void onStart() { super.onStart(); mContactsPrefs.registerChangeListener(mPreferencesChangeListener); if (mProviderStatusLoader == null) { mProviderStatusLoader = new ProviderStatusLoader(mContext); } mForceLoad = loadPreferences(); mDirectoryListStatus = STATUS_NOT_LOADED; mLoadPriorityDirectoriesOnly = true; startLoading(); } protected void startLoading() { if (mAdapter == null) { // The method was called before the fragment was started return; } configureAdapter(); int partitionCount = mAdapter.getPartitionCount(); for (int i = 0; i < partitionCount; i++) { Partition partition = mAdapter.getPartition(i); if (partition instanceof DirectoryPartition) { DirectoryPartition directoryPartition = (DirectoryPartition)partition; if (directoryPartition.getStatus() == DirectoryPartition.STATUS_NOT_LOADED) { if (directoryPartition.isPriorityDirectory() || !mLoadPriorityDirectoriesOnly) { startLoadingDirectoryPartition(i); } } } else { getLoaderManager().initLoader(i, null, this); } } // Next time this method is called, we should start loading non-priority directories mLoadPriorityDirectoriesOnly = false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == DIRECTORY_LOADER_ID) { DirectoryListLoader loader = new DirectoryListLoader(mContext); mAdapter.configureDirectoryLoader(loader); return loader; } else { CursorLoader loader = new CursorLoader(mContext, null, null, null, null, null); long directoryId = args != null && args.containsKey(DIRECTORY_ID_ARG_KEY) ? args.getLong(DIRECTORY_ID_ARG_KEY) : Directory.DEFAULT; mAdapter.configureLoader(loader, directoryId); return loader; } } private void startLoadingDirectoryPartition(int partitionIndex) { DirectoryPartition partition = (DirectoryPartition)mAdapter.getPartition(partitionIndex); partition.setStatus(DirectoryPartition.STATUS_LOADING); long directoryId = partition.getDirectoryId(); if (mForceLoad) { if (directoryId == Directory.DEFAULT) { loadDirectoryPartition(partitionIndex, partition); } else { loadDirectoryPartitionDelayed(partitionIndex, partition); } } else { Bundle args = new Bundle(); args.putLong(DIRECTORY_ID_ARG_KEY, directoryId); getLoaderManager().initLoader(partitionIndex, args, this); } } /** * Queues up a delayed request to search the specified directory. Since * directory search will likely introduce a lot of network traffic, we want * to wait for a pause in the user's typing before sending a directory request. */ private void loadDirectoryPartitionDelayed(int partitionIndex, DirectoryPartition partition) { mDelayedDirectorySearchHandler.removeMessages(DIRECTORY_SEARCH_MESSAGE, partition); Message msg = mDelayedDirectorySearchHandler.obtainMessage( DIRECTORY_SEARCH_MESSAGE, partitionIndex, 0, partition); mDelayedDirectorySearchHandler.sendMessageDelayed(msg, DIRECTORY_SEARCH_DELAY_MILLIS); } /** * Loads the directory partition. */ protected void loadDirectoryPartition(int partitionIndex, DirectoryPartition partition) { Bundle args = new Bundle(); args.putLong(DIRECTORY_ID_ARG_KEY, partition.getDirectoryId()); getLoaderManager().restartLoader(partitionIndex, args, this); } /** * Cancels all queued directory loading requests. */ private void removePendingDirectorySearchRequests() { mDelayedDirectorySearchHandler.removeMessages(DIRECTORY_SEARCH_MESSAGE); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (!mEnabled) { - if (data != null) { - data.close(); - } return; } int loaderId = loader.getId(); if (loaderId == DIRECTORY_LOADER_ID) { mDirectoryListStatus = STATUS_LOADED; mAdapter.changeDirectories(data); startLoading(); } else { onPartitionLoaded(loaderId, data); if (isSearchMode()) { int directorySearchMode = getDirectorySearchMode(); if (directorySearchMode != DirectoryListLoader.SEARCH_MODE_NONE) { if (mDirectoryListStatus == STATUS_NOT_LOADED) { mDirectoryListStatus = STATUS_LOADING; getLoaderManager().initLoader(DIRECTORY_LOADER_ID, null, this); } else { startLoading(); } } } else { mDirectoryListStatus = STATUS_NOT_LOADED; getLoaderManager().destroyLoader(DIRECTORY_LOADER_ID); } } } public void onLoaderReset(Loader<Cursor> loader) { } protected void onPartitionLoaded(int partitionIndex, Cursor data) { mAdapter.changeCursor(partitionIndex, data); showCount(partitionIndex, data); if (!isLoading()) { completeRestoreInstanceState(); } } public boolean isLoading() { if (mAdapter != null && mAdapter.isLoading()) { return true; } if (isLoadingDirectoryList()) { return true; } return false; } public boolean isLoadingDirectoryList() { return isSearchMode() && getDirectorySearchMode() != DirectoryListLoader.SEARCH_MODE_NONE && (mDirectoryListStatus == STATUS_NOT_LOADED || mDirectoryListStatus == STATUS_LOADING); } @Override public void onStop() { super.onStop(); mContactsPrefs.unregisterChangeListener(); mAdapter.clearPartitions(); } protected void reloadData() { removePendingDirectorySearchRequests(); mAdapter.onDataReload(); mLoadPriorityDirectoriesOnly = true; mForceLoad = true; startLoading(); } /** * Configures the empty view. It is called when we are about to populate * the list with an empty cursor. */ protected void prepareEmptyView() { } /** * Shows the count of entries included in the list. The default * implementation does nothing. */ protected void showCount(int partitionIndex, Cursor data) { } /** * Provides logic that dismisses this fragment. The default implementation * does nothing. */ protected void finish() { } public void setSectionHeaderDisplayEnabled(boolean flag) { if (mSectionHeaderDisplayEnabled != flag) { mSectionHeaderDisplayEnabled = flag; if (mAdapter != null) { mAdapter.setSectionHeaderDisplayEnabled(flag); } configureVerticalScrollbar(); } } public boolean isSectionHeaderDisplayEnabled() { return mSectionHeaderDisplayEnabled; } public void setVisibleScrollbarEnabled(boolean flag) { if (mVisibleScrollbarEnabled != flag) { mVisibleScrollbarEnabled = flag; configureVerticalScrollbar(); } } public boolean isVisibleScrollbarEnabled() { return mVisibleScrollbarEnabled; } public void setVerticalScrollbarPosition(int position) { if (mVerticalScrollbarPosition != position) { mVerticalScrollbarPosition = position; configureVerticalScrollbar(); } } private void configureVerticalScrollbar() { boolean hasScrollbar = isVisibleScrollbarEnabled() && isSectionHeaderDisplayEnabled(); if (mListView != null) { mListView.setFastScrollEnabled(hasScrollbar); mListView.setFastScrollAlwaysVisible(hasScrollbar); mListView.setVerticalScrollbarPosition(mVerticalScrollbarPosition); int leftPadding = 0; int rightPadding = 0; if (mVerticalScrollbarPosition == View.SCROLLBAR_POSITION_LEFT) { leftPadding = mContext.getResources().getDimensionPixelOffset( R.dimen.list_visible_scrollbar_padding); } else if (hasScrollbar){ rightPadding = mContext.getResources().getDimensionPixelOffset( R.dimen.list_visible_scrollbar_padding); } mListView.setPadding(leftPadding, mListView.getPaddingTop(), rightPadding, mListView.getPaddingBottom()); } } public void setPhotoLoaderEnabled(boolean flag) { mPhotoLoaderEnabled = flag; configurePhotoLoader(); } public boolean isPhotoLoaderEnabled() { return mPhotoLoaderEnabled; } /** * Returns true if the list is supposed to visually highlight the selected item. */ public boolean isSelectionVisible() { return mSelectionVisible; } public void setSelectionVisible(boolean flag) { this.mSelectionVisible = flag; } public void setQuickContactEnabled(boolean flag) { this.mQuickContactEnabled = flag; } public void setSearchMode(boolean flag) { if (mSearchMode != flag) { mSearchMode = flag; setSectionHeaderDisplayEnabled(!mSearchMode); if (!flag) { mDirectoryListStatus = STATUS_NOT_LOADED; getLoaderManager().destroyLoader(DIRECTORY_LOADER_ID); } if (mAdapter != null) { mAdapter.setPinnedPartitionHeadersEnabled(flag); mAdapter.setSearchMode(flag); mAdapter.clearPartitions(); if (!flag) { // If we are switching from search to regular display, // remove all directory partitions (except the default one). int count = mAdapter.getPartitionCount(); for (int i = count; --i >= 1;) { mAdapter.removePartition(i); } } mAdapter.configureDefaultPartition(false, flag); reloadData(); } if (mListView != null) { mListView.setFastScrollEnabled(!flag); } } } public boolean isSearchMode() { return mSearchMode; } public String getQueryString() { return mQueryString; } public void setQueryString(String queryString, boolean delaySelection) { if (!TextUtils.equals(mQueryString, queryString)) { mQueryString = queryString; if (mAdapter != null) { mAdapter.setQueryString(queryString); reloadData(); } } } public int getDirectorySearchMode() { return mDirectorySearchMode; } public void setDirectorySearchMode(int mode) { mDirectorySearchMode = mode; } public boolean isLegacyCompatibilityMode() { return mLegacyCompatibility; } public void setLegacyCompatibilityMode(boolean flag) { mLegacyCompatibility = flag; } protected int getContactNameDisplayOrder() { return mDisplayOrder; } protected void setContactNameDisplayOrder(int displayOrder) { mDisplayOrder = displayOrder; if (mAdapter != null) { mAdapter.setContactNameDisplayOrder(displayOrder); } } public int getSortOrder() { return mSortOrder; } public void setSortOrder(int sortOrder) { mSortOrder = sortOrder; if (mAdapter != null) { mAdapter.setSortOrder(sortOrder); } } public void setDirectoryResultLimit(int limit) { mDirectoryResultLimit = limit; } public void setContextMenuAdapter(ContextMenuAdapter adapter) { mContextMenuAdapter = adapter; if (mListView != null) { mListView.setOnCreateContextMenuListener(adapter); } } public ContextMenuAdapter getContextMenuAdapter() { return mContextMenuAdapter; } protected boolean loadPreferences() { boolean changed = false; if (getContactNameDisplayOrder() != mContactsPrefs.getDisplayOrder()) { setContactNameDisplayOrder(mContactsPrefs.getDisplayOrder()); changed = true; } if (getSortOrder() != mContactsPrefs.getSortOrder()) { setSortOrder(mContactsPrefs.getSortOrder()); changed = true; } if (mListView instanceof ContactEntryListView) { ContactEntryListView listView = (ContactEntryListView)mListView; listView.setHighlightNamesWhenScrolling(isNameHighlighingEnabled()); } return changed; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { onCreateView(inflater, container); mAdapter = createListAdapter(); boolean searchMode = isSearchMode(); mAdapter.setSearchMode(searchMode); mAdapter.configureDefaultPartition(false, searchMode); mAdapter.setPhotoLoader(mPhotoLoader); mListView.setAdapter(mAdapter); if (!isSearchMode()) { mListView.setFocusableInTouchMode(true); mListView.requestFocus(); } return mView; } protected void onCreateView(LayoutInflater inflater, ViewGroup container) { mView = inflateView(inflater, container); mListView = (ListView)mView.findViewById(android.R.id.list); if (mListView == null) { throw new RuntimeException( "Your content must have a ListView whose id attribute is " + "'android.R.id.list'"); } View emptyView = mView.findViewById(com.android.internal.R.id.empty); if (emptyView != null) { mListView.setEmptyView(emptyView); if (emptyView instanceof ContactListEmptyView) { mEmptyView = (ContactListEmptyView)emptyView; } } mListView.setOnItemClickListener(this); mListView.setOnFocusChangeListener(this); mListView.setOnTouchListener(this); mListView.setFastScrollEnabled(!isSearchMode()); // Tell list view to not show dividers. We'll do it ourself so that we can *not* show // them when an A-Z headers is visible. mListView.setDividerHeight(0); // We manually save/restore the listview state mListView.setSaveEnabled(false); if (mContextMenuAdapter != null) { mListView.setOnCreateContextMenuListener(mContextMenuAdapter); } configureVerticalScrollbar(); configurePhotoLoader(); } protected void configurePhotoLoader() { if (isPhotoLoaderEnabled() && mContext != null) { if (mPhotoLoader == null) { mPhotoLoader = new ContactPhotoLoader(mContext, R.drawable.ic_contact_picture); } if (mListView != null) { mListView.setOnScrollListener(this); } if (mAdapter != null) { mAdapter.setPhotoLoader(mPhotoLoader); } } } protected void configureAdapter() { if (mAdapter == null) { return; } mAdapter.setQuickContactEnabled(mQuickContactEnabled); mAdapter.setQueryString(mQueryString); mAdapter.setDirectorySearchMode(mDirectorySearchMode); mAdapter.setPinnedPartitionHeadersEnabled(mSearchMode); mAdapter.setContactNameDisplayOrder(mDisplayOrder); mAdapter.setSortOrder(mSortOrder); mAdapter.setNameHighlightingEnabled(isNameHighlighingEnabled()); mAdapter.setSectionHeaderDisplayEnabled(mSectionHeaderDisplayEnabled); mAdapter.setSelectionVisible(mSelectionVisible); mAdapter.setDirectoryResultLimit(mDirectoryResultLimit); } protected boolean isNameHighlighingEnabled() { // When sort order and display order contradict each other, we want to // highlight the part of the name used for sorting. if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_ALTERNATIVE) { return true; } else if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_ALTERNATIVE && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { return true; } else { return false; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_FLING) { mPhotoLoader.pause(); } else if (isPhotoLoaderEnabled()) { mPhotoLoader.resume(); } } @Override public void onResume() { super.onResume(); if (isPhotoLoaderEnabled()) { mPhotoLoader.resume(); } } @Override public void onDestroy() { if (isPhotoLoaderEnabled()) { mPhotoLoader.stop(); } super.onDestroy(); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { hideSoftKeyboard(); int adjPosition = position - mListView.getHeaderViewsCount(); if (adjPosition >= 0) { onItemClick(adjPosition, id); } } private void hideSoftKeyboard() { // Hide soft keyboard, if visible InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mListView.getWindowToken(), 0); } /** * Dismisses the soft keyboard when the list takes focus. */ public void onFocusChange(View view, boolean hasFocus) { if (view == mListView && hasFocus) { hideSoftKeyboard(); } } /** * Dismisses the soft keyboard when the list is touched. */ public boolean onTouch(View view, MotionEvent event) { if (view == mListView) { hideSoftKeyboard(); } return false; } @Override public void onPause() { super.onPause(); removePendingDirectorySearchRequests(); } /** * Dismisses the search UI along with the keyboard if the filter text is empty. */ public void onClose() { hideSoftKeyboard(); finish(); } /** * Restore the list state after the adapter is populated. */ protected void completeRestoreInstanceState() { if (mListState != null) { mListView.onRestoreInstanceState(mListState); mListState = null; } } protected void setEmptyText(int resourceId) { TextView empty = (TextView) getEmptyView().findViewById(R.id.emptyText); empty.setText(mContext.getText(resourceId)); empty.setVisibility(View.VISIBLE); } // TODO redesign into an async task or loader protected boolean isSyncActive() { Account[] accounts = AccountManager.get(mContext).getAccounts(); if (accounts != null && accounts.length > 0) { IContentService contentService = ContentResolver.getContentService(); for (Account account : accounts) { try { if (contentService.isSyncActive(account, ContactsContract.AUTHORITY)) { return true; } } catch (RemoteException e) { Log.e(TAG, "Could not get the sync status"); } } } return false; } protected boolean hasIccCard() { TelephonyManager telephonyManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE); return telephonyManager.hasIccCard(); } /** * Processes a user request to start search. This may be triggered by the * search key, a menu item or some other user action. */ public void startSearch(String initialQuery) { ContactsSearchManager.startSearch(getActivity(), initialQuery, mRequest); } /** * Processes a result returned by the contact picker. */ public void onPickerResult(Intent data) { throw new UnsupportedOperationException("Picker result handler is not implemented."); } private ContactsPreferences.ChangeListener mPreferencesChangeListener = new ContactsPreferences.ChangeListener() { @Override public void onChange() { loadPreferences(); reloadData(); } }; }
false
false
null
null
diff --git a/src/Main/Client.java b/src/Main/Client.java index e41701b..f221b16 100644 --- a/src/Main/Client.java +++ b/src/Main/Client.java @@ -1,462 +1,465 @@ package Main; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.ArrayList; import org.apache.shiro.session.Session; /** * Provides an extensible framework to do public and private calculations Can be * extended to provide degrees within this black or white type casting * * @author Cole Christie * */ public class Client { private Logging mylog; private Networking ServerNetwork; private Networking DropOffNetwork; private Auth subject; private Crypto cryptSVR; private Crypto cryptDO; private Session clientSession; /** * s CONSTRUCTOR */ public Client(Logging passedLog, Auth passedSubject, Session passedSession) { mylog = passedLog; subject = passedSubject; clientSession = passedSession; } /** * This displays the CLI menu and advertised commands */ private void DisplayMenu() { System.out.println("======================================================================"); System.out.println("Commands are:"); System.out.println("QUIT - Closes connection with the server and quits"); System.out.println("REKEY - Rekeys encryption between the client and the server"); System.out.println("JOB - Requests a job from the server"); System.out.println("HELP - Displays this menu"); System.out.println("* - Anything else is sent to the server and echo'ed back"); System.out.println("======================================================================"); } /** * Handles the creation and main thread of client activity * * @param passedPort * @param passedTarget */ public void StartClient(int SERVERpassedPort, String SERVERpassedTarget, int DROPOFFpassedPort, String DROPOFFpassedTarget) { // TODO Setup a parameter to put the client into an endless loop of job // requests. In that loop, when jobs are missing sleep - after a certain // number of cycles quit // Connect to the server // Start up client networking ServerNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget); // Bring the created socket into this scope Socket ServerSock = ServerNetwork.PassBackClient(); // Bind I/O to the socket ServerNetwork.BringUp(ServerSock); System.out.println("Connected to Server [" + SERVERpassedTarget + "] on port [" + SERVERpassedPort + "]"); // Connect to the drop off // Start up client networking DropOffNetwork = new Networking(mylog, DROPOFFpassedPort, DROPOFFpassedTarget); // Bring the created socket into this scope Socket DropOffSock = DropOffNetwork.PassBackClient(); // Bind I/O to the socket DropOffNetwork.BringUp(DropOffSock); System.out.println("Connected to Drop Off [" + DROPOFFpassedTarget + "] on port [" + DROPOFFpassedPort + "]"); // Prepare the interface String UserInput = ""; String ServerResponse = null; // Load client identification data String OS = (String) clientSession.getAttribute("OS"); String SecLev = (String) clientSession.getAttribute("SecurityLevel"); String ClientID = (String) clientSession.getAttribute("ID"); // Display the UI boilerplate DisplayMenu(); // Activate crypto cryptSVR = new Crypto(mylog, subject.GetPSK(), "Server"); cryptDO = new Crypto(mylog, subject.GetPSK(), "Drop Off Point"); // Test bi-directional encryption is working String rawTest = "Testing!!!12345"; byte[] testdata = cryptSVR.encrypt(rawTest); // Craft test // Test the SERVER ServerNetwork.Send(testdata); // Send test byte[] fetched = ServerNetwork.ReceiveByte(); // Receive return response String dec = cryptSVR.decrypt(fetched); // Decrypt if (dec.equals(rawTest + "<S>")) { mylog.out("INFO", "Functional bi-directional encryption established. (Server)"); } else { mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Server)"); mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Server)"); ServerNetwork.BringDown(); try { ServerSock.close(); } catch (IOException e) { mylog.out("ERROR", "Failed to close client socket (Server)"); } System.exit(0); } // Test the DROPOFF testdata = cryptDO.encrypt(rawTest); // Craft test DropOffNetwork.Send(testdata); // Send test fetched = DropOffNetwork.ReceiveByte(); // Receive return response dec = cryptDO.decrypt(fetched); // Decrypt if (dec.equals(rawTest + "<S>")) { mylog.out("INFO", "Functional bi-directional encryption established. (Drop Off)"); } else { mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Drop Off)"); mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Drop Off)"); DropOffNetwork.BringDown(); try { ServerSock.close(); } catch (IOException e) { mylog.out("ERROR", "Failed to close client socket (Drop Off)"); } System.exit(0); } // Use DH to change encryption key DHrekey(ServerNetwork, cryptSVR, "Server"); DHrekey(DropOffNetwork, cryptDO, "Drop Off"); // Begin UI loop int MaxBeforeREKEY = 100; int Current = 0; boolean serverUp = true; boolean flagJob = false; boolean noSend = false; + boolean NewServerResponse = false; while ((UserInput.compareToIgnoreCase("quit") != 0) && (ServerSock.isConnected()) && (DropOffSock.isConnected())) { //Do not send empty strings if (UserInput.length() == 0) { noSend = true; } // Main server/client communication code block if (noSend) { // We do not send anything to the server this time, but we will // reset the boolean flag so we will next time noSend = false; } else { // Communicate with the server ServerNetwork.Send(cryptSVR.encrypt(UserInput)); fetched = ServerNetwork.ReceiveByte(); ServerResponse = cryptSVR.decrypt(fetched); if (ServerResponse == null) { mylog.out("WARN", "Server disconected"); serverUp = false; break; } + NewServerResponse = true; } // If this is the client receiving a job from the server if (flagJob) { if (ServerResponse.length() > 0) { // Print out the job the server has passed us (the client) System.out.println("JobIn:[" + ServerResponse + "]"); // Adjust the job so it can properly run (Windows clients // require some padding at the front) if (OS.contains("Windows")) { // Pad the job with the required Windows shell ServerResponse = "cmd /C " + ServerResponse; } try { /* * Some of the code in this section is from the * following URL http://www.javaworld * .com/jw-12-2000/jw-1229-traps.html?page=4 * * It provides a simple way of calling external code * while still capturing all of the output (STD and * STDERR) * * @author Michael C. Daconta */ // Setup and Connect ArrayList<String> ErrorData = new ArrayList<String>(); ArrayList<String> OutputData = new ArrayList<String>(); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(ServerResponse); // Capture all STDERR StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); errorGobbler.start(); // Capture all STDOUT StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); outputGobbler.start(); // Wait for the work to complete int CheckExit = 0; try { CheckExit = proc.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } if (CheckExit != 0) { System.out.println("ExitValue: " + CheckExit); } else { ErrorData = errorGobbler.ReturnData(); OutputData = outputGobbler.ReturnData(); // Send the results to the Drop Off point // TODO send completed work to drop off point for (String line : ErrorData) { System.out.println("Error:" + line); } for (String line : OutputData) { System.out.println("Output:" + line); } } } catch (IOException e) { e.printStackTrace(); } // Inform the Server that the work has been completed UserInput = "workdone"; ServerNetwork.Send(cryptSVR.encrypt(UserInput)); fetched = ServerNetwork.ReceiveByte(); ServerResponse = cryptSVR.decrypt(fetched); if (ServerResponse == null) { mylog.out("WARN", "Server disconected"); serverUp = false; break; } System.out.println(ServerResponse); } else { System.out.println("Job:[No jobs available]"); } flagJob = false; - } else { + } else if(NewServerResponse) { System.out.println(ServerResponse); + NewServerResponse = false; } UserInput = readUI().toLowerCase(); // Check input for special commands if ((UserInput.contains("rekey")) && serverUp) { UserInput = "Rekey executed."; DHrekey(ServerNetwork, cryptSVR, "Server"); DHrekey(DropOffNetwork, cryptDO, "Drop Off"); Current = 0; } else if (UserInput.contains("job")) { flagJob = true; // Flags the use of a slightly different display UserInput = "job" + ":" + ClientID + ":" + OS + ":" + SecLev; } else if (UserInput.contains("help")) { // Do not send anything, a help request stays local noSend = true; DisplayMenu(); } // Check for forced rekey interval if (Current == MaxBeforeREKEY) { DHrekey(ServerNetwork, cryptSVR, "Server"); DHrekey(DropOffNetwork, cryptDO, "Drop Off"); Current = 0; } else { Current++; } } if ((UserInput.compareToIgnoreCase("quit") == 0) && serverUp) { ServerNetwork.Send(cryptSVR.encrypt("quit")); DropOffNetwork.Send(cryptDO.encrypt("quit")); } // Client has quit or server shutdown ServerNetwork.BringDown(); DropOffNetwork.BringDown(); try { ServerSock.close(); DropOffSock.close(); } catch (IOException e) { mylog.out("ERROR", "Failed to close client socket"); } mylog.out("INFO", "Client terminated"); } /** * Reads input provided by the user, returns a string * * @return */ private String readUI() { System.out.flush(); System.out.print("> "); System.out.flush(); String data = null; BufferedReader inputHandle = new BufferedReader(new InputStreamReader(System.in)); boolean wait = true; while (wait) { try { if (inputHandle.ready()) { wait = false; } else { try { Thread.sleep(10); } catch (InterruptedException e) { mylog.out("ERROR", "Failed to sleep"); } } } catch (IOException err) { mylog.out("ERROR", "Failed to check if buffered input was ready [" + err + "]"); } } try { data = inputHandle.readLine(); } catch (IOException err) { mylog.out("ERROR", "Failed to collect user input [" + err + "]"); } return data; } /** * Starts a DH rekey between the client and the server */ private void DHrekey(Networking network, Crypto crypt, String ReKeyedWith) { // Prep byte[] fetched = null; String ServerResponse = null; // Create a DH instance and generate a PRIME and BASE DH myDH = new DH(mylog); // Share data with the server network.Send(crypt.encrypt("<REKEY>")); RecieveACK(network, crypt); // Wait for ACK network.Send(crypt.encrypt("<PRIME>")); RecieveACK(network, crypt); // Wait for ACK network.Send(crypt.encrypt(myDH.GetPrime(16))); RecieveACK(network, crypt); // Wait for ACK network.Send(crypt.encrypt("<BASE>")); RecieveACK(network, crypt); // Wait for ACK network.Send(crypt.encrypt(myDH.GetBase(16))); RecieveACK(network, crypt); // Wait for ACK // Validate server agrees with what has been sent fetched = network.ReceiveByte(); SendACK(network, crypt); // Send ACK ServerResponse = crypt.decrypt(fetched); if (ServerResponse.compareToIgnoreCase("<REKEY-STARTING>") != 0) { mylog.out("ERROR", ReKeyedWith + " has failed to acknowledge re-keying!"); } // Phase 1 of DH myDH.DHPhase1(); // Send my public DH key to SERVER network.Send(crypt.encrypt("<PUBLICKEY>")); RecieveACK(network, crypt); // Wait for ACK network.Send(crypt.encrypt(myDH.GetPublicKeyBF())); RecieveACK(network, crypt); // Wait for ACK // Validate server agrees with what has been sent fetched = network.ReceiveByte(); SendACK(network, crypt); // Send ACK ServerResponse = crypt.decrypt(fetched); if (ServerResponse.compareToIgnoreCase("<PubKey-GOOD>") != 0) { mylog.out("ERROR", ReKeyedWith + " has failed to acknowledge client public key!"); } // Receive server public DH key byte[] serverPublicKey = null; fetched = network.ReceiveByte(); SendACK(network, crypt); // Send ACK(); //Send ACK ServerResponse = crypt.decrypt(fetched); if (ServerResponse.compareToIgnoreCase("<PUBLICKEY>") != 0) { mylog.out("ERROR", ReKeyedWith + " has failed to send its public key!"); } else { fetched = network.ReceiveByte(); SendACK(network, crypt); // Send ACK(); //Send ACK serverPublicKey = crypt.decryptByte(fetched); network.Send(crypt.encrypt("<PubKey-GOOD>")); RecieveACK(network, crypt); // Wait for ACK } // Use server DH public key to generate shared secret myDH.DHPhase2(myDH.CraftPublicKey(serverPublicKey), ReKeyedWith); // Final verification // System.out.println("Shared Secret (Hex): " + // myDH.GetSharedSecret(10)); crypt.ReKey(myDH.GetSharedSecret(10), ReKeyedWith); } /** * Provides message synchronization */ private void SendACK(Networking network, Crypto crypt) { network.Send(crypt.encrypt("<ACK>")); if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) { mylog.out("ERROR", "Partner failed to ACK"); } } /** * Provides message synchronization */ private void RecieveACK(Networking network, Crypto crypt) { if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) { mylog.out("ERROR", "Partner failed to ACK"); } network.Send(crypt.encrypt("<ACK>")); } } /** * This code is a variation of the code from the following URL * http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=4 * * It is useful in catching all of the output of an executed sub-process and has * not been altered from its initial state * * @author Michael C. Daconta * */ class StreamGobbler extends Thread { InputStream is; String type; ArrayList<String> Collect; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; Collect = new ArrayList<String>(); } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { Collect.add(line); } } catch (IOException ioe) { ioe.printStackTrace(); } } public ArrayList<String> ReturnData() { return Collect; } } diff --git a/src/Main/ServerThread.java b/src/Main/ServerThread.java index 3d5df9f..c0c5ec7 100644 --- a/src/Main/ServerThread.java +++ b/src/Main/ServerThread.java @@ -1,394 +1,401 @@ package Main; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; /** * Provides threads for the server so multiple clients can be handled by a * single server * * @author Cole Christie * */ public class ServerThread extends Thread { private Logging mylog; private Socket socket; private Networking network; private Auth subject; private int UID; private Crypto crypt; private Object JobLock; private JobManagement JobQueue; private boolean ServerMode; /** * CONSTRUCTOR for Server Worker Thread */ public ServerThread(Auth passedSubject, Logging passedLog, Socket passedSocket, int passedUID, Object passedLock, JobManagement passedJobQueue, boolean PassedMode) { subject = passedSubject; mylog = passedLog; socket = passedSocket; UID = passedUID; JobLock = passedLock; JobQueue = passedJobQueue; ServerMode = PassedMode; network = new Networking(mylog); } /** * CONSTRUCTOR for Server Management Thread */ public ServerThread(Logging passedLog, Object passedLock, JobManagement passedJobQueue) { mylog = passedLog; JobLock = passedLock; JobQueue = passedJobQueue; } /** * Runs the Job loading framework based upon the execution request passed to * it (string argument). * * @param type * @return */ public void JobLoader(String type) { synchronized (JobLock) { if (type.compareToIgnoreCase("sw") == 0) { JobQueue.SampleWindows(); mylog.out("INFO", "Loaded 10 sample jobs (Windows)."); } else if (type.compareToIgnoreCase("sl") == 0) { JobQueue.SampleLinux(); mylog.out("INFO", "Loaded 10 sample jobs (Linux/UNIX)."); } else if (type.compareToIgnoreCase("sa") == 0) { JobQueue.Sample(); mylog.out("INFO", "Loaded 10 sample jobs (Any OS)."); } else if (type.compareToIgnoreCase("cuq") == 0) { JobQueue.ClearUnsentQueue(); mylog.out("INFO", "Unassigned job queue reset."); } else if (type.compareToIgnoreCase("caq") == 0) { JobQueue.ClearSentQueue(); mylog.out("INFO", "Assigned job queue reset."); } else if (type.compareToIgnoreCase("list") == 0) { mylog.out("INFO", "[" + JobQueue.UnassignedCount() + "] unassigned jobs are left in the queue"); mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress"); } // TODO add "load" option } } /** * Runs the Job loading framework based upon the execution request passed to * it (string argument). Returns the count (int) of the number of jobs that * were loaded. * * @param type * @return */ public void JobLoader(String type, String filename) { int QtyJobsLoaded = 0; synchronized (JobLock) { if (type.compareToIgnoreCase("load") == 0) { try { QtyJobsLoaded = JobQueue.Load(filename); } catch (IOException e) { mylog.out("ERROR", "Failed to load jobs from file [" + filename + "]"); } mylog.out("INFO", "Loaded [" + QtyJobsLoaded + "] jobs."); } } } /** * Assigns a job to the client in the system and returns a string that has * the requested jobs instructions * * @param clientID * @return */ public String AssignJob(String clientID, String OS, int ClientSecurityLevel) { String job = ""; synchronized (JobLock) { job = JobQueue.Assign(clientID, OS, ClientSecurityLevel); } return job; } /** * Server thread Enables multi-client support */ public void run() { // TODO Refactor so this can be used for both the SERVER and the DROPOFF // UID is just an iterator from the server side // It has no bearing on anything besides the raw question // "How many have connected to this single runtime?" mylog.out("INFO", "Establishing session with client number [" + UID + "]"); // Load and save the cleints IP and port for future UUID creation SocketAddress theirAddress = socket.getRemoteSocketAddress(); String ClientIP = theirAddress.toString(); ClientIP = ClientIP.replace("/", ""); // Bind I/O to the socket network.BringUp(socket); // Prep String fromClient = null; // Activate crypto crypt = new Crypto(mylog, subject.GetPSK(), "Client"); byte[] fetched = network.ReceiveByte(); String dec = crypt.decrypt(fetched); String craftReturn = dec + "<S>"; mylog.out("INFO", "Validating encryption with handshake."); byte[] returnData = crypt.encrypt(craftReturn); network.Send(returnData); // Main Loop while (!socket.isClosed()) { // Collect data sent over the network fetched = network.ReceiveByte(); if (fetched == null) { mylog.out("WARN", "Client disconnected abruptly"); break; } // Decrypt sent data fromClient = crypt.decrypt(fetched); // Pre-calculate meta data from passed arguments // (for job distribution) String ClientName = ClientIP; boolean ClientMetaSet = false; String ClientOS = ""; int ClientSecurityLevel = 0; if (fromClient == null) { mylog.out("WARN", "Client disconnected abruptly"); break; } // If this is a SERVER if (ServerMode) { // Preliminary scanning and data input manipulation if (fromClient.toLowerCase().contains("job")) { String[] CHOP = fromClient.split(":"); // Add the random number passed to us to the servers UID of // this client session to create a reasonable UUID if (CHOP.length == 4) { // Extract meta data if (!ClientMetaSet) { // Only set this once ClientName = ClientName + CHOP[1]; ClientOS = CHOP[2]; ClientSecurityLevel = Integer.parseInt(CHOP[3]); ClientMetaSet = true; } // Assign a job to the client mylog.out("INFO", "Client [" + ClientName + "] with security level [" + ClientSecurityLevel + "] reuested a job for [" + ClientOS + "]"); synchronized (JobLock) { String work = JobQueue.Assign(ClientName, ClientOS, ClientSecurityLevel); returnData = crypt.encrypt(work); network.Send(returnData); if (work.length() > 0) { mylog.out("INFO", "JobOut:[" + work + "]"); mylog.out("INFO", "[" + JobQueue.UnassignedCount() + "] unassigned jobs are left in the queue"); mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress"); } else { mylog.out("WARN", "There are no jobs for [" + ClientOS + "] with Security Level [" + ClientSecurityLevel + "]"); } } } else { // The client failed to send all of the meta data we // need, so abort the job request - fromClient = "Job request failed. Missing meta data in request."; + fromClient = ""; + mylog.out("INFO", "Job request failed. Missing meta data in request."); } } else if (fromClient.toLowerCase().contains("workdone")) { if (ClientMetaSet) { synchronized (JobLock) { String work = JobQueue.Signoff(ClientName); if (work.equalsIgnoreCase("Failed")) { // The job was not able to be acknowledged mylog.out("WARN", "Client [" + ClientName + "] job complete was NOT acknowledged (no was job assigned previously)."); } else { mylog.out("INFO", "Client [" + ClientName + "] job was acknowledged."); } work = "Acknowledged"; returnData = crypt.encrypt(work); network.Send(returnData); } } else { mylog.out("ERROR", "Client is requesting to acknowledge job completion before being assigned a job"); } } } else { // If this is a Drop Off point } // Common actions below (Server AND Drop Off point) if (fromClient.compareToIgnoreCase("quit") == 0) { mylog.out("INFO", "Client disconnected gracefully"); break; } else if (fromClient.compareToIgnoreCase("<REKEY>") == 0) { SendACK(); // Send ACK String prime = null; String base = null; // Grab 1st value (should be handshake for PRIME) fromClient = fromNetwork(); SendACK(); // Send ACK if (fromClient.compareToIgnoreCase("<PRIME>") == 0) { prime = fromNetwork(); SendACK(); // Send ACK } else { mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive PRIME)."); } // Grab 2nd value (should be handshake for BASE) fromClient = fromNetwork(); SendACK(); // Send ACK if (fromClient.compareToIgnoreCase("<BASE>") == 0) { base = fromNetwork(); SendACK(); // Send ACK } else { mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive BASE)."); } // Use received values to start DH DH myDH = new DH(mylog, prime, 16, base, 16); // Send rekeying ack returnData = crypt.encrypt("<REKEY-STARTING>"); network.Send(returnData); RecieveACK(); // Wait for ACK // Perform phase1 myDH.DHPhase1(); // Receive client public key byte[] clientPubKey = null; fromClient = fromNetwork(); SendACK(); // Send ACK if (fromClient.compareToIgnoreCase("<PUBLICKEY>") == 0) { clientPubKey = fromNetworkByte(); SendACK(); // Send ACK returnData = crypt.encrypt("<PubKey-GOOD>"); network.Send(returnData); RecieveACK(); // Wait for ACK } else { mylog.out("ERROR", "Failed to receieve client public key."); } // Send server public key to client network.Send(crypt.encrypt("<PUBLICKEY>")); RecieveACK(); // Wait for ACK network.Send(crypt.encrypt(myDH.GetPublicKeyBF())); RecieveACK(); // Wait for ACK fromClient = fromNetwork(); SendACK(); // Send ACK if (fromClient.compareToIgnoreCase("<PubKey-GOOD>") != 0) { mylog.out("ERROR", "Client has failed to acknowledge server public key!"); } // Use server DH public key to generate shared secret myDH.DHPhase2(myDH.CraftPublicKey(clientPubKey), "Client"); // Final verification // System.out.println("Shared Secret (Hex): " + // myDH.GetSharedSecret(10)); crypt.ReKey(myDH.GetSharedSecret(10), "Client"); + } else if (fromClient.length() == 0) { + // Send back empty data + craftReturn = ""; + returnData = crypt.encrypt(craftReturn); + network.Send(returnData); } else { + // Anything else, respond with error text mylog.out("INFO", "Not a supported request [" + fromClient + "]"); craftReturn = "Not a supported request [" + fromClient + "]"; returnData = crypt.encrypt(craftReturn); network.Send(returnData); } try { // Have the thread sleep for 1 second to lower CPU load Thread.sleep(1000); } catch (InterruptedException e) { mylog.out("ERROR", "Failed to have the thread sleep."); e.printStackTrace(); } } // Tear down bound I/O network.BringDown(); // Close this socket try { socket.close(); } catch (IOException e) { mylog.out("ERROR", "Failed to close SOCKET within SERVER THREAD"); } } /** * Reads a string from the network * * @return */ private String fromNetwork() { String decryptedValue = null; byte[] initialValue = network.ReceiveByte(); if (initialValue == null) { mylog.out("WARN", "Client disconnected abruptly"); } decryptedValue = crypt.decrypt(initialValue); if (decryptedValue == null) { mylog.out("WARN", "Client disconnected abruptly"); } else if (decryptedValue.compareToIgnoreCase("quit") == 0) { mylog.out("WARN", "Client disconnected abruptly"); } return decryptedValue; } /** * Read bytes from the network * * @return */ private byte[] fromNetworkByte() { byte[] decryptedValue = null; byte[] initialValue = network.ReceiveByte(); if (initialValue == null) { mylog.out("WARN", "Client disconnected abruptly"); } decryptedValue = crypt.decryptByte(initialValue); if (decryptedValue == null) { mylog.out("WARN", "Client disconnected abruptly"); } return decryptedValue; } /** * Provides message synchronization */ private void SendACK() { network.Send(crypt.encrypt("<ACK>")); if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) { mylog.out("ERROR", "Partner failed to ACK"); } } /** * Provides message synchronization */ private void RecieveACK() { if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) { mylog.out("ERROR", "Partner failed to ACK"); } network.Send(crypt.encrypt("<ACK>")); } }
false
false
null
null
diff --git a/src/java/org/codehaus/groovy/grails/support/DevelopmentResourceLoader.java b/src/java/org/codehaus/groovy/grails/support/DevelopmentResourceLoader.java index fe1fbfe93..f93030e33 100644 --- a/src/java/org/codehaus/groovy/grails/support/DevelopmentResourceLoader.java +++ b/src/java/org/codehaus/groovy/grails/support/DevelopmentResourceLoader.java @@ -1,111 +1,115 @@ /* Copyright 2004-2005 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.support; import grails.util.BuildSettings; import grails.util.BuildSettingsHolder; import grails.util.Metadata; import org.apache.commons.lang.StringUtils; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsResourceUtils; import org.codehaus.groovy.grails.plugins.GrailsPluginUtils; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import java.io.IOException; /** * * A ResourceLoader that allows files references like /WEB-INF/grails-app to be loaded from ./grails-app to support * the difference between wAR deployment and run-app * * @author Graeme Rocher * @since 1.0 * <p/> * Created: Jan 30, 2008 */ public class DevelopmentResourceLoader extends DefaultResourceLoader{ private String baseLocation = "."; private static final String PLUGINS_PREFIX = "plugins/"; private static final String SLASH = "/"; public DevelopmentResourceLoader(GrailsApplication application) { super(); } public DevelopmentResourceLoader() { super(); } public DevelopmentResourceLoader(GrailsApplication application, String baseLocation) { this(application); this.baseLocation = baseLocation; } public Resource getResource(String location) { if(Metadata.getCurrent().isWarDeployed()) { return super.getResource(location); } else { location = getRealLocationInProject(location); return super.getResource(location); } } /** * Retrieves the real location of a GSP within a Grails project * @param location The location of the GSP at deployment time * @return The location of the GSP at development time */ protected String getRealLocationInProject(String location) { if(!location.startsWith(SLASH)) location = SLASH +location; if(location.startsWith(GrailsResourceUtils.WEB_INF)) { final String noWebInf = location.substring(GrailsResourceUtils.WEB_INF.length() + 1); final String defaultPath = "file:" + baseLocation + SLASH + noWebInf; - if(noWebInf.startsWith(PLUGINS_PREFIX)) { + if(isNotMessageBundle(location) && noWebInf.startsWith(PLUGINS_PREFIX)) { BuildSettings settings = BuildSettingsHolder.getSettings(); String pluginPath = StringUtils.substringAfter(noWebInf, SLASH); String pluginName = StringUtils.substringBefore(pluginPath, SLASH); String remainingPath = StringUtils.substringAfter(pluginPath, SLASH); Resource r = GrailsPluginUtils.getPluginDirForName(pluginName); if(r != null) { try { return "file:" + r.getFile().getAbsolutePath() + SLASH + remainingPath; } catch (IOException e) { return defaultPath; } } else if(settings!=null){ return "file:" + settings.getProjectPluginsDir().getAbsolutePath() + SLASH + pluginName + SLASH + remainingPath; } else { return defaultPath; } } else { return defaultPath; } } else { return GrailsResourceUtils.WEB_APP_DIR+location; } } + + private boolean isNotMessageBundle(String location) { + return !location.endsWith(".properties") && !location.contains("i18n"); + } }
false
false
null
null
diff --git a/spring-data-commons-core/src/main/java/org/springframework/data/transaction/ChangeSetBackedTransactionSynchronization.java b/spring-data-commons-core/src/main/java/org/springframework/data/transaction/ChangeSetBackedTransactionSynchronization.java index e2e53ec2..1a21f9f7 100644 --- a/spring-data-commons-core/src/main/java/org/springframework/data/transaction/ChangeSetBackedTransactionSynchronization.java +++ b/spring-data-commons-core/src/main/java/org/springframework/data/transaction/ChangeSetBackedTransactionSynchronization.java @@ -1,62 +1,61 @@ package org.springframework.data.transaction; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.support.ChangeSetBacked; import org.springframework.data.support.ChangeSetPersister; import org.springframework.transaction.support.TransactionSynchronization; public class ChangeSetBackedTransactionSynchronization implements TransactionSynchronization { - protected final Log log = LogFactory.getLog(getClass()); + protected final Logger log = LoggerFactory.getLogger(getClass()); private ChangeSetPersister<Object> changeSetPersister; private ChangeSetBacked entity; private int changeSetTxStatus = -1; public ChangeSetBackedTransactionSynchronization(ChangeSetPersister<Object> changeSetPersister, ChangeSetBacked entity) { this.changeSetPersister = changeSetPersister; this.entity = entity; } public void afterCommit() { log.debug("After Commit called for " + entity); changeSetPersister.persistState(entity.getClass(), entity.getChangeSet()); changeSetTxStatus = 0; } public void afterCompletion(int status) { log.debug("After Completion called with status = " + status); if (changeSetTxStatus == 0) { if (status == STATUS_COMMITTED) { // this is good log.debug("ChangedSetBackedTransactionSynchronization completed successfully for " + this.entity); } else { // this could be bad - TODO: compensate log.error("ChangedSetBackedTransactionSynchronization failed for " + this.entity); } } } public void beforeCommit(boolean readOnly) { } public void beforeCompletion() { } public void flush() { } public void resume() { throw new IllegalStateException("ChangedSetBackedTransactionSynchronization does not support transaction suspension currently."); } public void suspend() { throw new IllegalStateException("ChangedSetBackedTransactionSynchronization does not support transaction suspension currently."); } } diff --git a/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java b/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java index 795d7c05..ff8f060c 100644 --- a/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java +++ b/spring-data-commons-core/src/main/java/org/springframework/persistence/support/AbstractConstructorEntityInstantiator.java @@ -1,78 +1,78 @@ package org.springframework.persistence.support; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.util.ClassUtils; /** * Try for a constructor taking state: failing that, try a no-arg * constructor and then setUnderlyingNode(). * * @author Rod Johnson */ public abstract class AbstractConstructorEntityInstantiator<BACKING_INTERFACE, STATE> implements EntityInstantiator<BACKING_INTERFACE, STATE> { - private final Log log = LogFactory.getLog(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); final public <T extends BACKING_INTERFACE> T createEntityFromState(STATE n, Class<T> c) { try { return fromStateInternal(n, c); } catch (InstantiationException e) { throw new IllegalArgumentException(e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e); } } final private <T extends BACKING_INTERFACE> T fromStateInternal(STATE n, Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // TODO this is fragile Class<? extends STATE> stateInterface = (Class<? extends STATE>) n.getClass().getInterfaces()[0]; Constructor<T> nodeConstructor = ClassUtils.getConstructorIfAvailable(c, stateInterface); if (nodeConstructor != null) { // TODO is this the correct way to instantiate or does Spring have a preferred way? log.info("Using " + c + " constructor taking " + stateInterface); return nodeConstructor.newInstance(n); } Constructor<T> noArgConstructor = ClassUtils.getConstructorIfAvailable(c); if (noArgConstructor == null) noArgConstructor = getDeclaredConstructor(c); if (noArgConstructor != null) { log.info("Using " + c + " no-arg constructor"); StateProvider.setUnderlyingState(n); T t; try { t = noArgConstructor.newInstance(); setState(t, n); } finally { StateProvider.retrieveState(); } return t; } throw new IllegalArgumentException(getClass().getSimpleName() + ": entity " + c + " must have either a constructor taking [" + stateInterface + "] or a no-arg constructor and state set method"); } private <T> Constructor<T> getDeclaredConstructor(Class<T> c) { try { final Constructor<T> declaredConstructor = c.getDeclaredConstructor(); declaredConstructor.setAccessible(true); return declaredConstructor; } catch (NoSuchMethodException e) { return null; } } /** * Subclasses must implement to set state * @param entity * @param s */ protected abstract void setState(BACKING_INTERFACE entity, STATE s); }
false
false
null
null
diff --git a/src/com/android/browser/WebsiteSettingsActivity.java b/src/com/android/browser/WebsiteSettingsActivity.java index 1e27092b..bd57c917 100644 --- a/src/com/android/browser/WebsiteSettingsActivity.java +++ b/src/com/android/browser/WebsiteSettingsActivity.java @@ -1,629 +1,629 @@ /* * 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.browser; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; -import android.provider.Browser; +import android.provider.BrowserContract.Bookmarks; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.GeolocationPermissions; import android.webkit.ValueCallback; import android.webkit.WebIconDatabase; import android.webkit.WebStorage; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.TextView; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Vector; /** * Manage the settings for an origin. * We use it to keep track of the 'HTML5' settings, i.e. database (webstorage) * and Geolocation. */ public class WebsiteSettingsActivity extends ListActivity { private String LOGTAG = "WebsiteSettingsActivity"; private static String sMBStored = null; private SiteAdapter mAdapter = null; static class Site { private String mOrigin; private String mTitle; private Bitmap mIcon; private int mFeatures; // These constants provide the set of features that a site may support // They must be consecutive. To add a new feature, add a new FEATURE_XXX // variable with value equal to the current value of FEATURE_COUNT, then // increment FEATURE_COUNT. private final static int FEATURE_WEB_STORAGE = 0; private final static int FEATURE_GEOLOCATION = 1; // The number of features available. private final static int FEATURE_COUNT = 2; public Site(String origin) { mOrigin = origin; mTitle = null; mIcon = null; mFeatures = 0; } public void addFeature(int feature) { mFeatures |= (1 << feature); } public void removeFeature(int feature) { mFeatures &= ~(1 << feature); } public boolean hasFeature(int feature) { return (mFeatures & (1 << feature)) != 0; } /** * Gets the number of features supported by this site. */ public int getFeatureCount() { int count = 0; for (int i = 0; i < FEATURE_COUNT; ++i) { count += hasFeature(i) ? 1 : 0; } return count; } /** * Gets the ID of the nth (zero-based) feature supported by this site. * The return value is a feature ID - one of the FEATURE_XXX values. * This is required to determine which feature is displayed at a given * position in the list of features for this site. This is used both * when populating the view and when responding to clicks on the list. */ public int getFeatureByIndex(int n) { int j = -1; for (int i = 0; i < FEATURE_COUNT; ++i) { j += hasFeature(i) ? 1 : 0; if (j == n) { return i; } } return -1; } public String getOrigin() { return mOrigin; } public void setTitle(String title) { mTitle = title; } public void setIcon(Bitmap icon) { mIcon = icon; } public Bitmap getIcon() { return mIcon; } public String getPrettyOrigin() { return mTitle == null ? null : hideHttp(mOrigin); } public String getPrettyTitle() { return mTitle == null ? hideHttp(mOrigin) : mTitle; } private String hideHttp(String str) { Uri uri = Uri.parse(str); return "http".equals(uri.getScheme()) ? str.substring(7) : str; } } class SiteAdapter extends ArrayAdapter<Site> implements AdapterView.OnItemClickListener { private int mResource; private LayoutInflater mInflater; private Bitmap mDefaultIcon; private Bitmap mUsageEmptyIcon; private Bitmap mUsageLowIcon; private Bitmap mUsageHighIcon; private Bitmap mLocationAllowedIcon; private Bitmap mLocationDisallowedIcon; private Site mCurrentSite; public SiteAdapter(Context context, int rsc) { super(context, rsc); mResource = rsc; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mDefaultIcon = BitmapFactory.decodeResource(getResources(), R.drawable.app_web_browser_sm); mUsageEmptyIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_list_data_off); mUsageLowIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_list_data_small); mUsageHighIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_list_data_large); mLocationAllowedIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_list_gps_on); mLocationDisallowedIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_list_gps_denied); askForOrigins(); } /** * Adds the specified feature to the site corresponding to supplied * origin in the map. Creates the site if it does not already exist. */ private void addFeatureToSite(Map<String, Site> sites, String origin, int feature) { Site site = null; if (sites.containsKey(origin)) { site = (Site) sites.get(origin); } else { site = new Site(origin); sites.put(origin, site); } site.addFeature(feature); } public void askForOrigins() { // Get the list of origins we want to display. // All 'HTML 5 modules' (Database, Geolocation etc) form these // origin strings using WebCore::SecurityOrigin::toString(), so it's // safe to group origins here. Note that WebCore::SecurityOrigin // uses 0 (which is not printed) for the port if the port is the // default for the protocol. Eg http://www.google.com and // http://www.google.com:80 both record a port of 0 and hence // toString() == 'http://www.google.com' for both. WebStorage.getInstance().getOrigins(new ValueCallback<Map>() { public void onReceiveValue(Map origins) { Map<String, Site> sites = new HashMap<String, Site>(); if (origins != null) { Iterator<String> iter = origins.keySet().iterator(); while (iter.hasNext()) { addFeatureToSite(sites, iter.next(), Site.FEATURE_WEB_STORAGE); } } askForGeolocation(sites); } }); } public void askForGeolocation(final Map<String, Site> sites) { GeolocationPermissions.getInstance().getOrigins(new ValueCallback<Set<String> >() { public void onReceiveValue(Set<String> origins) { if (origins != null) { Iterator<String> iter = origins.iterator(); while (iter.hasNext()) { addFeatureToSite(sites, iter.next(), Site.FEATURE_GEOLOCATION); } } populateIcons(sites); populateOrigins(sites); } }); } public void populateIcons(Map<String, Site> sites) { // Create a map from host to origin. This is used to add metadata // (title, icon) for this origin from the bookmarks DB. HashMap<String, Set<Site>> hosts = new HashMap<String, Set<Site>>(); Set<Map.Entry<String, Site>> elements = sites.entrySet(); Iterator<Map.Entry<String, Site>> originIter = elements.iterator(); while (originIter.hasNext()) { Map.Entry<String, Site> entry = originIter.next(); Site site = entry.getValue(); String host = Uri.parse(entry.getKey()).getHost(); Set<Site> hostSites = null; if (hosts.containsKey(host)) { hostSites = (Set<Site>)hosts.get(host); } else { hostSites = new HashSet<Site>(); hosts.put(host, hostSites); } hostSites.add(site); } // Check the bookmark DB. If we have data for a host used by any of // our origins, use it to set their title and favicon - Cursor c = getContext().getContentResolver().query(Browser.BOOKMARKS_URI, - new String[] { Browser.BookmarkColumns.URL, Browser.BookmarkColumns.TITLE, - Browser.BookmarkColumns.FAVICON }, "bookmark = 1", null, null); + Cursor c = getContext().getContentResolver().query(Bookmarks.CONTENT_URI, + new String[] { Bookmarks.URL, Bookmarks.TITLE, Bookmarks.FAVICON }, + Bookmarks.IS_FOLDER + " == 0", null, null); if (c != null) { if (c.moveToFirst()) { - int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); - int titleIndex = c.getColumnIndex(Browser.BookmarkColumns.TITLE); - int faviconIndex = c.getColumnIndex(Browser.BookmarkColumns.FAVICON); + int urlIndex = c.getColumnIndex(Bookmarks.URL); + int titleIndex = c.getColumnIndex(Bookmarks.TITLE); + int faviconIndex = c.getColumnIndex(Bookmarks.FAVICON); do { String url = c.getString(urlIndex); String host = Uri.parse(url).getHost(); if (hosts.containsKey(host)) { String title = c.getString(titleIndex); Bitmap bmp = null; byte[] data = c.getBlob(faviconIndex); if (data != null) { bmp = BitmapFactory.decodeByteArray(data, 0, data.length); } Set matchingSites = (Set) hosts.get(host); Iterator<Site> sitesIter = matchingSites.iterator(); while (sitesIter.hasNext()) { Site site = sitesIter.next(); // We should only set the title if the bookmark is for the root // (i.e. www.google.com), as website settings act on the origin // as a whole rather than a single page under that origin. If the // user has bookmarked a page under the root but *not* the root, // then we risk displaying the title of that page which may or // may not have any relevance to the origin. if (url.equals(site.getOrigin()) || (new String(site.getOrigin()+"/")).equals(url)) { site.setTitle(title); } if (bmp != null) { site.setIcon(bmp); } } } } while (c.moveToNext()); } c.close(); } } public void populateOrigins(Map<String, Site> sites) { clear(); // We can now simply populate our array with Site instances Set<Map.Entry<String, Site>> elements = sites.entrySet(); Iterator<Map.Entry<String, Site>> entryIterator = elements.iterator(); while (entryIterator.hasNext()) { Map.Entry<String, Site> entry = entryIterator.next(); Site site = entry.getValue(); add(site); } notifyDataSetChanged(); if (getCount() == 0) { finish(); // we close the screen } } public int getCount() { if (mCurrentSite == null) { return super.getCount(); } return mCurrentSite.getFeatureCount(); } public String sizeValueToString(long bytes) { // We display the size in MB, to 1dp, rounding up to the next 0.1MB. // bytes should always be greater than zero. if (bytes <= 0) { Log.e(LOGTAG, "sizeValueToString called with non-positive value: " + bytes); return "0"; } float megabytes = (float) bytes / (1024.0F * 1024.0F); int truncated = (int) Math.ceil(megabytes * 10.0F); float result = (float) (truncated / 10.0F); return String.valueOf(result); } /* * If we receive the back event and are displaying * site's settings, we want to go back to the main * list view. If not, we just do nothing (see * dispatchKeyEvent() below). */ public boolean backKeyPressed() { if (mCurrentSite != null) { mCurrentSite = null; askForOrigins(); return true; } return false; } /** * @hide * Utility function * Set the icon according to the usage */ public void setIconForUsage(ImageView usageIcon, long usageInBytes) { float usageInMegabytes = (float) usageInBytes / (1024.0F * 1024.0F); // We set the correct icon: // 0 < empty < 0.1MB // 0.1MB < low < 5MB // 5MB < high if (usageInMegabytes <= 0.1) { usageIcon.setImageBitmap(mUsageEmptyIcon); } else if (usageInMegabytes > 0.1 && usageInMegabytes <= 5) { usageIcon.setImageBitmap(mUsageLowIcon); } else if (usageInMegabytes > 5) { usageIcon.setImageBitmap(mUsageHighIcon); } } public View getView(int position, View convertView, ViewGroup parent) { View view; final TextView title; final TextView subtitle; final ImageView icon; final ImageView usageIcon; final ImageView locationIcon; final ImageView featureIcon; if (convertView == null) { view = mInflater.inflate(mResource, parent, false); } else { view = convertView; } title = (TextView) view.findViewById(R.id.title); subtitle = (TextView) view.findViewById(R.id.subtitle); icon = (ImageView) view.findViewById(R.id.icon); featureIcon = (ImageView) view.findViewById(R.id.feature_icon); usageIcon = (ImageView) view.findViewById(R.id.usage_icon); locationIcon = (ImageView) view.findViewById(R.id.location_icon); usageIcon.setVisibility(View.GONE); locationIcon.setVisibility(View.GONE); if (mCurrentSite == null) { setTitle(getString(R.string.pref_extras_website_settings)); Site site = getItem(position); title.setText(site.getPrettyTitle()); String subtitleText = site.getPrettyOrigin(); if (subtitleText != null) { title.setMaxLines(1); title.setSingleLine(true); subtitle.setVisibility(View.VISIBLE); subtitle.setText(subtitleText); } else { subtitle.setVisibility(View.GONE); title.setMaxLines(2); title.setSingleLine(false); } icon.setVisibility(View.VISIBLE); usageIcon.setVisibility(View.INVISIBLE); locationIcon.setVisibility(View.INVISIBLE); featureIcon.setVisibility(View.GONE); Bitmap bmp = site.getIcon(); if (bmp == null) { bmp = mDefaultIcon; } icon.setImageBitmap(bmp); // We set the site as the view's tag, // so that we can get it in onItemClick() view.setTag(site); String origin = site.getOrigin(); if (site.hasFeature(Site.FEATURE_WEB_STORAGE)) { WebStorage.getInstance().getUsageForOrigin(origin, new ValueCallback<Long>() { public void onReceiveValue(Long value) { if (value != null) { setIconForUsage(usageIcon, value.longValue()); usageIcon.setVisibility(View.VISIBLE); } } }); } if (site.hasFeature(Site.FEATURE_GEOLOCATION)) { locationIcon.setVisibility(View.VISIBLE); GeolocationPermissions.getInstance().getAllowed(origin, new ValueCallback<Boolean>() { public void onReceiveValue(Boolean allowed) { if (allowed != null) { if (allowed.booleanValue()) { locationIcon.setImageBitmap(mLocationAllowedIcon); } else { locationIcon.setImageBitmap(mLocationDisallowedIcon); } } } }); } } else { icon.setVisibility(View.GONE); locationIcon.setVisibility(View.GONE); usageIcon.setVisibility(View.GONE); featureIcon.setVisibility(View.VISIBLE); setTitle(mCurrentSite.getPrettyTitle()); String origin = mCurrentSite.getOrigin(); switch (mCurrentSite.getFeatureByIndex(position)) { case Site.FEATURE_WEB_STORAGE: WebStorage.getInstance().getUsageForOrigin(origin, new ValueCallback<Long>() { public void onReceiveValue(Long value) { if (value != null) { String usage = sizeValueToString(value.longValue()) + " " + sMBStored; title.setText(R.string.webstorage_clear_data_title); subtitle.setText(usage); subtitle.setVisibility(View.VISIBLE); setIconForUsage(featureIcon, value.longValue()); } } }); break; case Site.FEATURE_GEOLOCATION: title.setText(R.string.geolocation_settings_page_title); GeolocationPermissions.getInstance().getAllowed(origin, new ValueCallback<Boolean>() { public void onReceiveValue(Boolean allowed) { if (allowed != null) { if (allowed.booleanValue()) { subtitle.setText(R.string.geolocation_settings_page_summary_allowed); featureIcon.setImageBitmap(mLocationAllowedIcon); } else { subtitle.setText(R.string.geolocation_settings_page_summary_not_allowed); featureIcon.setImageBitmap(mLocationDisallowedIcon); } subtitle.setVisibility(View.VISIBLE); } } }); break; } } return view; } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mCurrentSite != null) { switch (mCurrentSite.getFeatureByIndex(position)) { case Site.FEATURE_WEB_STORAGE: new AlertDialog.Builder(getContext()) .setTitle(R.string.webstorage_clear_data_dialog_title) .setMessage(R.string.webstorage_clear_data_dialog_message) .setPositiveButton(R.string.webstorage_clear_data_dialog_ok_button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dlg, int which) { WebStorage.getInstance().deleteOrigin(mCurrentSite.getOrigin()); // If this site has no more features, then go back to the // origins list. mCurrentSite.removeFeature(Site.FEATURE_WEB_STORAGE); if (mCurrentSite.getFeatureCount() == 0) { mCurrentSite = null; } askForOrigins(); notifyDataSetChanged(); }}) .setNegativeButton(R.string.webstorage_clear_data_dialog_cancel_button, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); break; case Site.FEATURE_GEOLOCATION: new AlertDialog.Builder(getContext()) .setTitle(R.string.geolocation_settings_page_dialog_title) .setMessage(R.string.geolocation_settings_page_dialog_message) .setPositiveButton(R.string.geolocation_settings_page_dialog_ok_button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dlg, int which) { GeolocationPermissions.getInstance().clear(mCurrentSite.getOrigin()); mCurrentSite.removeFeature(Site.FEATURE_GEOLOCATION); if (mCurrentSite.getFeatureCount() == 0) { mCurrentSite = null; } askForOrigins(); notifyDataSetChanged(); }}) .setNegativeButton(R.string.geolocation_settings_page_dialog_cancel_button, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); break; } } else { mCurrentSite = (Site) view.getTag(); notifyDataSetChanged(); } } public Site currentSite() { return mCurrentSite; } } /** * Intercepts the back key to immediately notify * NativeDialog that we are done. */ public boolean dispatchKeyEvent(KeyEvent event) { if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) { if ((mAdapter != null) && (mAdapter.backKeyPressed())){ return true; // event consumed } } return super.dispatchKeyEvent(event); } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); if (sMBStored == null) { sMBStored = getString(R.string.webstorage_origin_summary_mb_stored); } mAdapter = new SiteAdapter(this, R.layout.website_settings_row); setListAdapter(mAdapter); getListView().setOnItemClickListener(mAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.websitesettings, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // If we are not on the sites list (rather on the page for a specific site) or // we aren't listing any sites hide the clear all button (and hence the menu). return mAdapter.currentSite() == null && mAdapter.getCount() > 0; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.website_settings_menu_clear_all: // Show the prompt to clear all origins of their data and geolocation permissions. new AlertDialog.Builder(this) .setTitle(R.string.website_settings_clear_all_dialog_title) .setMessage(R.string.website_settings_clear_all_dialog_message) .setPositiveButton(R.string.website_settings_clear_all_dialog_ok_button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dlg, int which) { WebStorage.getInstance().deleteAllData(); GeolocationPermissions.getInstance().clearAll(); WebStorageSizeManager.resetLastOutOfSpaceNotificationTime(); mAdapter.askForOrigins(); finish(); }}) .setNegativeButton(R.string.website_settings_clear_all_dialog_cancel_button, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return true; } return false; } }
false
false
null
null
diff --git a/src/net/fred/feedex/widget/ColorPickerDialogPreference.java b/src/net/fred/feedex/widget/ColorPickerDialogPreference.java index a7df507..7ff0597 100644 --- a/src/net/fred/feedex/widget/ColorPickerDialogPreference.java +++ b/src/net/fred/feedex/widget/ColorPickerDialogPreference.java @@ -1,134 +1,132 @@ /** * FeedEx * * Copyright (c) 2012-2013 Frederic Julian * * 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/>. * * * Some parts of this software are based on "Sparse rss" under the MIT license (see * below). Please refers to the original project to identify which parts are under the * MIT license. * * Copyright (c) 2010-2012 Stefan Handschuh * * 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 net.fred.feedex.widget; import net.fred.feedex.R; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; public class ColorPickerDialogPreference extends DialogPreference { + private SeekBar redSeekBar; - private SeekBar greenSeekBar; - private SeekBar blueSeekBar; - private SeekBar transparencySeekBar; int color; public ColorPickerDialogPreference(Context context, AttributeSet attrs) { super(context, attrs); color = WidgetProvider.STANDARD_BACKGROUND; } @Override protected View onCreateDialogView() { final View view = super.onCreateDialogView(); view.setBackgroundColor(color); redSeekBar = (SeekBar) view.findViewById(R.id.seekbar_red); greenSeekBar = (SeekBar) view.findViewById(R.id.seekbar_green); blueSeekBar = (SeekBar) view.findViewById(R.id.seekbar_blue); transparencySeekBar = (SeekBar) view.findViewById(R.id.seekbar_transparency); int _color = color; transparencySeekBar.setProgress(((_color / 0x01000000) * 100) / 255); _color %= 0x01000000; redSeekBar.setProgress(((_color / 0x00010000) * 100) / 255); _color %= 0x00010000; greenSeekBar.setProgress(((_color / 0x00000100) * 100) / 255); _color %= 0x00000100; blueSeekBar.setProgress((_color * 100) / 255); OnSeekBarChangeListener onSeekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int red = (redSeekBar.getProgress() * 255) / 100; int green = (greenSeekBar.getProgress() * 255) / 100; int blue = (blueSeekBar.getProgress() * 255) / 100; int transparency = (transparencySeekBar.getProgress() * 255) / 100; color = transparency * 0x01000000 + red * 0x00010000 + green * 0x00000100 + blue; view.setBackgroundColor(color); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }; redSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); greenSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); blueSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); transparencySeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); return view; } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { persistInt(color); } super.onDialogClosed(positiveResult); } } diff --git a/src/net/fred/feedex/widget/WidgetConfigActivity.java b/src/net/fred/feedex/widget/WidgetConfigActivity.java index e03885a..29dfaa4 100644 --- a/src/net/fred/feedex/widget/WidgetConfigActivity.java +++ b/src/net/fred/feedex/widget/WidgetConfigActivity.java @@ -1,148 +1,161 @@ /** * FeedEx * * Copyright (c) 2012-2013 Frederic Julian * * 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/>. * * * Some parts of this software are based on "Sparse rss" under the MIT license (see * below). Please refers to the original project to identify which parts are under the * MIT license. * * Copyright (c) 2010-2012 Stefan Handschuh * * 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 net.fred.feedex.widget; import net.fred.feedex.PrefsManager; import net.fred.feedex.R; import net.fred.feedex.provider.FeedData.FeedColumns; +import android.app.PendingIntent; +import android.app.PendingIntent.CanceledException; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.view.View; import android.view.View.OnClickListener; public class WidgetConfigActivity extends PreferenceActivity { private int widgetId; - private static final String NAMECOLUMN = new StringBuilder("ifnull(").append(FeedColumns.NAME).append(',').append(FeedColumns.URL).append(") as title").toString(); + private static final String NAMECOLUMN = new StringBuilder("ifnull(").append(FeedColumns.NAME).append(',').append(FeedColumns.URL) + .append(") as title").toString(); public static final String ZERO = "0"; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setResult(RESULT_CANCELED); Bundle extras = getIntent().getExtras(); if (extras != null) { widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); } addPreferencesFromResource(R.layout.widget_preferences); setContentView(R.layout.widget_config); final PreferenceCategory feedsPreferenceCategory = (PreferenceCategory) findPreference("widget.visiblefeeds"); Cursor cursor = this.getContentResolver().query(FeedColumns.CONTENT_URI, new String[] { FeedColumns._ID, NAMECOLUMN }, null, null, null); if (cursor.moveToFirst()) { int[] ids = new int[cursor.getCount() + 1]; CheckBoxPreference checkboxPreference = new CheckBoxPreference(this); checkboxPreference.setTitle(R.string.all_feeds); feedsPreferenceCategory.addPreference(checkboxPreference); checkboxPreference.setKey(ZERO); checkboxPreference.setDisableDependentsState(true); ids[0] = 0; for (int n = 1; !cursor.isAfterLast(); cursor.moveToNext(), n++) { checkboxPreference = new CheckBoxPreference(this); checkboxPreference.setTitle(cursor.getString(1)); ids[n] = cursor.getInt(0); checkboxPreference.setKey(Integer.toString(ids[n])); feedsPreferenceCategory.addPreference(checkboxPreference); checkboxPreference.setDependency(ZERO); } cursor.close(); findViewById(R.id.save_button).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { StringBuilder builder = new StringBuilder(); for (int n = 0, i = feedsPreferenceCategory.getPreferenceCount(); n < i; n++) { CheckBoxPreference preference = (CheckBoxPreference) feedsPreferenceCategory.getPreference(n); if (preference.isChecked()) { if (n == 0) { break; } else { if (builder.length() > 0) { builder.append(','); } builder.append(preference.getKey()); } } } String feedIds = builder.toString(); PrefsManager.putString(widgetId + ".feeds", feedIds); int color = PrefsManager.getInteger("widget.background", WidgetProvider.STANDARD_BACKGROUND); PrefsManager.putInteger(widgetId + ".background", color); - AppWidgetManager.getInstance(WidgetConfigActivity.this).notifyAppWidgetViewDataChanged(widgetId, R.id.feedsListView); + // Now we need to update the widget + //AppWidgetManager.getInstance(WidgetConfigActivity.this).notifyAppWidgetViewDataChanged(widgetId, R.id.feedsListView); + Intent intent = new Intent(WidgetConfigActivity.this, WidgetProvider.class); + intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { widgetId }); + PendingIntent pendingIntent = PendingIntent.getBroadcast(WidgetConfigActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + try { + pendingIntent.send(); + } catch (CanceledException e) { + } + // WidgetProvider.updateAppWidget(WidgetConfigActivity.this, widgetId, hideRead, feedIds, color); setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)); finish(); } }); } else { // no feeds found --> use all feeds, no dialog needed cursor.close(); setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)); } } } diff --git a/src/net/fred/feedex/widget/WidgetFeedsFactory.java b/src/net/fred/feedex/widget/WidgetFeedsFactory.java index 1ca48f5..64b65e4 100644 --- a/src/net/fred/feedex/widget/WidgetFeedsFactory.java +++ b/src/net/fred/feedex/widget/WidgetFeedsFactory.java @@ -1,171 +1,171 @@ /** * FeedEx * * Copyright (c) 2012-2013 Frederic Julian * * 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/>. * * * Some parts of this software are based on "Sparse rss" under the MIT license (see * below). Please refers to the original project to identify which parts are under the * MIT license. * * Copyright (c) 2010-2012 Stefan Handschuh * * 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 net.fred.feedex.widget; import net.fred.feedex.Constants; import net.fred.feedex.PrefsManager; import net.fred.feedex.R; import net.fred.feedex.ThrottledContentObserver; import net.fred.feedex.provider.FeedData.EntryColumns; import net.fred.feedex.provider.FeedData.FeedColumns; import android.appwidget.AppWidgetManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.RemoteViews; import android.widget.RemoteViewsService; public class WidgetFeedsFactory implements RemoteViewsService.RemoteViewsFactory { private Context context = null; private final int appWidgetId; private Cursor cursor; private ThrottledContentObserver mContentObserver; public WidgetFeedsFactory(Context ctxt, Intent intent) { this.context = ctxt; appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } @Override public void onCreate() { computeCursor(); mContentObserver = new ThrottledContentObserver(new Handler(), 3000) { @Override public void onChangeThrottled(boolean selfChange) { AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(appWidgetId, R.id.feedsListView); } }; ContentResolver cr = context.getContentResolver(); cr.registerContentObserver(EntryColumns.CONTENT_URI, true, mContentObserver); } @Override public void onDestroy() { cursor.close(); ContentResolver cr = context.getContentResolver(); cr.unregisterContentObserver(mContentObserver); } @Override public int getCount() { return cursor.getCount(); } @Override public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(context.getPackageName(), R.layout.widget_item); if (cursor.moveToPosition(position)) { row.setTextViewText(android.R.id.text1, cursor.getString(0)); - row.setOnClickFillInIntent(android.R.id.text1, new Intent(Intent.ACTION_VIEW, EntryColumns.CONTENT_URI(cursor.getString(1)))); + row.setOnClickFillInIntent(android.R.id.content, new Intent(Intent.ACTION_VIEW, EntryColumns.CONTENT_URI(cursor.getString(1)))); if (!cursor.isNull(2)) { try { byte[] iconBytes = cursor.getBlob(2); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null) { row.setImageViewBitmap(android.R.id.icon, bitmap); } } } catch (Throwable e) { } } } return row; } @Override public RemoteViews getLoadingView() { return (null); } @Override public int getViewTypeCount() { return (1); } @Override public long getItemId(int position) { return (position); } @Override public boolean hasStableIds() { return (true); } @Override public void onDataSetChanged() { cursor.close(); computeCursor(); } private void computeCursor() { StringBuilder selection = new StringBuilder(); // selection.append(EntryColumns.WHERE_UNREAD); String feedIds = PrefsManager.getString(appWidgetId + ".feeds", ""); if (feedIds.length() > 0) { if (selection.length() > 0) { selection.append(Constants.DB_AND); } selection.append(EntryColumns.FEED_ID).append(" IN (" + feedIds).append(')'); } ContentResolver cr = context.getContentResolver(); cursor = cr.query(EntryColumns.CONTENT_URI, new String[] { EntryColumns.TITLE, EntryColumns._ID, FeedColumns.ICON }, selection.toString(), null, new StringBuilder(EntryColumns.DATE).append(Constants.DB_DESC).toString()); } } \ No newline at end of file
false
false
null
null
diff --git a/src/main/java/org/tal/sensorlibrary/daytime.java b/src/main/java/org/tal/sensorlibrary/daytime.java index cedcc0a..f820992 100644 --- a/src/main/java/org/tal/sensorlibrary/daytime.java +++ b/src/main/java/org/tal/sensorlibrary/daytime.java @@ -1,172 +1,185 @@ package org.tal.sensorlibrary; import java.util.Calendar; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.tal.redstonechips.circuit.Circuit; /** * * @author Tal Eisenberg */ public class daytime extends Circuit { enum TimeField { SECOND(23999,59), SECONDOFDAY(23999, 86399), MINUTE(59,59), MINUTEOFDAY(1439,1439), HOUR(23, 23), TICK(23999, 86399), MINUTE1(9,9), MINUTE10(5,5), HOUR1(9, 9), HOUR10(2, 2), SECOND1(9,9), SECOND10(5,5); public int gameMax, earthMax; TimeField(int gameMax, int earthMax) { this.gameMax = gameMax; this.earthMax = earthMax; } int maxTime(boolean earthtime) { if (earthtime) return earthMax; else return gameMax; } } private static final double ticksPerHour = 1000d; private static final double ticksPerMinute = ticksPerHour/60d; //16.6666666... private boolean earthtime = false; private int maxval; private int hoursOffset = 0; private TimeField timeField; private World w; @Override public void inputChange(int inIdx, boolean state) { if (state) { int time; if (earthtime) { Calendar now = Calendar.getInstance(); if (timeField==TimeField.SECOND) time = now.get(Calendar.SECOND); else if(timeField == TimeField.SECONDOFDAY || timeField==TimeField.TICK) time = now.get(Calendar.SECOND) + now.get(Calendar.MINUTE)*60 + now.get(Calendar.HOUR_OF_DAY) * 60; else if (timeField==TimeField.MINUTE) time = now.get(Calendar.MINUTE); else if (timeField==TimeField.MINUTEOFDAY) time = now.get(Calendar.MINUTE) + now.get(Calendar.HOUR_OF_DAY)*60; - else if (timeField==TimeField.HOUR) + else if (timeField==TimeField.HOUR) { time = now.get(Calendar.HOUR_OF_DAY) + hoursOffset; - else if (timeField==TimeField.HOUR1) { // hour of day, ones digit - time = (now.get(Calendar.HOUR_OF_DAY) + hoursOffset) % 10; + if (time>=24) time = time - 24; + } else if (timeField==TimeField.HOUR1) { // hour of day, ones digit + time = (now.get(Calendar.HOUR_OF_DAY) + hoursOffset); + if (time>=24) time = time - 24; + time = time % 10; } else if (timeField==TimeField.HOUR10) { // hour of day, tens digit - time = (now.get(Calendar.HOUR_OF_DAY) + hoursOffset) / 10; + time = (now.get(Calendar.HOUR_OF_DAY) + hoursOffset); + if (time>=24) time = time - 24; + time = time / 10; } else if (timeField==TimeField.MINUTE1) { // minute of hour, ones digit time = now.get(Calendar.MINUTE) % 10; } else if (timeField==TimeField.MINUTE10) { // minute of hour, tens digit time = now.get(Calendar.MINUTE) / 10; } else if (timeField==TimeField.SECOND1) { // second of minute, ones digit time = now.get(Calendar.SECOND) % 10; } else if (timeField==TimeField.SECOND10) { time = now.get(Calendar.SECOND) / 10; } else time = -1; } else { if (timeField==TimeField.SECONDOFDAY || timeField==TimeField.TICK || timeField==TimeField.SECOND) time = (int)w.getTime(); else if (timeField == TimeField.MINUTEOFDAY) time = (int)Math.round(w.getTime()/ticksPerMinute); else if (timeField == TimeField.MINUTE) time = (int)Math.round((w.getTime()%1000)/ticksPerMinute); - else if (timeField == TimeField.HOUR) + else if (timeField == TimeField.HOUR) { time = (int)(w.getTime()/ticksPerHour) + hoursOffset; - else if (timeField==TimeField.HOUR1) { // hour of day, ones digit - time = ((int)(w.getTime()/ticksPerHour) + hoursOffset) % 10; + if (time>=24) time = time - 24; + + } else if (timeField==TimeField.HOUR1) { // hour of day, ones digit + time = ((int)(w.getTime()/ticksPerHour) + hoursOffset); + if (time>=24) time = time - 24; + time = time % 10; + } else if (timeField==TimeField.HOUR10) { // hour of day, tens digit - time = ((int)(w.getTime()/ticksPerHour) + hoursOffset) / 10; + time = ((int)(w.getTime()/ticksPerHour) + hoursOffset); + if (time>=24) time = time - 24; + time = time / 10; + } else if (timeField==TimeField.MINUTE1) { // minute of hour, ones digit time = ((int)Math.round((w.getTime()%1000)/ticksPerMinute)) % 10; } else if (timeField==TimeField.MINUTE10) { // minute of hour, tens digit time = ((int)Math.round((w.getTime()%1000)/ticksPerMinute)) / 10; } else time = -1; } time = Math.min(time, timeField.maxTime(earthtime)); if (hasListeners()) debug("Time is " + time); int output; int maxTime = timeField.maxTime(earthtime); if (maxTime>maxval) { float c = (float)(maxval+1)/(float)(maxTime+1); output = (int)(c*time); } else output = time; sendInt(0, outputs.length, output); } } @Override protected boolean init(CommandSender sender, String[] args) { if (inputs.length!=1) { error(sender, "Expecting 1 clock input."); return false; } if (args.length>0) { String errorMsg = "Expecting <earthtime|gametime>[:<hour-offset>]"; int colonIdx = args[0].indexOf(":"); String timetype; if (colonIdx==-1) { timetype = args[0]; hoursOffset = 0; } else { timetype = args[0].substring(0, colonIdx); try { hoursOffset = Integer.parseInt(args[0].substring(colonIdx+1)); } catch (NumberFormatException e) { error(sender, errorMsg); } } if (timetype.equalsIgnoreCase("earthtime")) earthtime = true; else if (timetype.equalsIgnoreCase("gametime")) earthtime = false; else { error(sender, errorMsg); return false; } } if (args.length>1) { try { timeField = TimeField.valueOf(args[1].toUpperCase()); } catch (IllegalArgumentException ie) { error(sender, "Unknown time field: " + args[1]); return false; } } else { timeField=TimeField.TICK; } if (!earthtime && (timeField==TimeField.SECOND1 || timeField==TimeField.SECOND10)) { error(sender, "second1 or second10 time fields are not allowed when using gametime."); return false; } if (args.length>2) { w = redstoneChips.getServer().getWorld(args[2]); if (w == null) { error(sender, "Unknown world name: " + args[2]); return false; } } else { w = world; } maxval = (int)(Math.pow(2, outputs.length)-1); return true; } } \ No newline at end of file
false
false
null
null
diff --git a/modules/dCache/diskCacheV111/pools/MultiProtocolPoolV3.java b/modules/dCache/diskCacheV111/pools/MultiProtocolPoolV3.java index 90db739e5c..bad09d911a 100755 --- a/modules/dCache/diskCacheV111/pools/MultiProtocolPoolV3.java +++ b/modules/dCache/diskCacheV111/pools/MultiProtocolPoolV3.java @@ -1,3642 +1,3644 @@ // $Id: MultiProtocolPoolV3.java,v 1.16 2007-10-26 11:17:06 behrmann Exp $ package diskCacheV111.pools; import diskCacheV111.vehicles.*; import diskCacheV111.util.*; import diskCacheV111.movers.*; import diskCacheV111.repository.*; import diskCacheV111.util.event.*; import dmg.cells.nucleus.*; import dmg.util.*; import dmg.cells.services.*; import java.util.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import org.apache.log4j.Logger; import org.dcache.pool.repository.v3.CacheRepositoryV3; import org.dcache.pool.repository.v4.CacheRepositoryV4; public class MultiProtocolPoolV3 extends CellAdapter implements Logable { private final static Logger _logPoolMonitor = Logger.getLogger("logger.org.dcache.poolmonitor." + MultiProtocolPoolV3.class.getName()); private static final String MAX_SPACE = "use-max-space"; private static final String PREALLOCATED_SPACE = "use-preallocated-space"; private final static int LFS_NONE = 0; private final static int LFS_PRECIOUS = 1; private final static int LFS_VOLATILE = 2; private final static int DUP_REQ_NONE = 0; private final static int DUP_REQ_IGNORE = 1; private final static int DUP_REQ_REFRESH = 2; private final static int P2P_INTEGRATED = 0; private final static int P2P_SEPARATED = 1; private final static int P2P_CACHED = 1; private final static int P2P_PRECIOUS = 2; private final String _poolName; private final Args _args; private final CellNucleus _nucleus; private final HashMap _moverAttributes = new HashMap(); private final Map<String, Class<?>> _moverHash = new HashMap<String, Class<?>>(); /** * pool start time identifier. * used by PoolManager to recognize pool restarts */ private final long _serialId = System.currentTimeMillis(); private int _recoveryFlags = 0; private final PoolV2Mode _poolMode = new PoolV2Mode(); private boolean _reportOnRemovals = false; private boolean _flushZeroSizeFiles = false; private boolean _suppressHsmLoad = false; private boolean _cleanPreciousFiles = false; private String _poolStatusMessage = "OK"; private int _poolStatusCode = 0; private final PnfsHandler _pnfs; private final CacheRepository _repository; private final StorageClassContainer _storageQueue; private final SpaceSweeper _sweeper; private String _setupManager = null; private String _pnfsManagerName = "PnfsManager"; private String _poolManagerName = "PoolManager"; private String _hsmPoolManagerName = "HsmPoolManager"; private String _sweeperClass = "diskCacheV111.pools.SpaceSweeper0"; private static final String _dummySweeperClass = "diskCacheV111.pools.DummySpaceSweeper"; private int _version = 4; private final CellPath _billingCell ; private final Map<String, String> _tags = new HashMap<String, String>(); private final String _baseDir; private File _base; private File _setup; private final PoolManagerPingThread _pingThread ; private final HsmFlushController _flushingThread; private final JobScheduler _ioQueue ; private final JobScheduler _p2pQueue; private final JobTimeoutManager _timeoutManager; private final HsmSet _hsmSet = new HsmSet(); private final HsmStorageHandler2 _storageHandler; private Logable _logClass = this; private boolean _crashEnabled = false; private String _crashType = "exception"; private boolean _isPermanent = false; private boolean _allowSticky = false; private boolean _allowModify = false; private boolean _isHsmPool = false; private boolean _blockOnNoSpace = true; private boolean _checkRepository = true; private boolean _waitForRepositoryOk = false; private long _gap = 4L * 1024L * 1024L * 1024L; private int _lfsMode = LFS_NONE; private int _p2pFileMode = P2P_CACHED; private int _dupRequest = DUP_REQ_IGNORE; private int _p2pMode = P2P_SEPARATED; private P2PClient _p2pClient = null; private int _cleaningInterval = 60; private double _simCpuCost = -1.; private double _simSpaceCost = -1.; private Object _hybridInventoryLock = new Object(); private boolean _hybridInventoryActive = false; private int _hybridCurrent = 0; private ChecksumModuleV1 _checksumModule = null; private ReplicationHandler _replicationHandler = null; // // arguments : // MPP2 <poolBasePath> no default // [-permanent] : default : dynamic // [-version=<version>] : default : 4 // [-sticky=allowed|denied] ; default : denied // [-recover-space[=no]] : default : no // [-recover-control[=no]] : default : no // [-lfs=precious] // [-p2p=<p2pFileMode>] : default : cached // [-poolManager=<name>] : default : PoolManager // [-billing=<name>] : default : billing // [-setupManager=<name>] : default : none // [-dupRequest=none|ignore|refresh]: default : ignore // [-flushZeroSizeFiles=yes|no] : default : no // [-blockOnNoSpace=yes|no|auto] : default : auto // [-allowCleaningPreciousFiles] : default : false // [-checkRepository] : default : true // [-waitForRepositoryOk] : default : false // [-replicateOnArrival[=[Manager],[host],[mode]]] : default : // PoolManager,thisHost,keep // public MultiProtocolPoolV3(String poolName, String args) throws Exception { super(poolName, args, false); _poolName = poolName; _args = getArgs(); _nucleus = getNucleus(); // // the export is convenient but not really necessary, because // we send our path along with the 'alive' message. // getNucleus().export(); int argc = _args.argc(); say("Pool " + poolName + " starting"); try { if (argc < 1) { throw new IllegalArgumentException("no base dir specified"); } _baseDir = _args.argv(0); String versionString = _args.getOpt("version"); if (versionString != null) { try { _version = Integer.parseInt(versionString); } catch (NumberFormatException e) { /* bad string, ignored */} } _isPermanent = _args.getOpt("permanent") != null; String stickyString = _args.getOpt("sticky"); if (stickyString != null) _allowSticky = stickyString.equals("allowed"); say("Sticky files : " + (_allowSticky ? "allowed" : "denied")); String modifyString = _args.getOpt("modify"); if (modifyString != null) _allowModify = modifyString.equals("allowed"); say("Modify files : " + (_allowModify ? "allowed" : "denied")); String sweeperClass = _args.getOpt("sweeper"); if (sweeperClass != null) _sweeperClass = sweeperClass; if (_isPermanent) _sweeperClass = _dummySweeperClass; say("Using sweeper : " + _sweeperClass); String recover = _args.getOpt("recover-control"); if ((recover != null) && (!recover.equals("no"))) { _recoveryFlags |= CacheRepository.ALLOW_CONTROL_RECOVERY; say("Enabled : recover-control"); } recover = _args.getOpt("recover-space"); if ((recover != null) && (!recover.equals("no"))) { _recoveryFlags |= CacheRepository.ALLOW_SPACE_RECOVERY; say("Enabled : recover-space"); } recover = _args.getOpt("checkRepository"); if (recover != null) { if (recover.equals("yes") || recover.equals("true")) { _checkRepository = true; } else if (recover.equals("no") || recover.equals("false")) { _checkRepository = false; } } say("CheckRepository : " + _checkRepository); recover = _args.getOpt("waitForRepositoryReady"); if (recover != null) { if (recover.equals("yes") || recover.equals("true")) { _waitForRepositoryOk = true; } else if (recover.equals("no") || recover.equals("false")) { _waitForRepositoryOk = false; } } say("waitForRepositoryReady : " + _waitForRepositoryOk); recover = _args.getOpt("recover-anyway"); if ((recover != null) && (!recover.equals("no"))) { _recoveryFlags |= CacheRepository.ALLOW_RECOVER_ANYWAY; say("Enabled : recover-anyway"); } recover = _args.getOpt("replicateOnArrival"); if (recover == null) { _replicationHandler = new ReplicationHandler(); } else { _replicationHandler = new ReplicationHandler( recover.equals("") ? "on" : recover); } say("ReplicationHandler : " + _replicationHandler); /** * If cleaner sends its remove list, do we allow to remove precious * files for HSM connected pools ? */ recover = _args.getOpt("allowCleaningPreciousFiles"); _cleanPreciousFiles = (recover != null) && (recover.equals("yes") || recover.equals("true")); say("allowCleaningPreciousFiles : " + _cleanPreciousFiles); String lfsModeString = _args.getOpt("lfs"); lfsModeString = lfsModeString == null ? _args .getOpt("largeFileStore") : lfsModeString; if (lfsModeString != null) { if (lfsModeString.equals("precious") || lfsModeString.equals("hsm") || lfsModeString.equals("")) { _lfsMode = LFS_PRECIOUS; _isHsmPool = lfsModeString.equals("hsm"); } else if (lfsModeString.equals("volatile") || lfsModeString.equals("transient")) { _lfsMode = LFS_VOLATILE; } else { throw new IllegalArgumentException( "lfs[=volatile|precious|transient]"); } } else { _lfsMode = LFS_NONE; } say("LargeFileStore Mode : " + (_lfsMode == LFS_NONE ? "None" : _lfsMode == LFS_VOLATILE ? "Volatile" : "Precious")); say("isHsmPool = " + _isHsmPool); lfsModeString = _args.getOpt("p2p"); lfsModeString = lfsModeString == null ? _args.getOpt("p2pFileMode") : lfsModeString; if (lfsModeString != null) { if (lfsModeString.equals("precious")) { _p2pFileMode = P2P_PRECIOUS; } else if (lfsModeString.equals("cached")) { _p2pFileMode = P2P_CACHED; } else { throw new IllegalArgumentException("p2p=precious|cached"); } } else { _p2pFileMode = P2P_CACHED; } say("Pool2Pool File Mode : " + (_p2pFileMode == P2P_CACHED ? "cached" : "precious")); String dupString = _args.getOpt("dupRequest"); if ((dupString == null) || dupString.equals("none")) { _dupRequest = DUP_REQ_NONE; } else if (dupString.equals("ignore")) { _dupRequest = DUP_REQ_IGNORE; } else if (dupString.equals("refresh")) { _dupRequest = DUP_REQ_REFRESH; } else { esay("Illegal 'dupRequest' value : " + dupString + " (using 'none')"); } say("DuplicateRequest Mode : " + (_dupRequest == DUP_REQ_NONE ? "None" : _dupRequest == DUP_REQ_IGNORE ? "Ignore" : "Refresh")); String tmp = _args.getOpt("poolManager"); _poolManagerName = tmp == null ? (_isHsmPool ? _hsmPoolManagerName : _poolManagerName) : tmp; say("PoolManagerName : " + _poolManagerName); tmp = _args.getOpt("billing"); if (tmp != null) { _billingCell = new CellPath(tmp); }else{ _billingCell = new CellPath("billing"); } say("Billing Cell : " + _billingCell); tmp = _args.getOpt("flushZeroSizeFiles"); if (tmp != null) { if (tmp.equals("yes") || tmp.equals("true")) { _flushZeroSizeFiles = true; } else if (tmp.equals("no") || tmp.equals("false")) { _flushZeroSizeFiles = false; } } say("flushZeroSizeFiles = " + _flushZeroSizeFiles); _setupManager = _args.getOpt("setupManager"); say("SetupManager set to " + (_setupManager == null ? "none" : _setupManager)); // // block 'reserve space' only if we have a chance to // make space available. So not for LFS_PRECIOUS. // _blockOnNoSpace = _lfsMode != LFS_PRECIOUS; // // and allow overwriting // tmp = _args.getOpt("blockOnNoSpace"); if ((tmp != null) && !tmp.equals("auto")) _blockOnNoSpace = tmp.equals("yes"); say("BlockOnNoSpace : " + _blockOnNoSpace); // // get additional tags // { for (Enumeration<String> options = _args.options().keys(); options .hasMoreElements();) { String key = options.nextElement(); say("Tag scanning : " + key); if ((key.length() > 4) && key.startsWith("tag.")) { _tags.put(key.substring(4), _args.getOpt(key)); } } for (Map.Entry<String, String> e: _tags.entrySet() ) { say(" Extra Tag Option : " + e.getKey() + " -> "+ e.getValue()); } } // // repository and ping thread must exist BEFORE the // setup file is scanned. PingThread will be start // after all the setup is done. // _pingThread = new PoolManagerPingThread(); disablePool(PoolV2Mode.DISABLED_STRICT, 1, "Initializing"); say("Checking base directory ( reading setup) " + _baseDir); _base = new File(_baseDir); _setup = new File(_base, "setup"); while (!_setup.canRead()) { disablePool(PoolV2Mode.DISABLED_STRICT,1,"Initializing : Repository seems not to be ready - setup file does not exist or not readble"); esay("Can't read setup file: exists? " + Boolean.toString(_setup.exists()) + " can read? " + Boolean.toString(_setup.canRead()) ); try { Thread.sleep(30000); } catch (InterruptedException ie) { esay("Waiting for repository was interrupted"); throw new Exception( "Waiting for repository was interrupted"); } } say("Base dir ok"); _storageQueue = new StorageClassContainer(poolName); _repository = new CacheRepositoryV4(_base, _args); _repository.setLogable(this); _pnfs = new PnfsHandler(this, new CellPath(_pnfsManagerName), _poolName); _storageHandler = new HsmStorageHandler2(this, _repository, _hsmSet, _pnfs); _storageHandler.setStickyAllowed(_allowSticky); _sweeper = getSweeperHandler(); // // transfer queue management // _timeoutManager = new JobTimeoutManager(this); // // _ioQueue = new SimpleJobScheduler( getNucleus().getThreadGroup() // , "IO" ) ; // _ioQueue.setSchedulerId( "regular" , 2 ) ; // _timeoutManager.addScheduler( "io" , _ioQueue ) ; // // _ioQueueManager = new IoQueueManager( // getNucleus().getThreadGroup() , // _args.getOpt("io-queues" ) ) ; // _ioQueue = _ioQueueManager.getDefaultScheduler() ; _ioQueue = new IoQueueManager(getNucleus().getThreadGroup(), _args .getOpt("io-queues")); _p2pQueue = new SimpleJobScheduler(getNucleus().getThreadGroup(), "P2P"); _flushingThread = new HsmFlushController(this, _storageQueue, _storageHandler); _checksumModule = new ChecksumModuleV1(this, _repository, _pnfs); _p2pClient = new P2PClient(this, _repository, _checksumModule); _timeoutManager.addScheduler("p2p", _p2pQueue); _timeoutManager.start(); addCommandListener(_timeoutManager); // // add the command listeners before we execute the setupFile. // addCommandListener(_sweeper); addCommandListener(_hsmSet); addCommandListener(new RepositoryInterpreter(this, _repository)); addCommandListener(_storageQueue); addCommandListener(new HsmStorageInterpreter(this, _storageHandler)); addCommandListener(_flushingThread); addCommandListener(_p2pClient); addCommandListener(_checksumModule); execFile(_setup); } catch (Exception e) { say("Exception occurred on startup: " + e); start(); kill(); throw e; } _pingThread.start(); _repository.addCacheRepositoryListener(new RepositoryLoader()); start(); Object weAreDone = new Object(); synchronized (weAreDone) { _nucleus.newThread(new InventoryScanner(weAreDone), "inventory") .start(); try { weAreDone.wait(); } catch (InterruptedException ee) { kill(); throw ee; } _logClass.elog("Starting Flushing Thread"); _flushingThread.start(); } esay("Constructor done (still waiting for 'inventory')"); } public CellVersion getCellVersion() { return new CellVersion(diskCacheV111.util.Version.getVersion(), "$Revision: 1.16 $"); } private class IoQueueManager implements JobScheduler { private ArrayList<JobScheduler> _list = new ArrayList<JobScheduler>(); private HashMap<String, JobScheduler> _hash = new HashMap<String, JobScheduler>(); private boolean _isConfigured = false; private IoQueueManager(ThreadGroup group, String ioQueueList) { _isConfigured = (ioQueueList != null) && (ioQueueList.length() > 0); if( !_isConfigured ) { ioQueueList = "regular"; } StringTokenizer st = new StringTokenizer(ioQueueList, ","); while (st.hasMoreTokens()) { String queueName = st.nextToken(); if (_hash.get(queueName) != null) { esay("Duplicated queue name (ignored) : " + queueName); continue; } int id = _list.size(); JobScheduler job = new SimpleJobScheduler(group, "IO-" + id); _list.add(job); _hash.put(queueName, job); job.setSchedulerId(queueName, id); _timeoutManager.addScheduler(queueName, job); } if (!_isConfigured) { say("IoQueueManager : not configured"); } else { say("IoQueueManager : " + _hash.toString()); } } private boolean isConfigured() { return _isConfigured; } private JobScheduler getDefaultScheduler() { return _list.get(0); } private Iterator<JobScheduler> scheduler() { return new ArrayList<JobScheduler>(_list).iterator(); } private JobScheduler getSchedulerByName(String queueName) { return _hash.get(queueName); } private JobScheduler getSchedulerById(int id) { int pos = id % 10; if (pos >= _list.size()) { throw new IllegalArgumentException( "Invalid id (doesn't below to any known scheduler)"); } return _list.get(pos); } public JobInfo getJobInfo(int id) { return getSchedulerById(id).getJobInfo(id); } public int add(String queueName, Runnable runnable, int priority) throws InvocationTargetException { JobScheduler js = queueName == null ? null : (JobScheduler) _hash .get(queueName); return js == null ? add(runnable, priority) : js.add(runnable, priority); } public int add(Runnable runnable) throws InvocationTargetException { return getDefaultScheduler().add(runnable); } public int add(Runnable runnable, int priority) throws InvocationTargetException { return getDefaultScheduler().add(runnable, priority); } public void kill(int jobId) throws NoSuchElementException { getSchedulerById(jobId).kill(jobId); } public void remove(int jobId) throws NoSuchElementException { getSchedulerById(jobId).remove(jobId); } public StringBuffer printJobQueue(StringBuffer sbin) { StringBuffer sb = sbin == null ? new StringBuffer() : sbin; for (Iterator it = scheduler(); it.hasNext();) { ((JobScheduler) it.next()).printJobQueue(sb); } return sb; } public int getMaxActiveJobs() { int sum = 0; for (Iterator it = scheduler(); it.hasNext();) { sum += ((JobScheduler) it.next()).getMaxActiveJobs(); } return sum; } public int getActiveJobs() { int sum = 0; for (Iterator it = scheduler(); it.hasNext();) { sum += ((JobScheduler) it.next()).getActiveJobs(); } return sum; } public int getQueueSize() { int sum = 0; for (Iterator it = scheduler(); it.hasNext();) { sum += ((JobScheduler) it.next()).getQueueSize(); } return sum; } public void setMaxActiveJobs(int maxJobs) { } public List getJobInfos() { List list = new ArrayList(); for (Iterator it = scheduler(); it.hasNext();) { list.addAll(((JobScheduler) it.next()).getJobInfos()); } return list; } public void setSchedulerId(String name, int id) { return; } public String getSchedulerName() { return "Manager"; } public int getSchedulerId() { return -1; } public void dumpSetup(PrintWriter pw) { for (Iterator it = scheduler(); it.hasNext();) { JobScheduler js = (JobScheduler) it.next(); pw.println("mover set max active -queue=" + js.getSchedulerName() + " " + js.getMaxActiveJobs()); } } } private class InventoryScanner implements Runnable { private Object _notifyMe = null; private InventoryScanner(Object notifyMe) { _notifyMe = notifyMe; } public void run() { _logClass.log("Running Repository (Cell is locked)"); _logClass.log("Repository seems to be ok"); try { _repository.runInventory(_logClass, _pnfs, _recoveryFlags); enablePool(); _logClass.elog("Pool enabled " + _poolName); } catch (CacheException cee) { _logClass.elog("Repository reported a problem : " + cee.getMessage()); _logClass.elog("Pool not enabled " + _poolName); disablePool(PoolV2Mode.DISABLED_STRICT, 2, "Init Failed"); } catch (Throwable t) { _logClass.elog("Repository reported Throwable : " + t); t.printStackTrace(); } _logClass.elog("Repository finished"); if (_notifyMe != null) { synchronized (_notifyMe) { _notifyMe.notifyAll(); } } } } public void cleanUp() { disablePool(PoolV2Mode.DISABLED_DEAD, 666, "Shutdown"); } // public void setMaxActiveIOs( int ios ){ _ioQueue.setMaxActiveJobs( ios) ; // } // // The sweeper class loader // // private SpaceSweeper getSweeperHandler() throws Exception { Class[] argClass = { dmg.cells.nucleus.CellAdapter.class, diskCacheV111.util.PnfsHandler.class, diskCacheV111.repository.CacheRepository.class, diskCacheV111.pools.HsmStorageHandler2.class }; Class sweeperClass = Class.forName(_sweeperClass); Constructor sweeperCon = sweeperClass.getConstructor(argClass); Object[] args = { this, _pnfs, _repository, _storageHandler }; return (SpaceSweeper) sweeperCon.newInstance(args); } private void setDummyStorageInfo(CacheRepositoryEntry entry) { try { StorageInfo storageInfo = entry.getStorageInfo(); storageInfo.setBitfileId("*"); _pnfs.setStorageInfoByPnfsId(entry.getPnfsId(), storageInfo, 0 // write // (don't // overwrite) ); } catch (Exception e) { // // for now we just ignore this exception (its dummy only) // esay("Problem in setDummyStorageInfo of : " + entry + " : " + e); } } // // interface between the repository and the StorageQueueContainer // (we do the pnfs stuff here as well) // private class RepositoryLoader implements CacheRepositoryListener { public void actionPerformed(CacheEvent event) { // forced by interface } public void sticky(CacheRepositoryEvent event) { say("RepositoryLoader : sticky : " + event); } public void precious(CacheRepositoryEvent event) { say("RepositoryLoader : precious : " + event); CacheRepositoryEntry entry = event.getRepositoryEntry(); long size = 0L; try { size = entry.getSize(); } catch (Exception ee) { esay("RepositoryLoader : can't get filesize : " + ee); // // if we can't get the size, so to be on the save side. // size = 1; } try { if ((size == 0) && !_flushZeroSizeFiles) { say("RepositoryLoader : 0 size file set cached (no HSM flush)"); if ((_lfsMode == LFS_NONE) || (_lfsMode == LFS_VOLATILE)) { entry.setCached(); setDummyStorageInfo(entry); } } else { if (_lfsMode == LFS_NONE) _storageQueue.addCacheEntry(entry); if (_lfsMode == LFS_VOLATILE) entry.setCached(); } } catch (CacheException ce) { esay("RepositoryLoader : Cache Exception in addCacheEntry [" + entry.getPnfsId() + "] : " + ce.getMessage()); } } public void cached(CacheRepositoryEvent event) { say("RepositoryLoader : cached : " + event); // // the remove will fail if the file // is coming FROM the store. // CacheRepositoryEntry entry = event.getRepositoryEntry(); try { CacheRepositoryEntry e = _storageQueue.removeCacheEntry(entry .getPnfsId()); say("RepositoryLoader : removing " + entry.getPnfsId() + (e == null ? " failed" : " ok")); } catch (CacheException ce) { esay("RepositoryLoader : remove " + entry.getPnfsId() + " failed : " + ce); } } public void available(CacheRepositoryEvent event) { say("RepositoryLoader : available : " + event); event.getRepositoryEntry().lock(false); } public void created(CacheRepositoryEvent event) { say("RepositoryLoader : created : " + event); _pnfs.addCacheLocation(event.getRepositoryEntry().getPnfsId()); } public void touched(CacheRepositoryEvent event) { say("RepositoryLoader : touched : " + event); } public void removed(CacheRepositoryEvent event) { say("RepositoryLoader : removed : " + event); CacheRepositoryEntry entry = event.getRepositoryEntry(); try { _storageQueue.removeCacheEntry(entry.getPnfsId()); } catch (CacheException ce) { esay("RepositoryLoader : PANIC : " + entry.getPnfsId() + " removing from storage queue failed : " + ce); } // // although we may be inconsistent now, we clear the database // (volatile systems remove the entry from pnfs if this was the last // copy) // _pnfs.clearCacheLocation(entry.getPnfsId(), _lfsMode == LFS_VOLATILE); // // if (_reportOnRemovals) { try { sendMessage(new CellMessage(_billingCell, new RemoveFileInfoMessage(getCellName() + "@" + getCellDomainName(), entry.getPnfsId()))); } catch (Exception ee) { esay("Couldn't report removal of : " + entry.getPnfsId() + " : " + ee); } } } public void destroyed(CacheRepositoryEvent event) { say("RepositoryLoader : destroyed : " + event); } public void needSpace(CacheNeedSpaceEvent event) { say("RepositoryLoader : needSpace : " + event); } public void scanned(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); try { if (entry.isPrecious() && (!entry.isBad()) && (_lfsMode == LFS_NONE)) { _storageQueue.addCacheEntry(entry); say("RepositoryLoader : Scanning " + entry.getPnfsId() + " ok"); } } catch (CacheException ce) { esay("RepositoryLoader : Scanning " + entry.getPnfsId() + " failed " + ce.getMessage()); } } } private void checkBaseDir() throws Exception { _base = new File(_baseDir); _setup = new File(_base, "setup"); if (!_setup.canRead()) throw new IllegalArgumentException( "Setup file not found or not readable : " + _setup); } private void execFile(File setup) throws Exception { BufferedReader br = new BufferedReader(new FileReader(setup)); String line = null; try { while ((line = br.readLine()) != null) { if (line.length() == 0) continue; if (line.charAt(0) == '#') continue; say("Execute setup : " + line); try { command(new Args(line)); } catch (Exception ce) { esay("Excecute setup failure : " + ce); esay("Excecute setup : won't continue"); throw ce; } } } finally { try { br.close(); } catch (Exception dummy) { } } return; } private void dumpSetup(PrintWriter pw) { pw.println("#\n# Created by " + getCellName() + "(" + this.getClass().getName() + ") at " + (new Date()).toString() + "\n#"); pw.println("set max diskspace " + _repository.getTotalSpace()); pw.println("set heartbeat " + _pingThread.getHeartbeat()); pw.println("set sticky " + (_allowSticky ? "allowed" : "denied")); pw.println("set report remove " + (_reportOnRemovals ? "on" : "off")); pw.println("set breakeven " + _breakEven); if (_suppressHsmLoad) pw.println("pool suppress hsmload on"); pw.println("set gap " + _gap); pw .println("set duplicate request " + (_dupRequest == DUP_REQ_NONE ? "none" : _dupRequest == DUP_REQ_IGNORE ? "ignore" : "refresh")); pw.println("set p2p " + (_p2pMode == P2P_INTEGRATED ? "integrated" : "separated")); _flushingThread.printSetup(pw); if (_storageQueue != null) _storageQueue.printSetup(pw); if (_storageHandler != null) _storageHandler.printSetup(pw); if (_hsmSet != null) _hsmSet.printSetup(pw); if (_sweeper != null) _sweeper.printSetup(pw); if (_ioQueue != null) ((IoQueueManager) _ioQueue).dumpSetup(pw); if (_p2pQueue != null) { pw.println("p2p set max active " + _p2pQueue.getMaxActiveJobs()); } if (_p2pClient != null) _p2pClient.printSetup(pw); if (_timeoutManager != null) _timeoutManager.printSetup(pw); _checksumModule.dumpSetup(pw); } private void dumpSetup() throws Exception { String name = _setup.getName(); String parent = _setup.getParent(); File tempFile = parent == null ? new File("." + name) : new File( parent, "." + name); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); try { dumpSetup(pw); } finally { try { pw.close(); } catch (Exception de) { } } if (!tempFile.renameTo(_setup)) throw new IOException("Rename failed (" + tempFile + " -> " + _setup + ")"); return; } public CellInfo getCellInfo() { PoolCellInfo info = new PoolCellInfo(super.getCellInfo()); info.setPoolCostInfo(getPoolCostInfo()); info.setTagMap(_tags); info.setErrorStatus(_poolStatusCode, _poolStatusMessage); return info; } public void log(String str) { say(str); } public void elog(String str) { esay(str); } public void plog(String str) { esay("PANIC : " + str); } public void getInfo(PrintWriter pw) { pw.println("Base directory : " + _baseDir); pw .println("Revision : [$Id: MultiProtocolPoolV3.java,v 1.16 2007-10-26 11:17:06 behrmann Exp $]"); pw.println("Version : " + getCellVersion() + " (Sub=" + _version + ")"); pw.println("StickyFiles : " + (_allowSticky ? "allowed" : "denied")); pw.println("ModifyFiles : " + (_allowModify ? "allowed" : "denied")); pw.println("Gap : " + _gap); pw.println("Report remove : " + (_reportOnRemovals ? "on" : "off")); pw .println("Recovery : " + ((_recoveryFlags & CacheRepository.ALLOW_CONTROL_RECOVERY) > 0 ? "CONTROL " : "") + ((_recoveryFlags & CacheRepository.ALLOW_SPACE_RECOVERY) > 0 ? "SPACE " : "") + ((_recoveryFlags & CacheRepository.ALLOW_RECOVER_ANYWAY) > 0 ? "ANYWAY " : "")); pw.println("Pool Mode : " + _poolMode); if (_poolMode.isDisabled()) { pw.println("Detail : [" + _poolStatusCode + "] " + _poolStatusMessage); } pw.println("Clean prec. files : " + (_cleanPreciousFiles ? "on" : "off")); pw.println("Hsm Load Suppr. : " + (_suppressHsmLoad ? "on" : "off")); pw.println("Ping Heartbeat : " + _pingThread.getHeartbeat() + " seconds"); pw.println("Storage Mode : " + (_isPermanent ? "Static" : "Dynamic")); pw.println("ReplicationMgr : " + _replicationHandler); pw.println("Check Repository : " + _checkRepository); pw.println("LargeFileStore : " + (_lfsMode == LFS_NONE ? "None" : _lfsMode == LFS_VOLATILE ? "Volatile" : "Precious")); pw.println("DuplicateRequests : " + (_dupRequest == DUP_REQ_NONE ? "None" : _dupRequest == DUP_REQ_IGNORE ? "Ignored" : "Refreshed")); pw.println("P2P Mode : " + (_p2pMode == P2P_INTEGRATED ? "Integrated" : "Separated")); pw.println("P2P File Mode : " + (_p2pFileMode == P2P_PRECIOUS ? "Precious" : "Cached")); if (_hybridInventoryActive) { pw.println("Inventory : " + _hybridCurrent); } pw.println("Diskspace usage : "); if (_repository != null) { long total = _repository.getTotalSpace(); long used = total - _repository.getFreeSpace(); long precious = _repository.getPreciousSpace(); pw.println(" Total : " + UnitInteger.toUnitString(total)); pw.println(" Used : " + used + " [" + (((float) used) / ((float) total)) + "]"); pw.println(" Free : " + (total - used)); pw.println(" Precious : " + precious + " [" + (((float) precious) / ((float) total)) + "]"); pw .println(" Removable: " + _sweeper.getRemovableSpace() + " [" + (((float) _sweeper.getRemovableSpace()) / ((float) total)) + "]"); pw.println(" Reserved : " + _repository.getReservedSpace()); } else { pw.println("No Yet known"); } if (_flushingThread != null) _flushingThread.getInfo(pw); pw.println("Storage Queue : "); if (_storageQueue != null) { pw.println(" Classes : " + _storageQueue.getStorageClassCount()); pw.println(" Requests : " + _storageQueue.getRequestCount()); } else { pw.println(" Not Yet known"); } if (_ioQueue != null) { IoQueueManager manager = (IoQueueManager) _ioQueue; pw.println("Mover Queue Manager : " + (manager.isConfigured() ? "Active" : "Not Configured")); for (Iterator it = manager.scheduler(); it.hasNext();) { JobScheduler js = (JobScheduler) it.next(); pw.println("Mover Queue (" + js.getSchedulerName() + ") " + js.getActiveJobs() + "(" + js.getMaxActiveJobs() + ")/" + js.getQueueSize()); } } if (_p2pQueue != null) pw.println("P2P Queue " + _p2pQueue.getActiveJobs() + "(" + _p2pQueue.getMaxActiveJobs() + ")/" + _p2pQueue.getQueueSize()); if (_storageHandler != null) _storageHandler.getInfo(pw); _p2pClient.getInfo(pw); _timeoutManager.getInfo(pw); _checksumModule.getInfo(pw); } public void say(String str) { pin(str); super.say(str); } public void esay(String str) { pin(str); super.esay(str); } // ////////////////////////////////////////////////////////////// // // The io File Part // // private void ioFile(PoolIoFileMessage poolMessage, CellMessage cellMessage) { cellMessage.revertDirection(); RepositoryIoHandler io = null; try { io = new RepositoryIoHandler(poolMessage, cellMessage); } catch (CacheException ce) { poolMessage.setFailed(ce.getRc(), ce.getMessage()); esay(ce.getMessage()); try { sendMessage(cellMessage); } catch (Exception e) { esay(e); } return; } Iterator i = _moverAttributes.keySet().iterator(); while (i.hasNext()) { try { Object key = i.next(); Object value = _moverAttributes.get(key); say("Setting mover " + key.toString() + " -> " + value); io.setAttribute(key.toString(), value); } catch (IllegalArgumentException iae) { esay("setAttribute : " + iae.getMessage()); } } String queueName = null; try { // // we could get a 'no such method exception' // queueName = poolMessage.getIoQueueName(); } catch (Exception ee) { say("Possibly old fashioned message : " + ee); } IoQueueManager queueManager = (IoQueueManager) _ioQueue; try { if (io.isWrite()) { queueManager.add(queueName, io, SimpleJobScheduler.HIGH); } else if (poolMessage.isPool2Pool()) { (_p2pMode == P2P_INTEGRATED ? _ioQueue : _p2pQueue).add(io, SimpleJobScheduler.HIGH); } else { String newClient = io.getClient(); long newId = io.getClientId(); if (_dupRequest != DUP_REQ_NONE) { JobInfo job = null; List list = _ioQueue.getJobInfos(); boolean found = false; for (int l = 0; l < list.size(); l++) { job = (JobInfo) list.get(l); if (newClient.equals(job.getClientName()) && (newId == job.getClientId())) { found = true; break; } } if (!found) { say("Dup Request : regular <" + newClient + ":" + newId + ">"); queueManager.add(queueName, io, SimpleJobScheduler.REGULAR); } else if (_dupRequest == DUP_REQ_IGNORE) { say("Dup Request : ignoring <" + newClient + ":" + newId + ">"); } else if (_dupRequest == DUP_REQ_REFRESH) { long jobId = job.getJobId(); say("Dup Request : refresing <" + newClient + ":" + newId + "> old = " + jobId); queueManager.kill((int) jobId); queueManager.add(queueName, io, SimpleJobScheduler.REGULAR); } else { say("Dup Request : PANIC (code corrupted) <" + newClient + ":" + newId + ">"); } } else { say("Dup Request : none <" + newClient + ":" + newId + ">"); queueManager.add(queueName, io, SimpleJobScheduler.REGULAR); } } } catch (InvocationTargetException ite) { esay("" + io + " not added due to : " + ite.getTargetException()); esay(ite); } return; } private class RepositoryIoHandler implements IoBatchable { private PoolIoFileMessage _command = null; private CellMessage _message = null; private String _clientPath = null; private PnfsId _pnfsId = null; private MoverProtocol _handler = null; private ProtocolInfo _protocolInfo = null; private StorageInfo _storageInfo = null; private CellPath _destination = null; private boolean _rdOnly = true; private boolean _create = false; private CacheRepositoryEntry _entry = null; private boolean _preparationDone = false; private DoorTransferFinishedMessage _finished = null; private MoverInfoMessage _info = null; private boolean _started = false; public RepositoryIoHandler(PoolIoFileMessage poolMessage, CellMessage originalCellMessage) throws CacheException { _message = originalCellMessage; _command = poolMessage; _destination = _message.getDestinationPath(); _pnfsId = _command.getPnfsId(); _protocolInfo = _command.getProtocolInfo(); _storageInfo = _command.getStorageInfo(); _info = new MoverInfoMessage(getCellName() + "@" + getCellDomainName(), _pnfsId); _info.setInitiator(_command.getInitiator()); CellPath tmp = (CellPath) _destination.clone(); tmp.revert(); _clientPath = tmp.getCellName() + "@" + tmp.getCellDomainName(); // // prepare the final reply // _finished = new DoorTransferFinishedMessage(_command.getId(), _pnfsId, _protocolInfo, _storageInfo, poolMessage .getPoolName()); try { // // we could get a 'no such method exception' // _finished.setIoQueueName(poolMessage.getIoQueueName()); } catch (Exception ee) { say("Possibly old fashioned message : " + ee); } // // we need to change the next two lines as soon // as we allow 'transient files'. // _rdOnly = poolMessage instanceof PoolDeliverFileMessage; _create = !_rdOnly; _info.setFileCreated(_create); _info.setStorageInfo(_storageInfo); // check for file existence if (_rdOnly && !_repository.contains(_pnfsId)) { // remove 'BAD' cachelocation in pnfs _pnfs.clearCacheLocation(_pnfsId); throw new FileNotInCacheException("Entry not in repository : " + _pnfsId); } } private boolean isWrite() { return _create; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(_pnfsId.toString()); if (_handler == null) { sb.append(" h={NoHandlerYet}"); } else { sb.append(" h={").append(_handler.toString()) .append("} bytes=").append( _handler.getBytesTransferred()).append( " time/sec=").append(getTransferTime() / 1000L) .append(" LM="); long lastTransferTime = getLastTransferred(); if (lastTransferTime == 0L) { sb.append(0); } else { sb.append((System.currentTimeMillis() - lastTransferTime) / 1000L); } } return sb.toString(); } private void setAttribute(String name, Object attribute) { if (_handler == null) { throw new IllegalArgumentException("Handler not yet installed"); } _handler.setAttribute(name, attribute); } private Object getAttribute(String name) { if (_handler == null) { throw new IllegalArgumentException("Handler not yet installed"); } return _handler.getAttribute(name); } private synchronized boolean prepare() { if (_preparationDone) return false; _preparationDone = true; boolean failed = false; say("JOB prepare " + _pnfsId); // // do all the preliminary stuff // - load Protocol Handler // - check File is ok // - increment the link count (to prevent the file from been // removed) // PnfsId pnfsId = _pnfsId; try { _handler = getProtocolHandler(_protocolInfo); if (_handler == null) throw new CacheException(27, "PANIC : Couldn't get handler for " + _protocolInfo); if (_create && _rdOnly) throw new IllegalArgumentException("Can't read and create"); synchronized (_repository) { if (_create) { _entry = _repository.createEntry(pnfsId); _entry.lock(true); _entry.setReceivingFromClient(); } else { _entry = _repository.getEntry(pnfsId); say("Entry for " + pnfsId + " found and is " + _entry); if ((!_entry.isCached()) && (!_entry.isPrecious())) throw new CacheException(301, "File is still transient : " + pnfsId); } _entry.incrementLinkCount(); } _command.setSucceeded(); } catch (FileNotInCacheException fce) { esay(_pnfsId + " not in repository"); // probably bad entry in cacheInfo, clean it _pnfs.clearCacheLocation(_pnfsId); failed = true; _command.setFailed(fce.getRc(), fce.getMessage()); } catch (CacheException ce) { esay("Io Thread Cache Exception : " + ce); esay(ce); if (ce.getRc() == CacheRepository.ERROR_IO_DISK) disablePool(PoolV2Mode.DISABLED_STRICT, ce.getRc(), ce .getMessage()); failed = true; _command.setFailed(ce.getRc(), ce.getMessage()); } catch (Exception exc) { esay("Thread Exception : " + exc); esay(exc); failed = true; _command.setFailed(11, exc.toString()); } // // send first acknowledge. // try { sendMessage(_message); } catch (Exception eee) { esay("Can't send message back to door : " + eee); esay(eee); failed = true; } if (failed) { try { if (_create) { _entry.lock(false); _repository.removeEntry(_entry); } } catch (CacheException ce) { esay("PANIC : couldn't remove entry : " + _entry); } esay("IoFile thread finished (request failure)"); } return failed; } // // the IoBatchable Interface // public PnfsId getPnfsId() { return _pnfsId; } public long getLastTransferred() { synchronized (this) { if (!_started) return 0L; } if (_handler == null) { return 0; } else { return _handler.getLastTransferred(); } } public long getTransferTime() { synchronized (this) { if (!_started) return 0L; } if (_handler == null) { return 0; } else { return _handler.getTransferTime(); } } public long getBytesTransferred() { if (_handler == null) { return 0; } else { return _handler.getBytesTransferred(); } } public double getTransferRate() { if (_handler == null) { return 10.000; } else { long bt = _handler.getBytesTransferred(); long tm = _handler.getTransferTime(); return tm == 0L ? (double) 10.00 : ((double) bt / (double) tm); } } // // the Batchable Interface // public String getClient() { return _clientPath; } public long getClientId() { return _command.getId(); } public void queued() { say("JOB queued " + _pnfsId); if (prepare()) throw new IllegalArgumentException("prepare failed"); } public void unqueued() { say("JOB unqueued " + _pnfsId); // // TBD: have to send 'failed' as last message // return; } // // the Runnable Interface // public void run() { say("JOB run " + _pnfsId); if (prepare()) return; synchronized (this) { _started = true; } SysTimer sysTimer = new SysTimer(); long transferTimer = System.currentTimeMillis(); RandomAccessFile raf = null; MoverProtocol moverProtocol = null; SpaceMonitor monitor = _repository; File cacheFile = null; ChecksumMover csmover = null; ChecksumFactory clientChecksumFactory = null; if (!_crashEnabled) { _storageInfo.setKey("crash", null); } else { _storageInfo.setKey("crashType", _crashType); } try { cacheFile = _entry.getDataFile(); say("Trying to open " + cacheFile); raf = new RandomAccessFile(cacheFile, (_rdOnly && !_allowModify) ? "r" : "rw"); if (_create) { sysTimer.getDifference(); String tmp = null; long preallocatedSpace = 0L; long maxAllocatedSpace = 0L; if ((tmp = _storageInfo.getKey(PREALLOCATED_SPACE)) != null) { try { preallocatedSpace = Long.parseLong(tmp); } catch (NumberFormatException ee) { /* ignore 'bad' values*/ } } if ((tmp = _storageInfo.getKey(MAX_SPACE)) != null) { try { maxAllocatedSpace = Long.parseLong(tmp); } catch (NumberFormatException ee) {/* ignore 'bad' values*/ } } if ((preallocatedSpace > 0L) || (maxAllocatedSpace > 0L)) monitor = new PreallocationSpaceMonitor(_repository, preallocatedSpace, maxAllocatedSpace); csmover = _handler instanceof ChecksumMover ? (ChecksumMover) _handler : null; if( csmover != null ){ say("Checksum mover is set"); clientChecksumFactory = csmover.getChecksumFactory(_protocolInfo); Checksum checksum = null; if ( clientChecksumFactory != null ){ say("Got checksum factory of "+clientChecksumFactory.getType()); checksum = clientChecksumFactory.create(); } else checksum = _checksumModule.getDefaultChecksumFactory().create(); if ( _checksumModule.checkOnTransfer() ){ csmover.setDigest(checksum); } } _handler.runIO(raf, _protocolInfo, _storageInfo, _pnfsId, monitor, MoverProtocol.WRITE | MoverProtocol.READ); long fileSize = cacheFile.length(); _storageInfo.setFileSize(fileSize); _info.setFileSize(fileSize); if (csmover != null) { _checksumModule.setMoverChecksums(_entry, clientChecksumFactory, csmover .getClientChecksum(), _checksumModule .checkOnTransfer() ? csmover .getTransferChecksum() : null); } else { _checksumModule.setMoverChecksums(_entry, null, null, null); } boolean overwrite = _storageInfo.getKey("overwrite") != null; say(_pnfsId.toString() + ";length=" + fileSize + ";timer=" + sysTimer.getDifference().toString()); // // store the storage info and set the file precious. // ( first remove the lock, otherwise the // state for the precious events is wrong. // /* * Due to support of <AccessLatency> and <RetentionPolicy> * the file state in the pool has changed has changed it's * meaning: * precious: have to goto tape * cached: free to be removed by sweeper * cached+sticky: does not go to tape, isn't removed by sweeper * * new states depending on AL and RP: * Custodial+ONLINE (T1D1) : precious+sticky => cached+sticky * Custodial+NEARLINE (T1D0) : precious => cached * Output+ONLINE (T0D1) : cached+sticky => cached+sticky * */ _entry.lock(false) ; _entry.setStorageInfo( _storageInfo ) ; // flush to tape only if the file defined as a 'tape file'( RP = Custodial) and the HSM is defined String hsm = _storageInfo.getHsm(); RetentionPolicy retentionPolicy = _storageInfo.getRetentionPolicy(); if( retentionPolicy != null && retentionPolicy.equals(RetentionPolicy.CUSTODIAL) ) { if(hsm != null && !hsm.toLowerCase().equals("none") ) { _entry.setPrecious() ; }else{ _entry.setCached() ; } }else{ _entry.setCached() ; } AccessLatency accessLatency = _storageInfo.getAccessLatency(); if( accessLatency != null && accessLatency.equals( AccessLatency.ONLINE) ) { // TODO: probably, we have to notify PinManager // HopingManager have to copy file into a 'read' pool if // needed, set copy 'sticky' and remove sticky flag in the 'write' pool _entry.setSticky(true); }else{ _entry.setSticky(false); - } if (overwrite) { + } + + if (overwrite) { _entry.setCached(); say("Overwriting requested"); } // // setFileSize will throw an exception if the file is no // longer in pnfs. As a result, the client will let the // close fail and we will remove the entries from the // the repository. // if ((!overwrite) && (!_isHsmPool)) { _pnfs.setFileSize(_pnfsId, fileSize); if (_lfsMode == MultiProtocolPoolV3.LFS_NONE) { _pnfs.putPnfsFlag(_pnfsId, "h", "yes"); } else { _pnfs.putPnfsFlag(_pnfsId, "h", "no"); } } // _replicationHandler.initiateReplication(_entry, "write"); // // cache location changed by event handler // // } else { sysTimer.getDifference(); long fileSize = cacheFile.length(); _info.setFileSize(fileSize); _handler .runIO( raf, _protocolInfo, _storageInfo, _pnfsId, _repository, MoverProtocol.READ | (_entry.isPrecious() && _allowModify ? MoverProtocol.WRITE : 0)); if (_handler.wasChanged() && (!_isHsmPool)) { fileSize = cacheFile.length(); try { _pnfs.setFileSize(_pnfsId, fileSize); } catch (Exception eee) { esay(_pnfsId.toString() + " failed to change filesize"); } } // // better we close it here (otherwise small files may just // disappear) // try { raf.close(); // TODO: some logic depends on this 'nulling' raf = null; } catch (IOException ee) { // IO error ? } say(_pnfsId.toString() + ";length=" + fileSize + ";timer=" + sysTimer.getDifference().toString()); } _finished.setSucceeded(); } catch (Exception eofe) { esay("Exception in runIO for : " + _pnfsId + " " + eofe); if (!(eofe instanceof EOFException)) esay(eofe); if (eofe instanceof CacheException) { int errorCode = ((CacheException) eofe).getRc(); if (errorCode == CacheRepository.ERROR_IO_DISK) { disablePool(PoolV2Mode.DISABLED_STRICT, errorCode, eofe .getMessage()); fsay(eofe.getMessage()); } } try { // remove newly created zero size files if there was a // problem to write it (no close arrived) if (_create) { if ((raf != null) && (raf.length() == 0)) { esay("removing empty file: " + _pnfsId); _entry.lock(false); _repository.removeEntry(_entry); if (!_isHsmPool) _pnfs.deletePnfsEntry(_pnfsId); } else { // FIXME: this part is not as elegant as it's should // be - duplicated code // set file size long fileSize = cacheFile.length(); esay("Storing incomplete file : " + _pnfsId + " with " + fileSize); _storageInfo.setFileSize(fileSize); _info.setFileSize(fileSize); _entry.lock(false); _entry.setStorageInfo(_storageInfo); _entry.setPrecious(); if (!_isHsmPool) { _pnfs.setFileSize(_pnfsId, fileSize); if (_lfsMode == MultiProtocolPoolV3.LFS_NONE) { _pnfs.putPnfsFlag(_pnfsId, "h", "yes"); } else { _pnfs.putPnfsFlag(_pnfsId, "h", "no"); } } // set checksum if (csmover != null) { _checksumModule .setMoverChecksums( _entry, clientChecksumFactory, csmover.getClientChecksum(), _checksumModule .checkOnTransfer() ? csmover .getTransferChecksum() : null); } else { _checksumModule.setMoverChecksums(_entry, null, null, null); } } } } catch (Throwable e) { esay("Stacked Exception (Original) for : " + _entry + " : "+ eofe); esay("Stacked Throwable (Resulting) for : " + _entry+ " : " + e); esay(e); } finally { String errorMessage = "Unexpected Exception : " + eofe; int errorCode = 33; if (eofe instanceof CacheException) { errorCode = ((CacheException) eofe).getRc(); errorMessage = eofe.getMessage(); } _finished.setReply(errorCode, errorMessage); _info.setResult(errorCode, errorMessage); } } catch (Throwable e) { esay("Throwable in runIO() " + _entry + " " + e); esay(e); _finished.setReply(34, e); _info.setResult(34, e.toString()); } finally { try { _entry.decrementLinkCount(); } catch (CacheException ce_ignored) { // Exception never thrown } try { if (raf != null) { raf.close(); } } catch (IOException ee) { esay("Couldn't close Random access file"); esay(ee); } try { if (monitor instanceof PreallocationSpaceMonitor) { PreallocationSpaceMonitor m = (PreallocationSpaceMonitor) monitor; long usedSpace = m.getUsedSpace(); say("Applying preallocated space : " + usedSpace); if (usedSpace > 0L) _repository.applyReservedSpace(usedSpace); } } catch (Exception ee) { esay("Problem handling reserved space management : " + ee); esay(ee); } transferTimer = System.currentTimeMillis() - transferTimer; long bytesTransferred = _handler.getBytesTransferred(); _info.setTransferAttributes(bytesTransferred, transferTimer, _protocolInfo); } try { _message.setMessageObject(_finished); sendMessage(_message); } catch (Exception eee) { esay("PANIC : Can't send message back to door : " + eee); esay(eee); } try { sendMessage(new CellMessage(_billingCell, _info)); } catch (Exception eee) { esay("PANIC : Can't report to 'billing cell' : " + eee); esay(eee); } say("IO thread finished : " + Thread.currentThread().toString()); } public void ided(int id) { // say("RepositoryIoHandler.ided("+id+")"); _command.setMoverId(id); } } // ////////////////////////////////////////////////////////////// // // replication on data arrived // private class ReplicationHandler { private boolean _enabled = false; private String _replicationManager = "PoolManager"; private String _destinationHostName = null; private String _destinationMode = "keep"; private boolean _replicateOnRestore = false; // // replicationManager,Hostname,modeOfDestFile // private ReplicationHandler() { init(null); } private ReplicationHandler(String vars) { init(vars); } public void init(String vars) { if (_destinationHostName == null) { try { _destinationHostName = InetAddress.getLocalHost() .getHostAddress(); } catch (Exception ee) { _destinationHostName = "localhost"; } } if ((vars == null) || vars.equals("off")) { _enabled = false; return; } else if (vars.equals("on")) { _enabled = true; return; } _enabled = true; String[] args = vars.split(","); _replicationManager = (args.length > 0) && (!args[0].equals("")) ? args[0] : _replicationManager; _destinationHostName = (args.length > 1) && (!args[1].equals("")) ? args[1] : _destinationHostName; _destinationMode = (args.length > 2) && (!args[2].equals("")) ? args[2] : _destinationMode; if (_destinationHostName.equals("*")) { try { _destinationHostName = InetAddress.getLocalHost() .getHostAddress(); } catch (Exception ee) { _destinationHostName = "localhost"; } } return; } public String getParameterString() { StringBuffer sb = new StringBuffer(); if (_enabled) { sb.append(_replicationManager).append(_destinationHostName) .append(_destinationMode); } else { sb.append("off"); } return sb.toString(); } public String toString() { StringBuffer sb = new StringBuffer(); if (_enabled) { sb.append("{Mgr=").append(_replicationManager).append(",Host=") .append(_destinationHostName).append(",DestMode=") .append(_destinationMode).append("}"); } else { sb.append("Disabled"); } return sb.toString(); } private void initiateReplication(CacheRepositoryEntry entry, String source) { if ((!_enabled) || (source.equals("restore") && !_replicateOnRestore)) return; try { _initiateReplication(entry, source); } catch (Exception ee) { esay("Problem in sending replication request : " + ee); esay(ee); } } private void _initiateReplication(CacheRepositoryEntry entry, String source) throws Exception { PnfsId pnfsId = entry.getPnfsId(); StorageInfo storageInfo = entry.getStorageInfo(); storageInfo.setKey("replication.source", source); PoolMgrReplicateFileMsg req = new PoolMgrReplicateFileMsg(pnfsId, storageInfo, new DCapProtocolInfo("DCap", 3, 0, _destinationHostName, 2222), storageInfo .getFileSize()); req.setReplyRequired(false); sendMessage(new CellMessage(new CellPath(_replicationManager), req)); } } // /////////////////////////////////////////////////////////// // // The mover class loader // // private Hashtable<String, Class> _handlerClasses = new Hashtable<String, Class>(); private MoverProtocol getProtocolHandler(ProtocolInfo info) { Class<?>[] argsClass = { dmg.cells.nucleus.CellAdapter.class }; String moverClassName = info.getProtocol() + "-" + info.getMajorVersion(); Class<?> mover = _moverHash.get(moverClassName); try { if (mover == null) { moverClassName = "diskCacheV111.movers." + info.getProtocol() + "Protocol_" + info.getMajorVersion(); mover = _handlerClasses.get(moverClassName); if (mover == null) { mover = Class.forName(moverClassName); _handlerClasses.put(moverClassName, mover); } } Constructor<?> moverCon = mover.getConstructor(argsClass); Object[] args = { this }; return (MoverProtocol) moverCon.newInstance(args); } catch (Exception e) { esay("Couldn't get Handler Class" + moverClassName); esay(e); return null; } } // ////////////////////////////////////////////////////////////////////////// // // interface to the HsmRestoreHandler // private class ReplyToPoolFetch implements CacheFileAvailable { private CellMessage _cellMessage = null; private ReplyToPoolFetch(CellMessage cellMessage) { _cellMessage = cellMessage; } public void cacheFileAvailable(String pnfsId, Throwable ee) { Message msg = (Message) _cellMessage.getMessageObject(); if (ee != null) { if (ee instanceof CacheException) { CacheException ce = (CacheException) ee; int errorCode = ce.getRc(); msg.setFailed(errorCode, ce.getMessage()); switch (errorCode) { case 41: case 42: case 43: disablePool(PoolV2Mode.DISABLED_STRICT, errorCode, ce .getMessage()); } } else { msg.setFailed(1000, ee); } } else { try { PnfsId id = new PnfsId(pnfsId); CacheRepositoryEntry entry = _repository.getEntry(id); msg.setSucceeded(); doChecksum(id, entry); try { _replicationHandler.initiateReplication(entry, "restore"); } catch (Exception eee) { esay("Problems in replicating : " + entry + " (" + eee + ")"); } } catch (Exception ee2) { msg.setFailed(1010, "Checksum calculation failed " + ee2); esay("Checksum calculation failed : " + ee2); esay(ee); } } _cellMessage.revertDirection(); esay("cacheFileAvailable : Returning from restore : " + _cellMessage.getMessageObject()); try { sendMessage(_cellMessage); } catch (Exception iee) { esay("Sorry coudn't send ack to poolManager : " + iee); } } private void doChecksum(PnfsId pnfsId, CacheRepositoryEntry entry) { Message msg = (Message) _cellMessage.getMessageObject(); if (_checksumModule.getCrcFromHsm()) getChecksumFromHsm(pnfsId, entry); if (!_checksumModule.checkOnRestore()) return; say("Calculating checksum of " + pnfsId); try { StorageInfo info = entry.getStorageInfo(); String checksumString = info.getKey("flag-c"); if (checksumString == null) throw new Exception("Checksum not in StorageInfo"); long start = System.currentTimeMillis(); Checksum infoChecksum = new Checksum(checksumString); Checksum fileChecksum = _checksumModule.calculateFileChecksum( entry, _checksumModule.getDefaultChecksum()); say("Checksum for " + pnfsId + " info=" + infoChecksum + ";file=" + fileChecksum + " in " + (System.currentTimeMillis() - start)); if (!infoChecksum.equals(fileChecksum)) { esay("Checksum of " + pnfsId + " differs info=" + infoChecksum + ";file=" + fileChecksum); try { _repository.removeEntry(entry); } catch (Exception ee2) { esay("Couldn't remove file : " + pnfsId + " : " + ee2); } msg.setFailed(1009, "Checksum error : info=" + infoChecksum + ";file=" + fileChecksum); } } catch (Exception ee3) { esay("Couldn't compare checksum of " + pnfsId + " : " + ee3); ee3.printStackTrace(); } } private void getChecksumFromHsm(PnfsId pnfsId, CacheRepositoryEntry entry) { String line = null; try { File f = entry.getDataFile(); f = new File(f.getCanonicalPath() + ".crcval"); Checksum checksum = null; if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); try { line = "1:" + br.readLine(); checksum = new Checksum(line); } finally { try { br.close(); } catch (IOException ioio) { } f.delete(); } say(pnfsId + " : sending adler32 to pnfs : " + line); _checksumModule .storeChecksumInPnfs(pnfsId, checksum, false); } } catch (Exception waste) { esay("Couldn't send checksum (" + line + ") to pnfs : " + waste); } } } private boolean fetchFile(PoolFetchFileMessage poolMessage, CellMessage cellMessage) { PnfsId pnfsId = poolMessage.getPnfsId(); StorageInfo storageInfo = poolMessage.getStorageInfo(); say("Pool " + _poolName + " asked to fetch file " + pnfsId + " (hsm=" + storageInfo.getHsm() + ")"); try { if ((storageInfo.getFileSize() == 0) && !_flushZeroSizeFiles) { CacheRepositoryEntry entry = _repository.createEntry(pnfsId); entry.setStorageInfo(storageInfo); entry.setReceivingFromStore(); entry.setCached(); return true; } ReplyToPoolFetch reply = new ReplyToPoolFetch(cellMessage); if (_storageHandler.fetch(pnfsId, storageInfo, reply)) { poolMessage.setSucceeded(); return true; } else { return false; } } catch (FileInCacheException ce) { esay(ce); poolMessage.setFailed(0, null); return true; } catch (CacheException ce) { esay(ce); poolMessage.setFailed(ce.getRc(), ce); if (ce.getRc() == CacheRepository.ERROR_IO_DISK) disablePool(PoolV2Mode.DISABLED_STRICT, ce.getRc(), ce .getMessage()); return true; } catch (Exception ui) { esay(ui); poolMessage.setFailed(100, ui); return true; } } private void checkFile(PoolFileCheckable poolMessage) { PnfsId pnfsId = poolMessage.getPnfsId(); try { CacheRepositoryEntry entry = _repository.getEntry(pnfsId); poolMessage.setWaiting(false); if (entry.isReceivingFromClient() || entry.isReceivingFromStore()) { poolMessage.setHave(false); poolMessage.setWaiting(true); } else { // old behavior, probably we do not need it any more // TODO: remove it ASAP /* * if( entry.getDataFile().length() == 0 ) throw new * FileNotInCacheException("Filesize(fs) == 0") ; */ poolMessage.setHave(true); } } catch (FileNotInCacheException fe) { poolMessage.setHave(false); } catch (Exception e) { esay("Could get information about <" + pnfsId + "> : " + e.getMessage()); poolMessage.setHave(false); } } private void setSticky(PoolSetStickyMessage stickyMessage) { if (stickyMessage.isSticky() && (!_allowSticky)) { stickyMessage.setFailed(101, "making sticky denied by pool : " + _poolName); return; } PnfsId pnfsId = stickyMessage.getPnfsId(); try { /* * add sticky owner and lifetime if repository supports it */ CacheRepositoryEntry entry = _repository.getEntry(pnfsId); entry.setSticky(stickyMessage .isSticky(), stickyMessage.getOwner(), stickyMessage .getLifeTime()); } catch (CacheException ce) { stickyMessage.setFailed(ce.getRc(), ce); return; } catch (Exception ee) { stickyMessage.setFailed(100, ee); return; } return; } private void modifyPersistency( PoolModifyPersistencyMessage persistencyMessage) { PnfsId pnfsId = persistencyMessage.getPnfsId(); try { CacheRepositoryEntry entry = _repository.getEntry(pnfsId); if (entry.isPrecious()) { if (persistencyMessage.isCached()) entry.setCached(); } else if (entry.isCached()) { if (persistencyMessage.isPrecious()) entry.setPrecious(true); } else { persistencyMessage.setFailed(101, "File still transient : " + entry); return; } } catch (CacheException ce) { persistencyMessage.setFailed(ce.getRc(), ce); return; } catch (Exception ee) { persistencyMessage.setFailed(100, ee); return; } return; } private void modifyPoolMode(PoolModifyModeMessage modeMessage) { PoolV2Mode mode = modeMessage.getPoolMode(); if (mode == null) return; if (mode.isEnabled()) { enablePool(); } else { disablePool(mode.getMode(), modeMessage.getStatusCode(), modeMessage.getStatusMessage()); } return; } private void checkFreeSpace(PoolCheckFreeSpaceMessage poolMessage) { // long freeSpace = _repository.getFreeSpace() ; long freeSpace = 1024L * 1024L * 1024L * 100L; say("XChecking free space [ result = " + freeSpace + " ] "); poolMessage.setFreeSpace(freeSpace); poolMessage.setSucceeded(); } private void updateCacheStatistics( PoolUpdateCacheStatisticsMessage poolMessage) { // / } private class CompanionFileAvailableCallback implements CacheFileAvailable { private final CellMessage _cellMessage ; private final Pool2PoolTransferMsg _poolMessage ; private final PnfsId _pnfsId ; private CompanionFileAvailableCallback(CellMessage cellMessage, Pool2PoolTransferMsg poolMessage, PnfsId pnfsId) { this._cellMessage = cellMessage; this._poolMessage = poolMessage; this._pnfsId = pnfsId; } public void cacheFileAvailable(String pnfsIdString, Throwable e) { if (e != null) { if (e instanceof CacheException) { _poolMessage.setReply(((CacheException) e).getRc(), e); } else { _poolMessage.setReply(102, e); } } else { try { // // the default mode of a p2p copy is 'cached'. // So we only have to change the mode if the customer // needs something different. // // ( API overwrites the configuration setting ) // CacheRepositoryEntry entry = _repository.getEntry(_pnfsId); try { int fileMode = _poolMessage.getDestinationFileStatus(); if (fileMode != Pool2PoolTransferMsg.UNDETERMINED) { if (fileMode == Pool2PoolTransferMsg.PRECIOUS) entry.setPrecious(true); } else { if ((_lfsMode == LFS_PRECIOUS) && (_p2pFileMode == P2P_PRECIOUS)) { entry.setPrecious(true); } } } catch (Exception eee) { esay("Couldn't set precious : " + entry + " : " + eee); throw eee; } } catch (Exception ee) { // // we regard this transfer as OK, even if setting the file // mode // failed. // esay("Problems setting file mode : " + ee); } } if (_poolMessage.getReplyRequired()) { say("Sending p2p reply " + _poolMessage); try { say("CellMessage before revert : " + _cellMessage); _cellMessage.revertDirection(); say("CellMessage after revert : " + _cellMessage); sendMessage(_cellMessage); } catch (Exception ee) { ee.printStackTrace(); esay("Can't reply p2p message : " + ee); } } } } private void runPool2PoolClient(final CellMessage cellMessage, final Pool2PoolTransferMsg poolMessage) { String poolName = poolMessage.getPoolName(); PnfsId pnfsId = poolMessage.getPnfsId(); StorageInfo storageInfo = poolMessage.getStorageInfo(); try { CacheFileAvailable callback = new CompanionFileAvailableCallback( cellMessage, poolMessage, pnfsId); _p2pClient.newCompanion(pnfsId, poolName, storageInfo, callback); } catch (Exception ee) { esay("Exception from _p2pClient.newCompanion of : " + pnfsId + " : " + ee); if (ee instanceof FileInCacheException) { poolMessage.setReply(0, null); } else { poolMessage.setReply(102, ee); } try { say("Sending p2p reply " + poolMessage); cellMessage.revertDirection(); sendMessage(cellMessage); } catch (Exception eee) { esay("Can't reply p2p message : " + eee); } } } public void messageArrived(CellMessage cellMessage) { Object messageObject = cellMessage.getMessageObject(); if (!(messageObject instanceof Message)) { say("Unexpected message class 1 " + messageObject.getClass()); return; } Message poolMessage = (Message) messageObject; boolean replyRequired = poolMessage.getReplyRequired(); if (poolMessage instanceof PoolMoverKillMessage) { PoolMoverKillMessage kill = (PoolMoverKillMessage) poolMessage; say("PoolMoverKillMessage for mover id " + kill.getMoverId()); try { mover_kill(kill.getMoverId()); } catch (Exception e) { esay(e); kill.setReply(1, e); } } else if (poolMessage instanceof PoolFlushControlMessage) { _flushingThread.messageArrived( (PoolFlushControlMessage) poolMessage, cellMessage); return; } else if (poolMessage instanceof DoorTransferFinishedMessage) { _p2pClient.messageArrived(poolMessage, cellMessage); return; } else if (poolMessage instanceof PoolIoFileMessage) { PoolIoFileMessage msg = (PoolIoFileMessage) poolMessage; if (msg.isPool2Pool() && msg.isReply()) { say("Pool2PoolIoFileMsg delivered to p2p Client"); _p2pClient.messageArrived(poolMessage, cellMessage); } else { say("PoolIoFileMessage delivered to ioFile (method)"); if (((poolMessage instanceof PoolAcceptFileMessage) && _poolMode .isDisabled(PoolV2Mode.DISABLED_STORE)) || ((poolMessage instanceof PoolDeliverFileMessage) && _poolMode .isDisabled(PoolV2Mode.DISABLED_FETCH))) { esay("PoolIoFileMessage Request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } msg.setReply(); ioFile((PoolIoFileMessage) poolMessage, cellMessage); } return; } else if (poolMessage instanceof Pool2PoolTransferMsg) { if (_poolMode.isDisabled(PoolV2Mode.DISABLED_P2P_CLIENT)) { esay("Pool2PoolTransferMsg Request rejected due to " + _poolMode); sentNotEnabledException( poolMessage, cellMessage); return; } runPool2PoolClient(cellMessage, (Pool2PoolTransferMsg) poolMessage); poolMessage.setReply(); return; } else if (poolMessage instanceof PoolFetchFileMessage) { if ((_poolMode.isDisabled(PoolV2Mode.DISABLED_STAGE)) || (_lfsMode != LFS_NONE)) { esay("PoolFetchFileMessage Request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } replyRequired = fetchFile((PoolFetchFileMessage) poolMessage, cellMessage); } else if (poolMessage instanceof PoolRemoveFilesFromHSMMessage) { if ((_poolMode.isDisabled(PoolV2Mode.DISABLED_STAGE)) || (_lfsMode != LFS_NONE)) { esay("PoolRemoveFilesFromHsmMessage request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } _storageHandler.remove(cellMessage); replyRequired = false; } else if (poolMessage instanceof PoolCheckFreeSpaceMessage) { if (_poolMode.isDisabled(PoolV2Mode.DISABLED)) { esay("PoolCheckFreeSpaceMessage Request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } checkFreeSpace((PoolCheckFreeSpaceMessage) poolMessage); } else if (poolMessage instanceof PoolCheckable) { if( _poolMode.getMode() == PoolV2Mode.DISABLED || _poolMode.isDisabled(PoolV2Mode.DISABLED_FETCH) || _poolMode.isDisabled(PoolV2Mode.DISABLED_DEAD)){ esay("PoolCheckable Request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } if (poolMessage instanceof PoolFileCheckable) { checkFile((PoolFileCheckable) poolMessage); poolMessage.setSucceeded(); } } else if (poolMessage instanceof PoolUpdateCacheStatisticsMessage) { updateCacheStatistics((PoolUpdateCacheStatisticsMessage) poolMessage); } else if (poolMessage instanceof PoolRemoveFilesMessage) { if (_poolMode.isDisabled(PoolV2Mode.DISABLED)) { esay("PoolRemoveFilesMessage Request rejected due to " + _poolMode); sentNotEnabledException(poolMessage, cellMessage); return; } removeFiles((PoolRemoveFilesMessage) poolMessage); } else if (poolMessage instanceof PoolModifyPersistencyMessage) { modifyPersistency((PoolModifyPersistencyMessage) poolMessage); } else if (poolMessage instanceof PoolModifyModeMessage) { modifyPoolMode((PoolModifyModeMessage) poolMessage); } else if (poolMessage instanceof PoolSetStickyMessage) { setSticky((PoolSetStickyMessage) poolMessage); } else if (poolMessage instanceof PoolQueryRepositoryMsg) { getRepositoryListing((PoolQueryRepositoryMsg) poolMessage); replyRequired = true; } else if (poolMessage instanceof PoolSpaceReservationMessage) { replyRequired = false; runSpaceReservation((PoolSpaceReservationMessage) poolMessage, cellMessage); } else { say("Unexpected message class 2" + poolMessage.getClass()); say(" isReply = " + ( poolMessage).isReply()); // REMOVE say(" source = " + cellMessage.getSourceAddress()); return; } if (!replyRequired) return; try { say("Sending reply " + poolMessage); cellMessage.revertDirection(); sendMessage(cellMessage); } catch (Exception e) { esay("Can't reply message : " + e); } } private void runSpaceReservation( final PoolSpaceReservationMessage spaceReservationMessage, final CellMessage cellMessage) { if (_blockOnNoSpace && (spaceReservationMessage instanceof PoolReserveSpaceMessage)) { getNucleus().newThread(new Runnable() { public void run() { say("Reservation job started"); spaceReservation(spaceReservationMessage, cellMessage); say("Reservation job finished"); } }, "reservationThread").start(); } else { spaceReservation(spaceReservationMessage, cellMessage); } } private void spaceReservation( PoolSpaceReservationMessage spaceReservationMessage, CellMessage cellMessage) { try { if (spaceReservationMessage instanceof PoolReserveSpaceMessage) { PoolReserveSpaceMessage reserve = (PoolReserveSpaceMessage) spaceReservationMessage; _repository.reserveSpace(reserve.getSpaceReservationSize(), _blockOnNoSpace); } else if (spaceReservationMessage instanceof PoolFreeSpaceReservationMessage) { _repository .freeReservedSpace(((PoolFreeSpaceReservationMessage) spaceReservationMessage) .getFreeSpaceReservationSize()); } else if (spaceReservationMessage instanceof PoolQuerySpaceReservationMessage) { } spaceReservationMessage.setReservedSpace(_repository .getReservedSpace()); } catch (CacheException ce) { spaceReservationMessage.setFailed(ce.getRc(), ce.getMessage()); } catch (MissingResourceException mre) { spaceReservationMessage.setFailed(104, mre); } catch (Exception ee) { spaceReservationMessage.setFailed(101, ee.toString()); } try { say("Sending reply " + spaceReservationMessage); cellMessage.revertDirection(); sendMessage(cellMessage); } catch (Exception e) { esay("Can't reply message : " + e); } } private void getRepositoryListing(PoolQueryRepositoryMsg queryMessage) { queryMessage.setReply(new RepositoryCookie(), _repository .getValidPnfsidList()); } private void sentNotEnabledException(Message poolMessage, CellMessage cellMessage) { try { say("Sending reply " + poolMessage); poolMessage.setFailed(104, "Pool is disabled"); cellMessage.revertDirection(); sendMessage(cellMessage); } catch (Exception e) { esay("Can't reply message : " + e); } } public String hh_simulate_cost = "[-cpu=<cpuCost>] [-space=<space>]"; public String ac_simulate_cost(Args args) throws Exception { String tmp = args.getOpt("cpu"); if (tmp != null) _simCpuCost = Double.parseDouble(tmp); tmp = args.getOpt("space"); if (tmp != null) _simSpaceCost = Double.parseDouble(tmp); return "Costs : cpu = " + _simCpuCost + " , space = " + _simSpaceCost; } /** * Partially or fully disables normal operation of this pool. */ private synchronized void disablePool(int mode, int errorCode, String errorString) { _poolStatusCode = errorCode; _poolStatusMessage = (errorString == null ? "Requested By Operator" : errorString); _poolMode.setMode(mode); _pingThread.sendPoolManagerMessage(true); esay("New Pool Mode : " + _poolMode); } /** * Fully enables this pool. The status code is set to 0 and the * status message is cleared. */ private synchronized void enablePool() { _poolMode.setMode(PoolV2Mode.ENABLED); _poolStatusCode = 0; _poolStatusMessage = "OK"; _pingThread.sendPoolManagerMessage(true); esay("New Pool Mode : " + _poolMode); } private class PoolManagerPingThread implements Runnable { private final Thread _worker; private int _heartbeat = 30; private PoolManagerPingThread() { _worker = _nucleus.newThread(this, "ping"); } private void start() { _worker.start(); } public void run() { say("Ping Thread started"); while (!Thread.interrupted()) { if (_poolMode.isEnabled() && _checkRepository && !_repository.isRepositoryOk()) { esay("Pool disabled due to problems in repository") ; disablePool(PoolV2Mode.DISABLED | PoolV2Mode.DISABLED_STRICT, 99, "Repository got lost"); } sendPoolManagerMessage(true); try { Thread.sleep(_heartbeat*1000); } catch(InterruptedException e) { esay("Ping Thread was interrupted"); break; } } esay("Ping Thread sending Pool Down message"); disablePool(PoolV2Mode.DISABLED_DEAD, 666, "PingThread terminated"); esay("Ping Thread finished"); } public void setHeartbeat(int seconds) { _heartbeat = seconds; } public int getHeartbeat() { return _heartbeat; } public synchronized void sendPoolManagerMessage(boolean forceSend) { if (forceSend || _storageQueue.poolStatusChanged()) send(getPoolManagerMessage()); } private CellMessage getPoolManagerMessage() { boolean disabled = _poolMode.getMode() == PoolV2Mode.DISABLED || _poolMode.isDisabled(PoolV2Mode.DISABLED_STRICT) || _poolMode.isDisabled(PoolV2Mode.DISABLED_DEAD); PoolCostInfo info = disabled ? null : getPoolCostInfo(); PoolManagerPoolUpMessage poolManagerMessage = new PoolManagerPoolUpMessage(_poolName, _serialId, _poolMode, info); if( _logPoolMonitor.isDebugEnabled() ) { _logPoolMonitor.debug(_poolName + " - sending poolUpMessage (mode/seialId): " + _poolMode + " / " + _serialId); } poolManagerMessage.setTagMap( _tags ) ; poolManagerMessage.setHsmInstances(new TreeSet<String>(_hsmSet.getHsmInstances())); poolManagerMessage.setMessage(_poolStatusMessage); poolManagerMessage.setCode(_poolStatusCode); return new CellMessage( new CellPath(_poolManagerName), poolManagerMessage ) ; } private void send(CellMessage msg) { try { sendMessage(msg); } catch (Exception exc){ esay("Exception sending ping message " + exc); esay(exc); } } } private PoolCostInfo getPoolCostInfo() { PoolCostInfo info = new PoolCostInfo(_poolName); info.setSpaceUsage(_repository.getTotalSpace(), _repository .getFreeSpace(), _repository.getPreciousSpace(), _sweeper .getRemovableSpace(), _sweeper.getLRUSeconds()); info.getSpaceInfo().setParameter(_breakEven, _gap); info.setQueueSizes(_ioQueue.getActiveJobs(), _ioQueue .getMaxActiveJobs(), _ioQueue.getQueueSize(), _storageHandler .getFetchScheduler().getActiveJobs(), _suppressHsmLoad ? 0 : _storageHandler.getFetchScheduler().getMaxActiveJobs(), _storageHandler.getFetchScheduler().getQueueSize(), _storageHandler.getStoreScheduler().getActiveJobs(), _suppressHsmLoad ? 0 : _storageHandler.getStoreScheduler() .getMaxActiveJobs(), _storageHandler .getStoreScheduler().getQueueSize() ); IoQueueManager manager = (IoQueueManager) _ioQueue; if (manager.isConfigured()) { for (Iterator it = manager.scheduler(); it.hasNext();) { JobScheduler js = (JobScheduler) it.next(); info.addExtendedMoverQueueSizes(js.getSchedulerName(), js .getActiveJobs(), js.getMaxActiveJobs(), js .getQueueSize()); } } info.setP2pClientQueueSizes(_p2pClient.getActiveJobs(), _p2pClient .getMaxActiveJobs(), _p2pClient.getQueueSize()); if (_p2pMode == P2P_SEPARATED) { info.setP2pServerQueueSizes(_p2pQueue.getActiveJobs(), _p2pQueue .getMaxActiveJobs(), _p2pQueue.getQueueSize()); } return info; } // ////////////////////////////////////////////////////////// // // Check cost // public String hh_set_breakeven = "<breakEven> # free and recovable space"; public String ac_set_breakeven_$_0_1(Args args) { if (args.argc() > 0) _breakEven = Double.parseDouble(args.argv(0)); return "BreakEven = " + _breakEven; } public String hh_get_cost = " [filesize] # get space and performance cost"; public String ac_get_cost_$_0_1(Args args) { return "DEPRICATED # cost now solely calculated in PoolManager"; /* * long filesize = 0 ; if( args.argc() > 0 )filesize = * Long.parseLong(args.argv(0)); * * PoolCheckCostMessage m = new PoolCheckCostMessage( * _nucleus.getCellName() , filesize ) ; * * checkCost( m ) ; return m.toString() ; */ } private double _breakEven = 250.0; /* * private CostCalculationEngine _costCalculationEngine = new * CostCalculationEngine("V5") ; * * private void checkCost( PoolCostCheckable poolMessage ) { * * CostCalculatable cost = _costCalculationEngine.getCostCalculatable( * getPoolCostInfo() ) ; * * cost.recalculate( poolMessage.getFilesize() ) ; * * * if( _simSpaceCost > (double)(-1.0) ){ * * poolMessage.setSpaceCost( _simSpaceCost ) ; * * }else if( ! _isPermanent ){ * * poolMessage.setSpaceCost( cost.getSpaceCost() ) ; * * }else{ * * poolMessage.setSpaceCost( (double)200000000.0 ); * } * * if( _simCpuCost > (double) (-1.0)) * * poolMessage.setPerformanceCost( _simCpuCost ) ; * * * else * * poolMessage.setPerformanceCost( cost.getSpaceCost() ); * * poolMessage.setSucceeded(); say("checking cost for * PoolCheckCostMessage["+poolMessage+"]"); } * * */ private synchronized void removeFiles(PoolRemoveFilesMessage poolMessage) { String[] fileList = poolMessage.getFiles(); int counter = 0; for (int i = 0; i < fileList.length; i++) { synchronized (_repository) { try { String pnfsIdString = fileList[i]; if ((pnfsIdString == null) || (pnfsIdString.length() == 0)) { esay("removeFiles : invalid syntax in remove filespec >" + pnfsIdString + "<"); continue; } PnfsId pnfsId = new PnfsId(fileList[i]); CacheRepositoryEntry entry = _repository.getEntry(pnfsId); if ((!_cleanPreciousFiles) && (_lfsMode == LFS_NONE) && (entry.isPrecious())) { counter++; say("removeFiles : File " + fileList[i] + " kept. (precious)"); } else if (!_repository.removeEntry(_repository .getEntry(pnfsId))) { // // the entry couldn't be removed because the // file is still in an unstable phase. // counter++; say("removeFiles : File " + fileList[i] + " kept. (locked)"); } else { say("removeFiles : File " + fileList[i] + " deleted."); fileList[i] = null; } } catch (FileNotInCacheException fce) { esay("removeFiles : File " + fileList[i] + " delete CE : " + fce.getMessage()); fileList[i] = null; // let them remove it } catch (CacheException ce) { counter++; say("removeFiles : File " + fileList[i] + " kept. CE : " + ce.getMessage()); } } } if (counter > 0) { String[] replyList = new String[counter]; for (int i = 0, j = 0; i < fileList.length; i++) if (fileList[i] != null) replyList[j++] = fileList[i]; poolMessage.setFailed(1, replyList); } else { poolMessage.setSucceeded(); } } // ///////////////////////////////////////////////// // // the hybrid inventory part // private class HybridInventory implements Runnable { private boolean _activate = true; public HybridInventory(boolean activate) { _activate = activate; _nucleus.newThread(this, "HybridInventory").start(); } public void run() { _hybridCurrent = 0; try { Iterator pnfsids = _repository.pnfsids(); while (pnfsids.hasNext() && !Thread.interrupted()) { PnfsId pnfsid = (PnfsId) pnfsids.next(); _hybridCurrent++; if (_activate) _pnfs.addCacheLocation(pnfsid.toString()); else _pnfs.clearCacheLocation(pnfsid.toString()); } } catch (Exception ce) { esay(ce); } synchronized (_hybridInventoryLock) { _hybridInventoryActive = false; } } } public String hh_pnfs_register = " # add entry of all files into pnfs"; public String hh_pnfs_unregister = " # remove entry of all files from pnfs"; public String ac_pnfs_register(Args args) throws Exception { synchronized (_hybridInventoryLock) { if (_hybridInventoryActive) throw new IllegalArgumentException( "Hybrid inventory still active"); _hybridInventoryActive = true; new HybridInventory(true); } return ""; } public String ac_pnfs_unregister(Args args) throws Exception { synchronized (_hybridInventoryLock) { if (_hybridInventoryActive) throw new IllegalArgumentException( "Hybrid inventory still active"); _hybridInventoryActive = true; new HybridInventory(false); } return ""; } public String hh_run_hybrid_inventory = " [-destroy]"; public String ac_run_hybrid_inventory(Args args) throws Exception { synchronized (_hybridInventoryLock) { if (_hybridInventoryActive) throw new IllegalArgumentException( "Hybrid inventory still active"); _hybridInventoryActive = true; new HybridInventory(args.getOpt("destroy") == null); } return ""; } // ////////////////////////////////////////////////////////////////////////////////// // // the interpreter set/get functions // public String hh_pf = "<pnfsId>"; public String ac_pf_$_1(Args args) throws Exception { PnfsId pnfsId = new PnfsId(args.argv(0)); PnfsMapPathMessage info = new PnfsMapPathMessage(pnfsId); CellPath path = new CellPath("PnfsManager"); say("Sending : " + info); CellMessage m = sendAndWait(new CellMessage(path, info), 10000); say("Reply arrived : " + m); if (m == null) throw new Exception("No reply from PnfsManager"); info = ((PnfsMapPathMessage) m.getMessageObject()); if (info.getReturnCode() != 0) { Object o = info.getErrorObject(); if (o instanceof Exception) throw (Exception) o; else throw new Exception(o.toString()); } return info.getGlobalPath(); } public String hh_set_replication = "off|on|<mgr>,<host>,<destMode>"; public String ac_set_replication_$_1(Args args) { String mode = args.argv(0); _replicationHandler.init(mode); return _replicationHandler.toString(); } public String hh_pool_inventory = "DEBUG ONLY"; public String ac_pool_inventory(Args args) throws Exception { final StringBuffer sb = new StringBuffer(); Logable l = new Logable() { public void log(String msg) { _logClass.log(msg); }; public void elog(String msg) { sb.append(msg).append("\n"); _logClass.elog(msg); } public void plog(String msg) { sb.append(msg).append("\n"); _logClass.plog(msg); } }; _repository.runInventory(l, _pnfs, _recoveryFlags); return sb.toString(); } public String hh_pool_suppress_hsmload = "on|off"; public String ac_pool_suppress_hsmload_$_1(Args args) { String mode = args.argv(0); if (mode.equals("on")) { _suppressHsmLoad = true; } else if (mode.equals("off")) { _suppressHsmLoad = false; } else throw new IllegalArgumentException( "Illegal syntax : pool suppress hsmload on|off"); return "hsm load suppression swithed : " + (_suppressHsmLoad ? "on" : "off"); } public String hh_movermap_define = "<protocol>-<major> <moverClassName>"; public String hh_movermap_undefine = "<protocol>-<major>"; public String hh_movermap_ls = ""; public String ac_movermap_define_$_2(Args args) throws Exception { _moverHash.put(args.argv(0), Class.forName(args.argv(1))); return ""; } public String ac_movermap_undefine_$_1(Args args) throws Exception { _moverHash.remove(args.argv(0)); return ""; } public String ac_movermap_ls(Args args) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Class<?>> entry: _moverHash.entrySet()) { sb.append(entry.getKey()).append(" -> ").append( entry.getValue().getName()).append("\n"); } return sb.toString(); } public String hh_pool_lfs = "none|precious|volatile # FOR DEBUG ONLY"; public String ac_pool_lfs_$_1(Args args) throws CommandSyntaxException { String mode = args.argv(0); if (mode.equals("none")) { _lfsMode = LFS_NONE; } else if (mode.equals("precious")) { _lfsMode = LFS_PRECIOUS; } else if (mode.equals("volatile")) { _lfsMode = LFS_VOLATILE; } else { throw new CommandSyntaxException("Not Found : ", "Usage : pool lfs none|precious|volatile"); } return ""; } public String hh_set_duplicate_request = "none|ignore|refresh"; public String ac_set_duplicate_request_$_1(Args args) throws CommandSyntaxException { String mode = args.argv(0); if (mode.equals("none")) { _dupRequest = DUP_REQ_NONE; } else if (mode.equals("ignore")) { _dupRequest = DUP_REQ_IGNORE; } else if (mode.equals("refresh")) { _dupRequest = DUP_REQ_REFRESH; } else { throw new CommandSyntaxException("Not Found : ", "Usage : pool duplicate request none|ignore|refresh"); } return ""; } public String hh_set_p2p = "integrated|separated"; public String ac_set_p2p_$_1(Args args) throws CommandSyntaxException { String mode = args.argv(0); if (mode.equals("integrated")) { _p2pMode = P2P_INTEGRATED; } else if (mode.equals("separated")) { _p2pMode = P2P_SEPARATED; } else { throw new CommandSyntaxException("Not Found : ", "Usage : set p2p ntegrated|separated"); } return ""; } public String hh_pool_disablemode = "strict|fuzzy # DEPRICATED, use pool disable [options]"; public String ac_pool_disablemode_$_1(Args args) { return "# DEPRICATED, use pool disable [options]"; } public String fh_pool_disable = " pool disable [options] [ <errorCode> [<errorMessage>]]\n" + " OPTIONS :\n" + " -fetch # disallows fetch (transfer to client)\n" + " -stage # disallows staging (from HSM)\n" + " -store # disallows store (transfer from client)\n" + " -p2p-client\n" + " -rdonly # := store,stage,p2p-client\n" + " -strict # := disallows everything\n"; public String hh_pool_disable = "[options] [<errorCode> [<errorMessage>]] # suspend sending 'up messages'"; public String ac_pool_disable_$_0_2(Args args) { int rc = args.argc() > 0 ? Integer.parseInt(args.argv(0)) : 1; String rm = args.argc() > 1 ? args.argv(1) : "Operator intervention"; int modeBits = PoolV2Mode.DISABLED; if (args.getOpt("strict") != null) modeBits |= PoolV2Mode.DISABLED_STRICT; if (args.getOpt("stage") != null) modeBits |= PoolV2Mode.DISABLED_STAGE; if (args.getOpt("fetch") != null) modeBits |= PoolV2Mode.DISABLED_FETCH; if (args.getOpt("store") != null) modeBits |= PoolV2Mode.DISABLED_STORE; if (args.getOpt("p2p-client") != null) modeBits |= PoolV2Mode.DISABLED_P2P_CLIENT; if (args.getOpt("p2p-server") != null) modeBits |= PoolV2Mode.DISABLED_P2P_SERVER; if (args.getOpt("rdonly") != null) modeBits |= PoolV2Mode.DISABLED_RDONLY; disablePool(modeBits, rc, rm); return "Pool " + _poolName + " " + _poolMode; } public String hh_pool_enable = " # resume sending up messages'"; public String ac_pool_enable(Args args) { enablePool(); return "Pool " + _poolName + " enabled"; } public String hh_set_max_movers = "!!! Please use 'mover|st|rh set max active <jobs>'"; public String ac_set_max_movers_$_1(Args args) throws IllegalArgumentException { int num = Integer.parseInt(args.argv(0)); if ((num < 0) || (num > 10000)) throw new IllegalArgumentException("Not in range (0...10000)"); return "Please use 'mover|st|rh set max active <jobs>'"; } public String hh_set_gap = "<always removable gap>/bytes"; public String ac_set_gap_$_1(Args args) { _gap = Long.parseLong(args.argv(0)); return "Gap set to " + _gap; } public String hh_set_report_remove = "on|off"; public String ac_set_report_remove_$_1(Args args) throws CommandSyntaxException { String onoff = args.argv(0); if (onoff.equals("on")) _reportOnRemovals = true; else if (onoff.equals("off")) _reportOnRemovals = false; else throw new CommandSyntaxException("Invalid value : " + onoff); return ""; } public String hh_crash = "disabled|shutdown|exception"; public String ac_crash_$_0_1(Args args) throws IllegalArgumentException { if (args.argc() < 1) { return "Crash is " + (_crashEnabled ? _crashType : "disabled"); } else if (args.argv(0).equals("shutdown")) { _crashEnabled = true; _crashType = "shutdown"; } else if (args.argv(0).equals("exception")) { _crashEnabled = true; _crashType = "exception"; } else if (args.argv(0).equals("disabled")) { _crashEnabled = false; } else throw new IllegalArgumentException( "crash disabled|shutdown|exception"); return "Crash is " + (_crashEnabled ? _crashType : "disabled"); } public String hh_set_sticky = "allowed|denied"; public String ac_set_sticky_$_0_1(Args args) { if (args.argc() > 0) { String mode = args.argv(0); if (mode.equals("allowed")) { _allowSticky = true; } else if (mode.equals("denied")) { _allowSticky = false; } else throw new IllegalArgumentException("set sticky allowed|denied"); } _storageHandler.setStickyAllowed(_allowSticky); return "Sticky Bit " + (_allowSticky ? "allowed" : "denied"); } public String hh_set_max_diskspace = "<space>[<unit>] # unit = k|m|g"; public String ac_set_max_diskspace_$_1(Args args) { long maxDisk = UnitInteger.parseUnitLong(args.argv(0)); _repository.setTotalSpace(maxDisk); say("set maximum diskspace =" + UnitInteger.toUnitString(maxDisk)); return ""; } public String hh_set_cleaning_interval = "<interval/sec>"; public String ac_set_cleaning_interval_$_1(Args args) { _cleaningInterval = Integer.parseInt(args.argv(0)); say("_cleaningInterval=" + _cleaningInterval); return ""; } public String hh_set_flushing_interval = "DEPRECATED (use flush set interval <time/sec>)"; public String ac_set_flushing_interval_$_1(Args args) { return "DEPRECATED (use flush set interval <time/sec>)"; } public String hh_flush_class = "<hsm> <storageClass> [-count=<count>]"; public String ac_flush_class_$_2(Args args) { String tmp = args.getOpt("count"); int count = (tmp == null) || (tmp.equals("")) ? 0 : Integer .parseInt(tmp); long id = _flushingThread.flushStorageClass(args.argv(0), args.argv(1), count); return "Flush Initiated (id=" + id + ")"; } public String hh_flush_pnfsid = "<pnfsid> # flushs a single pnfsid"; public String ac_flush_pnfsid_$_1(Args args) throws Exception { CacheRepositoryEntry entry = _repository.getEntry(new PnfsId(args .argv(0))); _storageHandler.store(entry, null); return "Flush Initiated"; } /* * public String hh_mover_set_attr = "default|*|<moverId> <attrKey> * <attrValue>" ; public String ac_mover_set_attr_$_3( Args args )throws * Exception { String moverId = args.argv(0) ; String key = args.argv(1) ; * String value = args.argv(2) ; * * if( moverId.equals("default") ){ _moverAttributes.put( key , value ) ; * return "" ; }else if( moverId.equals("*") ){ StringBuffer sb = new * StringBuffer() ; synchronized( _ioMovers ){ Iterator i = * _ioMovers.values().iterator() ; while( i.hasNext() ){ RepositoryIoHandler * h = (RepositoryIoHandler)i.next() ; try{ h.setAttribute( key , value ) ; * sb.append( ""+h.getId()+" OK\n" ) ; }catch(Exception ee ){ sb.append( * ""+h.getId()+" ERROR : "+ee.getMessage()+"\n" ) ; } } } return * sb.toString() ; }else{ Integer id = new Integer(moverId) ; synchronized( * _ioMovers ){ RepositoryIoHandler h = * (RepositoryIoHandler)_ioMovers.get(id) ; h.setAttribute( key , value ) ; } * return "" ; } } */ public String hh_mover_set_max_active = "<maxActiveIoMovers> -queue=<queueName>"; public String hh_mover_queue_ls = ""; public String hh_mover_ls = "[-binary [jobId] ]"; public String hh_mover_remove = "<jobId>"; public String hh_mover_kill = "<jobId>"; public String hh_p2p_set_max_active = "<maxActiveIoMovers>"; public String hh_p2p_ls = "[-binary [jobId] ]"; public String hh_p2p_remove = "<jobId>"; public String hh_p2p_kill = "<jobId>"; public String ac_mover_set_max_active_$_1(Args args) throws Exception { String queueName = args.getOpt("queue"); IoQueueManager ioManager = (IoQueueManager) _ioQueue; if (queueName == null) return mover_set_max_active(ioManager.getDefaultScheduler(), args); JobScheduler js = ioManager.getSchedulerByName(queueName); if (js == null) return "Not found : " + queueName; return mover_set_max_active(js, args); } public String ac_p2p_set_max_active_$_1(Args args) throws Exception { return mover_set_max_active(_p2pQueue, args); } private String mover_set_max_active(JobScheduler js, Args args) throws Exception { int active = Integer.parseInt(args.argv(0)); if (active < 0) throw new IllegalArgumentException("<maxActiveMovers> must be >= 0"); js.setMaxActiveJobs(active); return "Max Active Io Movers set to " + active; } public Object ac_mover_queue_ls_$_0_1(Args args) throws Exception { StringBuffer sb = new StringBuffer(); IoQueueManager manager = (IoQueueManager) _ioQueue; if (args.getOpt("l") != null) { for (Iterator it = manager.scheduler(); it.hasNext();) { JobScheduler js = (JobScheduler) it.next(); sb.append(js.getSchedulerName()).append(" ").append( js.getActiveJobs()).append(" ").append( js.getMaxActiveJobs()).append(" ").append( js.getQueueSize()).append("\n"); } } else { for (Iterator it = manager.scheduler(); it.hasNext();) { sb.append(((JobScheduler) it.next()).getSchedulerName()) .append("\n"); } } return sb.toString(); } public Object ac_mover_ls_$_0_1(Args args) throws Exception { String queueName = args.getOpt("queue"); if (queueName == null) return mover_ls(_ioQueue, args); if (queueName.length() == 0) { IoQueueManager manager = (IoQueueManager) _ioQueue; StringBuffer sb = new StringBuffer(); for (Iterator it = manager.scheduler(); it.hasNext();) { JobScheduler js = (JobScheduler) it.next(); sb.append("[").append(js.getSchedulerName()).append("]\n"); sb.append(mover_ls(js, args).toString()); } return sb.toString(); } IoQueueManager manager = (IoQueueManager) _ioQueue; JobScheduler js = manager.getSchedulerByName(queueName); if (js == null) throw new NoSuchElementException(queueName); return mover_ls(js, args); } public Object ac_p2p_ls_$_0_1(Args args) throws Exception { return mover_ls(_p2pQueue, args); } /* * private Object mover_ls( IoQueueManager queueManager , int id , boolean * binary ){ Iterator queues = queueManager.scheduler() ; * * if( binary ){ if( id > 0 ){ ArrayList list = new ArrayList() ; while( * queues.hasNext() ){ list.addAll( * ((JobScheduler)queues.next()).getJobInfos() ) ; } return list.toArray( * new IoJobInfo[0] ) ; }else{ return queueManager.getJobInfo(id) ; } }else{ * StringBuffer sb = new StringBuffer() ; while( queues.hasNext() ){ * JobScheduler js = (JobScheduler)queues.next() ; js.printJobQueue(sb); } * return sb.toString() ; } } */ private Object mover_ls(JobScheduler js, Args args) throws Exception { boolean binary = args.getOpt("binary") != null; try { if (binary) { if (args.argc() > 0) { return js.getJobInfo(Integer.parseInt(args.argv(0))); } else { List<JobInfo> list = js.getJobInfos(); return list.toArray(new IoJobInfo[list.size()]); } } else { return js.printJobQueue(null).toString(); } } catch (Exception ee) { esay(ee); throw ee; } } public String ac_mover_remove_$_1(Args args) throws Exception { return mover_remove(_ioQueue, args); } public String ac_p2p_remove_$_1(Args args) throws Exception { return mover_remove(_p2pQueue, args); } private String mover_remove(JobScheduler js, Args args) throws Exception { int id = Integer.parseInt(args.argv(0)); js.remove(id); return "Removed"; } public String ac_mover_kill_$_1(Args args) throws Exception { return mover_kill(_ioQueue, args); } public String ac_p2p_kill_$_1(Args args) throws Exception { return mover_kill(_p2pQueue, args); } private void mover_kill(int id) throws Exception { mover_kill(_ioQueue, id); } private String mover_kill(JobScheduler js, Args args) throws Exception { int id = Integer.parseInt(args.argv(0)); mover_kill(js, id); return "Kill initialized"; } private void mover_kill(JobScheduler js, int id) throws Exception { js.kill(id); } // //////////////////////////////////////////////////// // // queue stuff // public String hh_set_heartbeat = "<heartbeatInterval/sec>"; public String ac_set_heartbeat_$_0_1(Args args) throws Exception { if (args.argc() > 0) { _pingThread.setHeartbeat(Integer.parseInt(args.argv(0))); } return "Heartbeat at " + (_pingThread.getHeartbeat()); } public String fh_update = " update [-force] [-perm] !!! DEPRECATED \n" + " sends relevant data to the PoolManager if this information has been\n" + " changed recently.\n\n" + " -force : forces the cell to send the information regardless whether it\n" + " changed or not.\n" + " -perm : writes the current parameter setup back to the setupFile\n"; public String hh_update = "[-force] [-perm] !!! DEPRECATED"; public String ac_update(Args args) throws Exception { boolean forced = args.getOpt("force") != null; _pingThread.sendPoolManagerMessage(forced); if (args.getOpt("perm") != null) { dumpSetup(); } return ""; } public String hh_save = "[-sc=<setupController>|none] # saves setup to disk or SC"; public String ac_save(Args args) throws Exception { String setupManager = args.getOpt("sc"); if (_setupManager == null) { if ((setupManager != null) && setupManager.equals("")) throw new IllegalArgumentException( "setupManager needs to be specified"); } else { if ((setupManager == null) || setupManager.equals("")) { setupManager = _setupManager; } } if ((setupManager != null) && !setupManager.equals("none")) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); dumpSetup(pw); SetupInfoMessage info = new SetupInfoMessage("put", this .getCellName(), "pool", sw.toString()); sendMessage(new CellMessage(new CellPath(setupManager), info)); } catch (Exception ee) { esay("Problem sending setup to >" + setupManager + "< : " + ee); throw ee; } } dumpSetup(); return ""; } // // } // end of MultiProtocolPool
true
false
null
null
diff --git a/tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/RequestParameterTests.java b/tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/RequestParameterTests.java index e8bd61d9e..34d47b4bd 100644 --- a/tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/RequestParameterTests.java +++ b/tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/RequestParameterTests.java @@ -1,59 +1,62 @@ // Copyright 2010, 2011 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.integration.app1; import org.apache.tapestry5.integration.TapestryCoreTestCase; import org.testng.annotations.Test; public class RequestParameterTests extends TapestryCoreTestCase { @Test public void successful_use_of_query_parameter_annotation() { openLinks("RequestParameter Annotation Demo", "Working Link"); assertText("id=current", "97"); } @Test public void null_value_when_not_allowed() { openLinks("RequestParameter Annotation Demo", "Null Link"); assertTextPresent( - "Unable process query parameter 'gnip' as parameter #1 of event handler method void onFrob(int) (in class org.apache.tapestry5.integration.app1.pages.RequestParameterDemo)", + "Unable process query parameter 'gnip' as parameter #1 of event handler method", + "org.apache.tapestry5.integration.app1.pages.RequestParameterDemo.onFrob(int)", "The value for query parameter 'gnip' was blank, but a non-blank value is needed."); } @Test public void null_for_primitive_when_allowed() { openLinks("RequestParameter Annotation Demo", "Null Allowed Link"); assertTextPresent( - "Unable process query parameter 'gnip' as parameter #1 of event handler method void onFrobNullAllowed(int) (in class org.apache.tapestry5.integration.app1.pages.RequestParameterDemo)", + "Unable process query parameter 'gnip' as parameter #1 of event handler method", + "org.apache.tapestry5.integration.app1.pages.RequestParameterDemo.onFrobNullAllowed(int)", "Query parameter 'gnip' evaluates to null, but the event method parameter is type int, a primitive."); } @Test public void type_mismatch_for_method_parameter() { openLinks("RequestParameter Annotation Demo", "Broken Link"); assertTextPresent( - "Unable process query parameter 'gnip' as parameter #1 of event handler method void onFrob(int) (in class org.apache.tapestry5.integration.app1.pages.RequestParameterDemo)", + "Unable process query parameter 'gnip' as parameter #1 of event handler method ", + "org.apache.tapestry5.integration.app1.pages.RequestParameterDemo.onFrob(int)", "Coercion of frodo to type java.lang.Integer"); } }
false
false
null
null
diff --git a/src/info/tregmine/commands/ActionCommand.java b/src/info/tregmine/commands/ActionCommand.java index a43691a..54d7cb3 100644 --- a/src/info/tregmine/commands/ActionCommand.java +++ b/src/info/tregmine/commands/ActionCommand.java @@ -1,51 +1,51 @@ package info.tregmine.commands; import static org.bukkit.ChatColor.*; import org.bukkit.Server; import org.bukkit.entity.Player; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; public class ActionCommand extends AbstractCommand { public ActionCommand(Tregmine tregmine) { super(tregmine, "action"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (args.length == 0) { return false; } Server server = player.getServer(); String channel = player.getChatChannel(); String msg = argsToMessage(args); Player[] players = server.getOnlinePlayers(); for (Player tp : players) { TregminePlayer to = tregmine.getPlayer(tp); if (!channel.equals(to.getChatChannel())) { continue; } - to.sendMessage("* " + player.getChatName() + WHITE + msg); + to.sendMessage("* " + player.getChatName() + " " + WHITE + msg); } return true; } } diff --git a/src/info/tregmine/commands/SayCommand.java b/src/info/tregmine/commands/SayCommand.java index 91551cc..1126645 100644 --- a/src/info/tregmine/commands/SayCommand.java +++ b/src/info/tregmine/commands/SayCommand.java @@ -1,63 +1,64 @@ package info.tregmine.commands; import static org.bukkit.ChatColor.*; import org.bukkit.Server; import org.bukkit.entity.Player; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; public class SayCommand extends AbstractCommand { public SayCommand(Tregmine tregmine) { super(tregmine, "say"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { - Server server = player.getServer(); - String msg = argsToMessage(args); + if(player.isAdmin()){ + Server server = player.getServer(); + String msg = argsToMessage(args); - server.broadcastMessage("<" + RED + "GOD" + WHITE + "> " + LIGHT_PURPLE - + msg); + server.broadcastMessage("<" + RED + "GOD" + WHITE + "> " + LIGHT_PURPLE + + msg); - LOGGER.info(player.getName() + ": <GOD> " + msg); + LOGGER.info(player.getName() + ": <GOD> " + msg); - Player[] players = server.getOnlinePlayers(); - for (Player p : players) { - TregminePlayer current = tregmine.getPlayer((p.getName())); - if (current.isAdmin()) { - current.sendMessage(DARK_AQUA + "/say used by: " - + player.getChatName()); + Player[] players = server.getOnlinePlayers(); + for (Player p : players) { + TregminePlayer current = tregmine.getPlayer((p.getName())); + if (current.isAdmin()) { + current.sendMessage(DARK_AQUA + "/say used by: " + + player.getChatName()); + } } } - return true; } @Override public boolean handleOther(Server server, String[] args) { String msg = argsToMessage(args); server.broadcastMessage("<" + BLUE + "GOD" + WHITE + "> " + LIGHT_PURPLE + msg); LOGGER.info("CONSOLE: <GOD> " + msg); return true; } }
false
false
null
null
diff --git a/app/models/events/AddCauseEvent.java b/app/models/events/AddCauseEvent.java index 6aafdca..b7e3bdd 100644 --- a/app/models/events/AddCauseEvent.java +++ b/app/models/events/AddCauseEvent.java @@ -1,47 +1,47 @@ /* * Copyright (C) 2011 by Eero Laukkanen, Risto Virtanen, Jussi Patana, Juha Viljanen, * Joona Koistinen, Pekka Rihtniemi, Mika Kekäle, Roope Hovi, Mikko Valjus, * Timo Lehtinen, Jaakko Harjuhahto * * 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 models.events; import models.Cause; public class AddCauseEvent extends Event { public final String text; public final String causeFrom; public final String causeTo; public final String creatorId; public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); - this.text = cause.name.replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("&", "&amp;"); + this.text = cause.name.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); } }
true
true
public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); this.text = cause.name.replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("&", "&amp;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); }
public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); this.text = cause.name.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); }
diff --git a/apps/wget/src/net/crud/wget/WgetTask.java b/apps/wget/src/net/crud/wget/WgetTask.java index ca70ab0..ca3f5a4 100644 --- a/apps/wget/src/net/crud/wget/WgetTask.java +++ b/apps/wget/src/net/crud/wget/WgetTask.java @@ -1,117 +1,118 @@ package net.crud.wget; import java.io.BufferedReader; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.os.AsyncTask; import android.widget.Button; import android.widget.ScrollView; import android.widget.TextView; public class WgetTask extends AsyncTask<String, String, Boolean> { TextView mLogTarget; ScrollView mScroller; Button mRunButton; Button mKillButton; int mPid; Method mCreateSubprocess; Method mWaitFor; WgetTask(TextView tv, ScrollView sc, Button run, Button kill) { tv.setText(""); mLogTarget = tv; mScroller = sc; mPid = -1; } protected Boolean doInBackground(String... command) { try { String one_line; String working_dir = "/sdcard/wget"; // Use a working directory on the sdcard File dir = new File(working_dir); dir.mkdir(); // Inspired by http://remotedroid.net/blog/2009/04/13/running-native-code-in-android/ Class<?> execClass = Class.forName("android.os.Exec"); Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class); mCreateSubprocess = createSubprocess; mWaitFor = execClass.getMethod("waitFor", int.class); // Executes the command. // NOTE: createSubprocess() is asynchronous. + // 'exec' is key here, otherwise killing this pid will only kill the shell, and wget will go background. int[] pids = new int[1]; FileDescriptor fd = (FileDescriptor)createSubprocess.invoke( - null, "/system/bin/sh", "-c", "cd " + working_dir + ";" + command[0], pids); + null, "/system/bin/sh", "-c", "cd " + working_dir + "; exec " + command[0], pids); mPid = pids[0]; // Reads stdout. // NOTE: You can write to stdin of the command using new FileOutputStream(fd). FileInputStream in = new FileInputStream(fd); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); //Old-style, has obnoxious buffering behaviour, don't know why. //Process proc = Runtime.getRuntime().exec(command[0], null, dir); //DataInputStream in = new DataInputStream(proc.getInputStream()); //BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((one_line = reader.readLine()) != null) { publishProgress(one_line + "\n"); } } catch (IOException e1) { // Hacky: When the input fd is closed, instead of returning null from the next readLine() // call, it seems that IOException is thrown. So we ignore it. } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage()); } catch (SecurityException e) { throw new RuntimeException(e.getMessage()); } catch (NoSuchMethodException e) { throw new RuntimeException(e.getMessage()); } catch (IllegalArgumentException e) { throw new RuntimeException(e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage()); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage()); } return true; } // Runs on UI thread protected void killWget() { try { - mCreateSubprocess.invoke( - null, "/system/bin/sh", "-c", "kill -9 " + mPid, null); - publishProgress("Killed by user"); + mCreateSubprocess.invoke(null, "/system/bin/sh", "-c", "kill -2 " + mPid, null); + + publishProgress("\n\nProcess " + mPid + " killed by user\n\n"); // If we catch an exception trying to run kill, don't worry about it much. // Wget will die on its own, eventually (probably) } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } protected void onProgressUpdate(String... progress) { this.mLogTarget.append(progress[0]); final ScrollView sc = this.mScroller; // Put this on the UI thread queue so the text view re-renders before we try to scroll. // Otherwise we fire too soon and there is no additional space to scroll to! sc.post(new Runnable() { public void run() { sc.smoothScrollBy(0, 1000); // Arbitrary number greater than line height } }); } protected void onPostExecute(Integer result) { } }
false
false
null
null
diff --git a/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java b/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java index f14301ae..3973377c 100644 --- a/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java +++ b/src/gov/nih/nci/rembrandt/web/struts/action/GPProcessAction.java @@ -1,494 +1,494 @@ package gov.nih.nci.rembrandt.web.struts.action; import gov.nih.nci.caintegrator.enumeration.FindingStatus; import gov.nih.nci.caintegrator.service.task.GPTask; import gov.nih.nci.rembrandt.cache.RembrandtPresentationTierCache; import gov.nih.nci.rembrandt.web.factory.ApplicationFactory; import gov.nih.nci.rembrandt.web.struts.form.GpProcessForm; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.util.LabelValueBean; import org.genepattern.client.GPClient; import org.genepattern.util.StringUtils; import org.genepattern.visualizer.RunVisualizerConstants; import org.genepattern.webservice.AnalysisWebServiceProxy; import org.genepattern.webservice.JobResult; import org.genepattern.webservice.Parameter; import org.genepattern.webservice.TaskIntegratorProxy; import org.genepattern.webservice.WebServiceException; /** * caIntegrator License * * Copyright 2001-2005 Science Applications International Corporation ("SAIC"). * The software subject to this notice and license includes both human readable source code form and machine readable, * binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with * the National Cancer Institute ("NCI") by NCI employees and employees of SAIC. * To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States * Code, section 105. * This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an * entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control" * for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity, * whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) * beneficial ownership of such entity. * This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive, * worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights * in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly * display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed * to and by third parties the caIntegrator Software and any modifications and derivative works thereof; * and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such * rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting * or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no * charge to You. * 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions * and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce * the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This * product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user * documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments * normally appear. * 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and * "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any * trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with * the terms of this License. * 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and * into any third party proprietary programs. However, if You incorporate the Software into third party proprietary * programs, You agree that You are solely responsible for obtaining any permission from such third parties required to * incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including * without limitation Your end-users, of their obligation to secure any required permissions from such third parties * before incorporating the Software into such third party proprietary software programs. In the event that You fail * to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such permissions. * 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and * to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses * of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction, * and distribution of the Work otherwise complies with the conditions stated in this License. * 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES 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. * */ public class GPProcessAction extends DispatchAction { private static Logger logger = Logger.getLogger(GPProcessAction.class); private static String HMV = "Heat Map Viewer"; private static String HC = "Hierarchical Clustering"; private static String KNN = "K-Nearest Neighbors"; private static String CMS = "Comparative Marker Selection"; private static String HEAT_MAP_VIEW = "HeatMapViewer"; private static String HC_PIPELINE = "HC.pipeline"; private static String KNN_PIPELINE = "KNN.pipeline"; private static String CMS_PIPELINE = "CMS.pipeline"; private static String GP_SERVER = "gov.nih.nci.caintegrator.gp.server"; public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { GpProcessForm gpForm = (GpProcessForm) form; processSetUp(gpForm, request); return mapping.findForward("success"); } public ActionForward startApplet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info("Entering startApplet method......."); GpProcessForm gpForm = (GpProcessForm)form; String processName = gpForm.getProcessName(); if (processName.equalsIgnoreCase(HC_PIPELINE)){ return runHCPipeline(mapping, form, request, response); } else if (processName.equalsIgnoreCase(KNN_PIPELINE)){ return runKNNPipeline(mapping, form, request, response); } else if (processName.equalsIgnoreCase(CMS_PIPELINE)){ return runCMSPipeline(mapping, form, request, response); } String jobNumber = gpForm.getJobId(); RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); GPTask gpTask = getGPTask(tempGpTaskList, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); setFileInformation(request, gpserverURL, "gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.gp_lsid", "gov.nih.nci.caintegrator.gpvisualizer.heatmapviewer.commandLine"); String fileName = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct"; request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, fileName); request.setAttribute("name", HEAT_MAP_VIEW); request.setAttribute(RunVisualizerConstants.PARAM_NAMES, "dataset"); gpForm.setJobList(getGPTaskList(tempGpTaskList)); gpForm.setProcessList(getVisualizers()); return mapping.findForward("appletViewer"); } private ActionForward runHCPipeline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info("Entering runHCPipeline......."); GpProcessForm gpForm = (GpProcessForm)form; String jobNumber = gpForm.getJobId(); GPTask gpTask = getGPTask(request, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); Parameter[] par = new Parameter[1]; String fileName = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct"; par[0] = new Parameter("VariationFiltering1.input.filename", fileName); runGenePattern(request, HC_PIPELINE, par, gpTask); return mapping.findForward("viewJob"); } private ActionForward runKNNPipeline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info("Entering runKNNPipeline......."); GpProcessForm gpForm = (GpProcessForm)form; String jobNumber = gpForm.getJobId(); GPTask gpTask = getGPTask(request, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); Parameter[] par = new Parameter[2]; String fileName1 = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct"; String fileName2 = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".cls"; par[0] = new Parameter("VariationFiltering1.input.filename", fileName1); par[1] = new Parameter("SplitDatasetTrainTest2.cls.file", fileName2); runGenePattern(request, KNN_PIPELINE, par, gpTask); return mapping.findForward("viewJob"); } private ActionForward runCMSPipeline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info("Entering runCMSPipeline......."); GpProcessForm gpForm = (GpProcessForm)form; String jobNumber = gpForm.getJobId(); GPTask gpTask = getGPTask(request, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); Parameter[] par = new Parameter[2]; String fileName1 = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".gct"; String fileName2 = gpserverURL + "gp/jobResults/" + jobNumber + "/" + gpTask.getResultName() + ".cls"; par[0] = new Parameter("VariationFiltering1.input.filename", fileName1); par[1] = new Parameter("ComparativeMarkerSelection2.cls.filename", fileName2); runGenePattern(request, CMS_PIPELINE, par, gpTask); return mapping.findForward("viewJob"); } public ActionForward hcApplet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { GpProcessForm gpForm = (GpProcessForm)form; processSetUp(gpForm, request); String jobNumber = gpForm.getJobId(); RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); GPTask gpTask = getGPTask(tempGpTaskList, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); setFileInformation(request, gpserverURL, "gov.nih.nci.caintegrator.gpvisualizer.hcpipeline.gp_lsid", "gov.nih.nci.caintegrator.gpvisualizer.hcpipeline.commandLine"); int newJobNumber = findChildJobNumber(request, Integer.parseInt(jobNumber), System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.hcpipeline.child_lsid")); if (newJobNumber == -1) return mapping.findForward("appletViewer"); String fileName = gpserverURL + "gp/jobResults/" + newJobNumber + "/" + gpTask.getResultName(); request.setAttribute("cdtFile", fileName + ".mad.cdt"); request.setAttribute("gtrFile", fileName + ".mad.gtr"); request.setAttribute("atrFile", fileName + ".mad.atr"); request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, "cdt.file,gtr.file,atr.file"); request.setAttribute("name", "HierarchicalClusteringViewer"); request.setAttribute("gp_paramNames", "cdt.file,gtr.file,atr.file"); return mapping.findForward("appletViewer"); } public ActionForward knnApplet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { GpProcessForm gpForm = (GpProcessForm)form; processSetUp(gpForm, request); String jobNumber = gpForm.getJobId(); RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); GPTask gpTask = getGPTask(tempGpTaskList, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); setFileInformation(request, gpserverURL, "gov.nih.nci.caintegrator.gpvisualizer.predictionResultsViewer.gp_lsid", "gov.nih.nci.caintegrator.gpvisualizer.predictionResultsViewer.commandLine"); int newJobNumber = findChildJobNumber(request, Integer.parseInt(jobNumber), System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.predictionResultsViewer.child_lsid")); if (newJobNumber == -1) return mapping.findForward("appletViewer"); - String fileName = gpserverURL + "gp/jobResults/" + newJobNumber + "/" + gpTask.getResultName() + "..test.0.pred.odf"; + String fileName = gpserverURL + "gp/jobResults/" + newJobNumber + "/" + gpTask.getResultName() + ".mad.test.0.pred.odf"; logger.info("datafile name = " + fileName); request.setAttribute("predictionResultsfilename", fileName); request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, "prediction.results.filename"); request.setAttribute("name", "PredictionResultsViewer"); request.setAttribute("gp_paramNames", "prediction.results.filename"); return mapping.findForward("appletViewer"); } public ActionForward cmsApplet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { GpProcessForm gpForm = (GpProcessForm)form; processSetUp(gpForm, request); String jobNumber = gpForm.getJobId(); RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); GPTask gpTask = getGPTask(tempGpTaskList, jobNumber); String gpserverURL = System.getProperty(GP_SERVER); setFileInformation(request, gpserverURL, "gov.nih.nci.caintegrator.gpvisualizer.comparativeMarkerSelectionViewer.gp_lsid", "gov.nih.nci.caintegrator.gpvisualizer.comparativeMarkerSelectionViewer.commandLine"); int newJobNumber = findChildJobNumber(request, Integer.parseInt(jobNumber), System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.comparativeMarkerSelectionViewer.one.child_lsid")); if (newJobNumber == -1) return mapping.findForward("appletViewer"); String fileName1 = gpserverURL + "gp/jobResults/" + newJobNumber + "/" + gpTask.getResultName() + ".mad.gct"; newJobNumber = findChildJobNumber(request, Integer.parseInt(jobNumber), System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.comparativeMarkerSelectionViewer.two.child_lsid")); if (newJobNumber == -1) return mapping.findForward("appletViewer"); String fileName2 = gpserverURL + "gp/jobResults/" + newJobNumber + "/" + gpTask.getResultName() + ".mad.comp.marker.odf"; request.setAttribute("comparativeMarkerSelectionDatasetFilename", fileName1); request.setAttribute("comparativeMarkerSelectionFilename", fileName2); request.setAttribute(RunVisualizerConstants.DOWNLOAD_FILES, "comparative.marker.selection.filename,dataset.filename"); request.setAttribute("name", "ComparativeMarkerSelectionViewer"); request.setAttribute("gp_paramNames", "comparative.marker.selection.filename,dataset.filename"); return mapping.findForward("appletViewer"); } private String appendString(String[] str, String token){ StringBuffer sb = new StringBuffer(); int i = 1; //str.length; for (String string : str){ sb.append(string); if (i++ != str.length){ sb.append(token); } } return sb.toString(); } private List<String> getGPTaskList(Collection collection){ List<String> jobList = new ArrayList<String>(); if (collection != null && !collection.isEmpty()){ for(Iterator i = collection.iterator();i.hasNext();) { GPTask task = (GPTask) i.next(); if (task.getStatus().equals(FindingStatus.Completed) && task.getTaskModule() == null) jobList.add(task.getJobId()); } } return jobList; } private GPTask getGPTask(Collection tempGpTaskList, String jobNumber){ GPTask gpTask = null; if (tempGpTaskList != null && !tempGpTaskList.isEmpty()){ for(Iterator i = tempGpTaskList.iterator();i.hasNext();) { GPTask task = (GPTask) i.next(); if (task.getJobId().equals(jobNumber)) gpTask = task; } } return gpTask; } private GPTask getGPTask(HttpServletRequest request, String jobNumber){ RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); GPTask gpTask = null; if (tempGpTaskList != null && !tempGpTaskList.isEmpty()){ for(Iterator i = tempGpTaskList.iterator();i.hasNext();) { GPTask task = (GPTask) i.next(); if (task.getJobId().equals(jobNumber)) gpTask = task; } } return gpTask; } private List<LabelValueBean> getVisualizers(){ List<LabelValueBean> processList = new ArrayList<LabelValueBean>(); processList.add(new LabelValueBean(HMV, HEAT_MAP_VIEW)); processList.add(new LabelValueBean(HC, HC_PIPELINE)); processList.add(new LabelValueBean(KNN, KNN_PIPELINE)); processList.add(new LabelValueBean(CMS, CMS_PIPELINE)); return processList; } private void runGenePattern(HttpServletRequest request, String moduleName, Parameter[] par, GPTask gpTask) throws Exception{ GPClient gpClient = (GPClient)request.getSession().getAttribute("genePatternServer"); int nowait = gpClient.runAnalysisNoWait(moduleName, par); String tid = String.valueOf(nowait); request.setAttribute("jobId", tid); request.setAttribute("gpStatus", "running"); GPTask task = new GPTask(tid, gpTask.getResultName(), FindingStatus.Running); task.setTaskModule(moduleName); if (moduleName.equalsIgnoreCase(HC_PIPELINE)){ task.setTaskModuleDisplayName(HC); } else if (moduleName.equalsIgnoreCase(KNN_PIPELINE)){ task.setTaskModuleDisplayName(KNN); } else if (moduleName.equalsIgnoreCase(CMS_PIPELINE)){ task.setTaskModuleDisplayName(CMS); } ApplicationFactory.getPresentationTierCache().addNonPersistableToSessionCache(request.getSession().getId(), "latestGpTask",(Serializable)task); } private void setFileInformation(HttpServletRequest request, String gpserverURL, String gp_lsid, String gp_commandLine) throws Exception{ String gpUserId = (String)request.getSession().getAttribute("gpUserId"); String password = System.getProperty("gov.nih.nci.caintegrator.gp.publicuser.password"); TaskIntegratorProxy taskIntegratorProxy = new TaskIntegratorProxy(gpserverURL, gpUserId, password, false); String lsid = System.getProperty(gp_lsid); String[] theFiles = taskIntegratorProxy.getSupportFileNames(lsid); long[] dateLongs = taskIntegratorProxy.getLastModificationTimes(lsid, theFiles); String[] dateStrings = new String[dateLongs.length]; int index = 0; for (long dateLong : dateLongs){ dateStrings[index++] = Long.toString(dateLong); } request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_DATES, appendString(dateStrings, ",")); request.setAttribute(RunVisualizerConstants.SUPPORT_FILE_NAMES, appendString(theFiles, ",")); String commandline = System.getProperty(gp_commandLine); commandline = StringUtils.htmlEncode(commandline); request.setAttribute(RunVisualizerConstants.COMMAND_LINE, commandline); request.setAttribute("gp_lsid", lsid); String gpHomeURL = (String)request.getSession().getAttribute("ticketString"); int ppp = gpHomeURL.indexOf("?"); String ticketString = gpHomeURL.substring(ppp); request.setAttribute("ticketString", ticketString); String supportFileURL = System.getProperty("gov.nih.nci.caintegrator.gpvisualizer.supportFileURL"); supportFileURL = gpserverURL + "gp/" + supportFileURL; request.setAttribute("supportFileURL", supportFileURL); request.setAttribute("goApplet", "goApplet"); } private void processSetUp(GpProcessForm gpForm, HttpServletRequest request) throws Exception { RembrandtPresentationTierCache _cacheManager = ApplicationFactory.getPresentationTierCache(); GPTask gpTask = (GPTask)_cacheManager.getNonPersistableObjectFromSessionCache( request.getSession().getId(), "latestGpTask"); if (gpTask != null){ request.setAttribute("jobId", gpTask.getJobId()); request.setAttribute("resultName", gpTask.getResultName()); request.setAttribute("jobIdSelect", gpTask.getJobId() + "_jobId"); request.setAttribute("processSelect", gpTask.getJobId() + "_process"); request.setAttribute("submitButton", gpTask.getJobId() + "_submit"); request.setAttribute("gpStatus", gpTask.getStatus().toString()); if (gpTask.getTaskModule() != null){ request.setAttribute("taskModule", gpTask.getTaskModule()); } } Collection tempGpTaskList = _cacheManager.getAllSessionGPTasks(request.getSession().getId()); gpForm.setJobList(getGPTaskList(tempGpTaskList)); gpForm.setProcessList(getVisualizers()); } private int findChildJobNumber(HttpServletRequest request, int parentJobNumber, String child_lsid){ AnalysisWebServiceProxy analysisProxy = (AnalysisWebServiceProxy)request.getSession().getAttribute("AnalysisWebServiceProxy"); if (analysisProxy == null){ return -1; } GPClient gpClient = (GPClient)request.getSession().getAttribute("genePatternServer"); try { int[] children = analysisProxy.getChildren(parentJobNumber); JobResult result = null; for (int job : children){ result = gpClient.createJobResult(job); if (result.getLSID().equalsIgnoreCase(child_lsid)){ return result.getJobNumber(); } } } catch (WebServiceException we){ logger.error("Failed to obtain child job number: " + we.getMessage()); } return -1; } }
true
false
null
null
diff --git a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java index 02508508d..ca13748b4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java @@ -1,130 +1,130 @@ /** * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.core; import java.util.ArrayList; import java.util.List; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.Spannable; import android.text.TextUtils; import android.text.style.URLSpan; import android.text.util.Linkify; import com.timsu.astrid.R; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.api.TaskAction; import com.todoroo.astrid.api.TaskDecoration; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.files.FileMetadata; import com.todoroo.astrid.files.FilesAction; import com.todoroo.astrid.notes.NotesAction; /** * Exposes {@link TaskDecoration} for phone numbers, emails, urls, etc * * @author Tim Su <[email protected]> * */ public class LinkActionExposer { private PackageManager pm; public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); - boolean hasAttachments = false; + boolean hasAttachments = FileMetadata.taskHasAttachments(taskId); if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && - !(hasAttachments = FileMetadata.taskHasAttachments(taskId))) + !hasAttachments) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; } @SuppressWarnings("nls") private TaskAction createLinkAction(Context context, long id, String url, String text) { Intent itemIntent = new Intent(Intent.ACTION_VIEW); itemIntent.setData(Uri.parse(url)); List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(itemIntent, 0); Intent actionIntent; // if options > 1, display open with... if(resolveInfoList.size() > 1) { actionIntent = Intent.createChooser(itemIntent, text); } // else show app that gets opened else if(resolveInfoList.size() == 1) { actionIntent = itemIntent; } // no intents -> no item else return null; Resources r = context.getResources(); Drawable icon; if (url.startsWith("mailto")) { icon = r.getDrawable(R.drawable.action_mail); } else if (url.startsWith("tel")) { icon = r.getDrawable(R.drawable.action_tel); } else { icon = r.getDrawable(R.drawable.action_web); } Bitmap bitmap = ((BitmapDrawable)icon).getBitmap(); if(text.length() > 15) text = text.substring(0, 12) + "..."; //$NON-NLS-1$ TaskAction action = new TaskAction(text, PendingIntent.getActivity(context, (int)id, actionIntent, 0), bitmap); return action; } }
false
true
public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); boolean hasAttachments = false; if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && !(hasAttachments = FileMetadata.taskHasAttachments(taskId))) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; }
public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); boolean hasAttachments = FileMetadata.taskHasAttachments(taskId); if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && !hasAttachments) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; }
diff --git a/src/main/java/com/p6spy/engine/proxy/ProxyFactory.java b/src/main/java/com/p6spy/engine/proxy/ProxyFactory.java index 6d04a9b47..495e1c55e 100644 --- a/src/main/java/com/p6spy/engine/proxy/ProxyFactory.java +++ b/src/main/java/com/p6spy/engine/proxy/ProxyFactory.java @@ -1,102 +1,105 @@ /* * #%L * P6Spy * %% * Copyright (C) 2013 P6Spy * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.p6spy.engine.proxy; -import net.sf.cglib.core.NamingPolicy; -import net.sf.cglib.core.Predicate; -import net.sf.cglib.proxy.Enhancer; - import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import net.sf.cglib.proxy.Enhancer; + /** * @author Quinton McCombs * @since 09/2013 */ public class ProxyFactory { + private static final String SQLITE_PACKAGE_PREFIX = "org.sqlite"; + /** * @deprecated use {@link #createProxy(Object, GenericInvocationHandler)} instead */ @Deprecated public static <T> T createProxy(final T underlying, final Class<T> notUsed, final GenericInvocationHandler<T> invocationHandler) { return createProxy(underlying, invocationHandler); } /** * Creates a proxy for the given object delegating all method calls to the invocation handler. The proxy will * implement all interfaces implemented by the object to be proxied. * * @param underlying the object to proxy * @param invocationHandler the invocation handler * @return */ + @SuppressWarnings("unchecked") public static <T> T createProxy(final T underlying, final GenericInvocationHandler<T> invocationHandler) { //noinspection unchecked - Enhancer enhancer = new Enhancer(); + final Enhancer enhancer = new Enhancer(); enhancer.setCallback(invocationHandler); enhancer.setInterfaces(getInterfaces(underlying.getClass())); // fix for the https://github.com/p6spy/p6spy/issues/188 enhancer.setClassLoader(Thread.currentThread().getContextClassLoader()); - enhancer.setNamingPolicy(ProxyNamingPolicy.INSTANCE); + + // sqlite has all the classes package protected + // => no chance to go for different package hierarchy there + if (!underlying.getClass().getPackage().getName().startsWith(SQLITE_PACKAGE_PREFIX)) { + enhancer.setNamingPolicy(ProxyNamingPolicy.INSTANCE); + } return (T) enhancer.create(); } /** * Used to determine is a given object is a Proxy created by this proxy factory. * * @param obj the object in question * @return true if it is a proxy - false otherwise */ public static boolean isProxy(final Object obj) { return (obj != null && isProxy(obj.getClass())); } /** * Used to determine if the given class is a proxy class. * * @param clazz the class in question * @return true if proxy - false otherwise */ public static boolean isProxy(final Class<?> clazz) { return (clazz != null && P6Proxy.class.isAssignableFrom(clazz)); } private static Class<?>[] getInterfaces(final Class<?> clazz) { Set<Class<?>> interfaces = new HashSet<Class<?>>(); - // add all interfaces directly implemented by the given class. - interfaces.addAll(Arrays.asList(clazz.getInterfaces())); - // loop through superclasses adding interfaces - Class<?> superclass = clazz.getSuperclass(); - while (superclass != null && !superclass.equals(Object.class)) { - interfaces.addAll(Arrays.asList(superclass.getInterfaces())); - superclass = superclass.getSuperclass(); + Class<?> examinedClass = clazz; + while (examinedClass != null && !examinedClass.equals(Object.class)) { + interfaces.addAll(Arrays.asList(examinedClass.getInterfaces())); + examinedClass = examinedClass.getSuperclass(); } // add P6Proxy interface interfaces.add(P6Proxy.class); return interfaces.toArray(new Class<?>[interfaces.size()]); } }
false
false
null
null
diff --git a/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java b/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java index 2336c86c..75240631 100644 --- a/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java +++ b/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java @@ -1,210 +1,227 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.cismet.cids.custom.treeicons.wunda_blau; import Sirius.navigator.types.treenode.ClassTreeNode; import Sirius.navigator.types.treenode.ObjectTreeNode; import Sirius.navigator.types.treenode.PureTreeNode; import Sirius.navigator.ui.ComponentRegistry; import Sirius.navigator.ui.tree.CidsTreeObjectIconFactory; import Sirius.server.middleware.types.MetaObject; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.tree.DefaultTreeModel; import de.cismet.cids.dynamics.CidsBean; import de.cismet.tools.gui.Static2DTools; /** * DOCUMENT ME! * * @author srichter * @version $Revision$, $Date$ */ public class Alb_baulastIconFactory implements CidsTreeObjectIconFactory { //~ Static fields/initializers --------------------------------------------- private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Alb_baulastIconFactory.class); private static ImageIcon fallback = new ImageIcon(Alb_baulastIconFactory.class.getResource( "/res/16/BaulastGrau.png")); //~ Instance fields -------------------------------------------------------- volatile javax.swing.SwingWorker<Void, Void> objectRetrievingWorker = null; final HashSet<ObjectTreeNode> listOfRetrievingObjectWorkers = new HashSet<ObjectTreeNode>(); private ExecutorService objectRetrievalExecutor = Executors.newFixedThreadPool(15); private final ImageIcon DELETED_ICON; private final ImageIcon CLOSED_ICON; private final ImageIcon WARNING_ICON; private final Object objectRetrievingLock = new Object(); //~ Constructors ----------------------------------------------------------- /** * Creates a new Alb_baulastIconFactory object. */ public Alb_baulastIconFactory() { DELETED_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png")); CLOSED_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/encrypted.png")); WARNING_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/dialog-warning.png")); } //~ Methods ---------------------------------------------------------------- @Override public Icon getClosedPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getOpenPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getLeafPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getOpenObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getClosedObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getLeafObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getClassNodeIcon(final ClassTreeNode dmtn) { return null; } /** * DOCUMENT ME! * * @param node DOCUMENT ME! * * @return DOCUMENT ME! */ private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { - if (!(node == null) - && ComponentRegistry.getRegistry().getSearchResultsTree() - .containsNode( - node.getNode())) { - node.getMetaObject(true); + if (!(node == null)) { + if (node.getPath()[0].equals( + ComponentRegistry.getRegistry().getSearchResultsTree() + .getModel().getRoot())) { + // Searchtree + if (ComponentRegistry.getRegistry().getSearchResultsTree().containsNode( + node.getNode())) { + node.getMetaObject(true); + } + } else { + // normaler Baum + node.getMetaObject(true); + } } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); - ((DefaultTreeModel)ComponentRegistry.getRegistry().getSearchResultsTree() - .getModel()).nodeChanged(node); + if (node.getPath()[0].equals( + ComponentRegistry.getRegistry().getSearchResultsTree() + .getModel().getRoot())) { + // Searchtree + ((DefaultTreeModel)ComponentRegistry.getRegistry() + .getSearchResultsTree().getModel()).nodeChanged(node); + } else { + // normaler Baum + ((DefaultTreeModel)ComponentRegistry.getRegistry().getCatalogueTree() + .getModel()).nodeChanged(node); + } } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; } /** * Checks whether or not all important attributes of a baulast are filled. * * @param baulastBean DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean checkIfBaulastBeansIsComplete(final CidsBean baulastBean) { return (baulastBean.getProperty("laufende_nummer") != null) && (baulastBean.getProperty("lageplan") != null) && (baulastBean.getProperty("textblatt") != null); } }
false
true
private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (!(node == null) && ComponentRegistry.getRegistry().getSearchResultsTree() .containsNode( node.getNode())) { node.getMetaObject(true); } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); ((DefaultTreeModel)ComponentRegistry.getRegistry().getSearchResultsTree() .getModel()).nodeChanged(node); } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; }
private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (!(node == null)) { if (node.getPath()[0].equals( ComponentRegistry.getRegistry().getSearchResultsTree() .getModel().getRoot())) { // Searchtree if (ComponentRegistry.getRegistry().getSearchResultsTree().containsNode( node.getNode())) { node.getMetaObject(true); } } else { // normaler Baum node.getMetaObject(true); } } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); if (node.getPath()[0].equals( ComponentRegistry.getRegistry().getSearchResultsTree() .getModel().getRoot())) { // Searchtree ((DefaultTreeModel)ComponentRegistry.getRegistry() .getSearchResultsTree().getModel()).nodeChanged(node); } else { // normaler Baum ((DefaultTreeModel)ComponentRegistry.getRegistry().getCatalogueTree() .getModel()).nodeChanged(node); } } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; }
diff --git a/src/main/java/de/cismet/cids/trigger/builtin/UpdateToStringCacheTrigger.java b/src/main/java/de/cismet/cids/trigger/builtin/UpdateToStringCacheTrigger.java index d28c77ac..cc3be7d4 100644 --- a/src/main/java/de/cismet/cids/trigger/builtin/UpdateToStringCacheTrigger.java +++ b/src/main/java/de/cismet/cids/trigger/builtin/UpdateToStringCacheTrigger.java @@ -1,178 +1,194 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.trigger.builtin; import Sirius.server.localserver.attribute.ClassAttribute; import Sirius.server.newuser.User; import Sirius.server.sql.DBConnection; import org.openide.util.lookup.ServiceProvider; import java.sql.SQLException; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.trigger.AbstractDBAwareCidsTrigger; import de.cismet.cids.trigger.CidsTrigger; import de.cismet.cids.trigger.CidsTriggerKey; /** * DOCUMENT ME! * * @author thorsten * @version $Revision$, $Date$ */ @ServiceProvider(service = CidsTrigger.class) public class UpdateToStringCacheTrigger extends AbstractDBAwareCidsTrigger { //~ Static fields/initializers --------------------------------------------- private static final transient org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger( UpdateToStringCacheTrigger.class); //~ Methods ---------------------------------------------------------------- @Override public void afterDelete(final CidsBean cidsBean, final User user) { if (isCacheEnabled(cidsBean)) { de.cismet.tools.CismetThreadPool.execute(new javax.swing.SwingWorker<Integer, Void>() { @Override protected Integer doInBackground() throws Exception { return getDbServer().getActiveDBConnection() .submitInternalUpdate( DBConnection.DESC_DELETE_STRINGREPCACHEENTRY, cidsBean.getMetaObject().getClassID(), cidsBean.getMetaObject().getID()); } @Override protected void done() { try { final Integer result = get(); } catch (Exception e) { log.error("Exception in Background Thread: afterDelete", e); } } }); } } @Override public void afterInsert(final CidsBean cidsBean, final User user) { if (isCacheEnabled(cidsBean)) { de.cismet.tools.CismetThreadPool.execute(new javax.swing.SwingWorker<Integer, Void>() { @Override protected Integer doInBackground() throws Exception { - return getDbServer().getActiveDBConnection() - .submitInternalUpdate( - DBConnection.DESC_INSERT_STRINGREPCACHEENTRY, - cidsBean.getMetaObject().getClassID(), - cidsBean.getMetaObject().getID(), - cidsBean.toString()); + final String name = cidsBean.toString(); + + if ((name != null) && !name.equals("")) { + return getDbServer().getActiveDBConnection() + .submitInternalUpdate( + DBConnection.DESC_INSERT_STRINGREPCACHEENTRY, + cidsBean.getMetaObject().getClassID(), + cidsBean.getMetaObject().getID(), + name); + } else { + return 0; + } } @Override protected void done() { try { final Integer result = get(); } catch (Exception e) { log.error("Exception in Background Thread: afterInsert", e); } } }); final String sql = "insert into cs_stringrepcache (class_id,object_id,stringrep) values(" + cidsBean.getMetaObject().getClassID() + "," + cidsBean .getMetaObject().getID() + ",'" + cidsBean.toString() + "');"; } } @Override public void afterUpdate(final CidsBean cidsBean, final User user) { if (isCacheEnabled(cidsBean)) { de.cismet.tools.CismetThreadPool.execute(new javax.swing.SwingWorker<Integer, Void>() { @Override protected Integer doInBackground() throws Exception { try { - return getDbServer().getActiveDBConnection() + final String name = cidsBean.toString(); + if ((name == null) || name.equals("")) { + getDbServer().getActiveDBConnection() .submitInternalUpdate( - DBConnection.DESC_UPDATE_STRINGREPCACHEENTRY, + DBConnection.DESC_DELETE_STRINGREPCACHEENTRY, cidsBean.getMetaObject().getClassID(), - cidsBean.getMetaObject().getID(), - cidsBean.toString()); + cidsBean.getMetaObject().getID()); + return 0; + } else { + return getDbServer().getActiveDBConnection() + .submitInternalUpdate( + DBConnection.DESC_UPDATE_STRINGREPCACHEENTRY, + cidsBean.getMetaObject().getClassID(), + cidsBean.getMetaObject().getID(), + name); + } } catch (SQLException e) { getDbServer().getActiveDBConnection() .submitInternalUpdate( DBConnection.DESC_DELETE_STRINGREPCACHEENTRY, cidsBean.getMetaObject().getClassID(), cidsBean.getMetaObject().getID()); return getDbServer().getActiveDBConnection() .submitInternalUpdate( DBConnection.DESC_INSERT_STRINGREPCACHEENTRY, cidsBean.getMetaObject().getClassID(), cidsBean.getMetaObject().getID(), cidsBean.toString()); } } @Override protected void done() { try { final Integer result = get(); } catch (Exception e) { log.error("Exception in Background Thread: afterUpdate", e); } } }); } } @Override public void beforeDelete(final CidsBean cidsBean, final User user) { } @Override public void beforeInsert(final CidsBean cidsBean, final User user) { } @Override public void beforeUpdate(final CidsBean cidsBean, final User user) { } @Override public CidsTriggerKey getTriggerKey() { return CidsTriggerKey.FORALL; } /** * DOCUMENT ME! * * @param o DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public int compareTo(final CidsTrigger o) { return 0; } /** * DOCUMENT ME! * * @param cidsBean DOCUMENT ME! * * @return DOCUMENT ME! */ private static boolean isCacheEnabled(final CidsBean cidsBean) { return (cidsBean.getMetaObject().getMetaClass().getClassAttribute(ClassAttribute.TO_STRING_CACHE_ENABLED) != null); } }
false
false
null
null
diff --git a/srcj/com/sun/electric/database/geometry/GenMath.java b/srcj/com/sun/electric/database/geometry/GenMath.java index fef7ca505..3d2f6bad7 100644 --- a/srcj/com/sun/electric/database/geometry/GenMath.java +++ b/srcj/com/sun/electric/database/geometry/GenMath.java @@ -1,840 +1,830 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: GenMath.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.database.geometry; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.AffineTransform; /** * General Math Functions. If you are working in Database Units, you * should be using DBMath instead. */ public class GenMath { /** * Class to define an Integer-like object that can be modified. */ public static class MutableInteger { private int value; /** * Constructor creates a MutableInteger object with an initial value. * @param value the initial value. */ public MutableInteger(int value) { this.value = value; } /** * Method to change the value of this MutableInteger. * @param value the new value. */ public void setValue(int value) { this.value = value; } /** * Method to increment this MutableInteger by 1. */ public void increment() { value++; } /** * Method to return the value of this MutableInteger. * @return the current value of this MutableInteger. */ public int intValue() { return value; } /** * Returns a printable version of this MutableInteger. * @return a printable version of this MutableInteger. */ public String toString() { return Integer.toString(value); } } /** * Class to define an Double-like object that can be modified. */ public static class MutableDouble { private double value; /** * Constructor creates a MutableDouble object with an initial value. * @param value the initial value. */ public MutableDouble(double value) { this.value = value; } /** * Method to change the value of this MutableDouble. * @param value the new value. */ public void setValue(double value) { this.value = value; } /** * Method to return the value of this MutableDouble. * @return the current value of this MutableDouble. */ public double doubleValue() { return value; } /** * Returns a printable version of this MutableDouble. * @return a printable version of this MutableDouble. */ public String toString() { return Double.toString(value); } } /** * Method to compare two objects for equality. * This does more than a simple "equal" because they may have the same value * but have diffent type (one Float, the other Double). * @param first the first object to compare. * @param second the second object to compare. * @return true if they are equal. */ public static boolean objectsReallyEqual(Object first, Object second) { // a simple test if (first.equals(second)) return true; // better comparison of numbers (because one may be Float and the other Double) boolean firstNumeric = false, secondNumeric = false; double firstValue = 0, secondValue = 0; if (first instanceof Float) { firstNumeric = true; firstValue = ((Float)first).floatValue(); } else if (first instanceof Double) { firstNumeric = true; firstValue = ((Double)first).doubleValue(); } else if (first instanceof Integer) { firstNumeric = true; firstValue = ((Integer)first).intValue(); } if (second instanceof Float) { secondNumeric = true; secondValue = ((Float)second).floatValue(); } else if (second instanceof Double) { secondNumeric = true; secondValue = ((Double)second).doubleValue(); } else if (second instanceof Integer) { secondNumeric = true; secondValue = ((Integer)second).intValue(); } if (firstNumeric && secondNumeric) { if (firstValue == secondValue) return true; } return false; } /** A transformation matrix that does nothing (identity). */ public static final AffineTransform MATID = new AffineTransform(); /** * Method to return the angle between two points. * @param end1 the first point. * @param end2 the second point. * @return the angle between the points (in tenth-degrees). */ public static int figureAngle(Point2D end1, Point2D end2) { double dx = end2.getX()-end1.getX(); double dy = end2.getY()-end1.getY(); if (dx == 0.0 && dy == 0.0) { System.out.println("Warning: domain violation while figuring angle"); return 0; } double angle = Math.atan2(dy, dx); if (angle < 0) angle += Math.PI*2; int iAngle = (int)(angle * 1800.0 / Math.PI); return iAngle; } /** * Method to return the angle between two points. * @param end1 the first point. * @param end2 the second point. * @return the angle between the points (in radians). */ public static double figureAngleRadians(Point2D end1, Point2D end2) { double dx = end2.getX() - end1.getX(); double dy = end2.getY() - end1.getY(); if (dx == 0.0 && dy == 0.0) { System.out.println("Warning: domain violation while figuring angle in radians"); return 0; } double ang = Math.atan2(dy, dx); if (ang < 0.0) ang += Math.PI * 2.0; return ang; } /** * Method to return the sum of two points. * @param p the first point. * @param dx the X component of the second point * @param dy the T component of the second point * @return the sum of two points. */ public static Point2D addPoints(Point2D p, double dx, double dy) { return new Point2D.Double(p.getX()+dx, p.getY()+dy); } /** - * NOTE: If you are comparing Electric database units, DO NOT - * use this method. Use the corresponding method from DBMath.<p> * Method to tell whether a point is on a given line segment. + * <p>NOTE: If you are comparing Electric database units, DO NOT + * use this method. Use the corresponding method from DBMath. * @param end1 the first end of the line segment. * @param end2 the second end of the line segment. * @param pt the point in question. * @return true if the point is on the line segment. */ public static boolean isOnLine(Point2D end1, Point2D end2, Point2D pt) { // trivial rejection if point not in the bounding box of the line if (pt.getX() < Math.min(end1.getX(), end2.getX())) return false; if (pt.getX() > Math.max(end1.getX(), end2.getX())) return false; if (pt.getY() < Math.min(end1.getY(), end2.getY())) return false; if (pt.getY() > Math.max(end1.getY(), end2.getY())) return false; // handle manhattan cases specially if (end1.getX() == end2.getX()) { if (pt.getX() == end1.getX()) return true; return false; } if (end1.getY() == end2.getY()) { if (pt.getY() == end1.getY()) return true; return false; } // handle nonmanhattan if ((pt.getX()-end1.getX()) * (end2.getY()-end1.getY()) == (pt.getY()-end1.getY()) * (end2.getX()-end1.getX())) return true; return false; } /** * Method to find the point on a line segment that is closest to a given point. * @param p1 one end of the line segment. * @param p2 the other end of the line segment. * @param pt the point near the line segment. * @return a point on the line segment that is closest to "pt". * The point is guaranteed to be between the two points that define the segment. */ public static Point2D closestPointToSegment(Point2D p1, Point2D p2, Point2D pt) { // find closest point on line Point2D pi = closestPointToLine(p1, p2, pt); // see if that intersection point is actually on the segment if (pi.getX() >= Math.min(p1.getX(), p2.getX()) && pi.getX() <= Math.max(p1.getX(), p2.getX()) && pi.getY() >= Math.min(p1.getY(), p2.getY()) && pi.getY() <= Math.max(p1.getY(), p2.getY())) { // it is return pi; } // intersection not on segment: choose one endpoint as the closest double dist1 = pt.distance(p1); double dist2 = pt.distance(p2); if (dist2 < dist1) return p2; return p1; } /** * Method to find the point on a line that is closest to a given point. * @param p1 one end of the line. * @param p2 the other end of the line. * @param pt the point near the line. * @return a point on the line that is closest to "pt". * The point is not guaranteed to be between the two points that define the line. */ public static Point2D closestPointToLine(Point2D p1, Point2D p2, Point2D pt) { // special case for horizontal line if (p1.getY() == p2.getY()) { return new Point2D.Double(pt.getX(), p1.getY()); } // special case for vertical line if (p1.getX() == p2.getX()) { return new Point2D.Double(p1.getX(), pt.getY()); } // compute equation of the line double m = (p1.getY() - p2.getY()) / (p1.getX() - p2.getX()); double b = -p1.getX() * m + p1.getY(); // compute perpendicular to line through the point double mi = -1.0 / m; double bi = -pt.getX() * mi + pt.getY(); // compute intersection of the lines double t = (bi-b) / (m-mi); return new Point2D.Double(t, m * t + b); } /** * Method to compute the distance between point (x,y) and the line that runs * from (x1,y1) to (x2,y2). */ public static double distToLine(Point2D l1, Point2D l2, Point2D pt) { // get point on line from (x1,y1) to (x2,y2) close to (x,y) double x1 = l1.getX(); double y1 = l1.getY(); double x2 = l2.getX(); double y2 = l2.getY(); if (doublesEqual(x1, x2) && doublesEqual(y1, y2)) { return pt.distance(l1); } int ang = figureAngle(l1, l2); Point2D iPt = intersect(l1, ang, pt, ang+900); double iX = iPt.getX(); double iY = iPt.getY(); if (doublesEqual(x1, x2)) iX = x1; if (doublesEqual(y1, y2)) iY = y1; // make sure (ix,iy) is on the segment from (x1,y1) to (x2,y2) if (iX < Math.min(x1,x2) || iX > Math.max(x1,x2) || iY < Math.min(y1,y2) || iY > Math.max(y1,y2)) { if (Math.abs(iX-x1) + Math.abs(iY-y1) < Math.abs(iX-x2) + Math.abs(iY-y2)) { iX = x1; iY = y1; } else { iX = x2; iY = y2; } } iPt.setLocation(iX, iY); return iPt.distance(pt); } /** * Method to find the two possible centers for a circle given a radius and two edge points. * @param r the radius of the circle. * @param p1 one point on the edge of the circle. * @param p2 the other point on the edge of the circle. * @param d the distance between the two points. * @return an array of two Point2Ds, either of which could be the center. * Returns null if there are no possible centers. * This code was written by John Mohammed of Schlumberger. */ public static Point2D [] findCenters(double r, Point2D p1, Point2D p2, double d) { // quit now if the circles concentric if (p1.getX() == p2.getX() && p1.getY() == p2.getY()) return null; // find the intersections, if any double r2 = r * r; double delta_1 = -d / 2.0; double delta_12 = delta_1 * delta_1; // quit if there are no intersections if (r2 < delta_12) return null; // compute the intersection points double delta_2 = Math.sqrt(r2 - delta_12); double x1 = p2.getX() + ((delta_1 * (p2.getX() - p1.getX())) + (delta_2 * (p2.getY() - p1.getY()))) / d; double y1 = p2.getY() + ((delta_1 * (p2.getY() - p1.getY())) + (delta_2 * (p1.getX() - p2.getX()))) / d; double x2 = p2.getX() + ((delta_1 * (p2.getX() - p1.getX())) + (delta_2 * (p1.getY() - p2.getY()))) / d; double y2 = p2.getY() + ((delta_1 * (p2.getY() - p1.getY())) + (delta_2 * (p2.getX() - p1.getX()))) / d; Point2D [] retArray = new Point2D[2]; retArray[0] = new Point2D.Double(x1, y1); retArray[1] = new Point2D.Double(x2, y2); return retArray; } /** - * NOTE: If you are comparing Electric database units, DO NOT - * use this method. Use the corresponding method from DBMath.<p> * Method to tell whether a point is inside of a bounds. + * <p>NOTE: If you are comparing Electric database units, DO NOT + * use this method. Use the corresponding method from DBMath. * The reason that this is necessary is that Rectangle2D.contains requires that * the point be INSIDE of the bounds, whereas this method accepts a point that * is ON the bounds. * @param pt the point in question. * @param bounds the bounds being tested. * @return true if the point is in the bounds. */ public static boolean pointInRect(Point2D pt, Rectangle2D bounds) { if (pt.getX() < bounds.getMinX()) return false; if (pt.getX() > bounds.getMaxX()) return false; if (pt.getY() < bounds.getMinY()) return false; if (pt.getY() > bounds.getMaxY()) return false; return true; } /** * Method to transform a Rectangle2D by a given transformation. * @param bounds the Rectangle to transform. * It is transformed "in place" (its coordinates are overwritten). * @param xform the transformation matrix. */ public static void transformRect(Rectangle2D bounds, AffineTransform xform) { Point2D [] corners = Poly.makePoints(bounds.getMinX(), bounds.getMaxX(), bounds.getMinY(), bounds.getMaxY()); xform.transform(corners, 0, corners, 0, 4); double lX = corners[0].getX(); double lY = corners[0].getY(); double hX = lX; double hY = lY; for(int i=1; i<4; i++) { if (corners[i].getX() < lX) lX = corners[i].getX(); if (corners[i].getX() > hX) hX = corners[i].getX(); if (corners[i].getY() < lY) lY = corners[i].getY(); if (corners[i].getY() > hY) hY = corners[i].getY(); } bounds.setRect(lX, lY, hX-lX, hY-lY); } /** * Method to determine the intersection of two lines and return that point. * @param p1 a point on the first line. * @param ang1 the angle of the first line (in tenth degrees). * @param p2 a point on the second line. * @param ang2 the angle of the second line (in tenth degrees). * @return a point that is the intersection of the lines. * Returns null if there is no intersection point. */ public static Point2D intersect(Point2D p1, int ang1, Point2D p2, int ang2) { // cannot handle lines if they are at the same angle while (ang1 < 0) ang1 += 3600; if (ang1 >= 3600) ang1 %= 3600; while (ang2 < 0) ang2 += 3600; if (ang2 >= 3600) ang2 %= 3600; if (ang1 == ang2) return null; // also cannot handle lines that are off by 180 degrees int amin = ang2, amax = ang1; if (ang1 < ang2) { amin = ang1; amax = ang2; } if (amin + 1800 == amax) return null; double fa1 = sin(ang1); double fb1 = -cos(ang1); double fc1 = -fa1 * p1.getX() - fb1 * p1.getY(); double fa2 = sin(ang2); double fb2 = -cos(ang2); double fc2 = -fa2 * p2.getX() - fb2 * p2.getY(); if (Math.abs(fa1) < Math.abs(fa2)) { double fswap = fa1; fa1 = fa2; fa2 = fswap; fswap = fb1; fb1 = fb2; fb2 = fswap; fswap = fc1; fc1 = fc2; fc2 = fswap; } double fy = (fa2 * fc1 / fa1 - fc2) / (fb2 - fa2*fb1/fa1); return new Point2D.Double((-fb1 * fy - fc1) / fa1, fy); } /** * Method to determine the intersection of two lines and return that point. * @param p1 a point on the first line. * @param ang1 the angle of the first line (in radians). * @param p2 a point on the second line. * @param ang2 the angle of the second line (in radians). * @return a point that is the intersection of the lines. * Returns null if there is no intersection point. */ public static Point2D intersectRadians(Point2D p1, double ang1, Point2D p2, double ang2) { // cannot handle lines if they are at the same angle if (doublesEqual(ang1, ang2)) return null; // also at the same angle if off by 180 degrees double fMin = ang2, fMax = ang2; if (ang1 < ang2) { fMin = ang1; fMax = ang2; } if (doublesEqual(fMin + Math.PI, fMax)) return null; double fa1 = Math.sin(ang1); double fb1 = -Math.cos(ang1); double fc1 = -fa1 * p1.getX() - fb1 * p1.getY(); double fa2 = Math.sin(ang2); double fb2 = -Math.cos(ang2); double fc2 = -fa2 * p2.getX() - fb2 * p2.getY(); if (Math.abs(fa1) < Math.abs(fa2)) { double fswap = fa1; fa1 = fa2; fa2 = fswap; fswap = fb1; fb1 = fb2; fb2 = fswap; fswap = fc1; fc1 = fc2; fc2 = fswap; } double fy = (fa2 * fc1 / fa1 - fc2) / (fb2 - fa2*fb1/fa1); return new Point2D.Double(fy, (-fb1 * fy - fc1) / fa1); } /** smallest such that 1.0+DBL_EPSILON != 1.0 */ private static double DBL_EPSILON = 2.2204460492503131e-016; /** * Method to round a value to the nearest increment. * @param a the value to round. * @param nearest the increment to which it should be rounded. * @return the value, rounded to the nearest increment. * For example:<BR> * toNearest(10.3, 1.0) = 10.0<BR> * toNearest(10.3, 0.1) = 10.3<BR> * toNearest(10.3, 0.5) = 10.5 */ public static double toNearest(double a, double nearest) { long v = Math.round(a / nearest); return v * nearest; } /** * Method to compare two double-precision numbers within an acceptable epsilon. * @param a the first number. * @param b the second number. * @return true if the numbers are equal to 16 decimal places. */ public static boolean doublesEqual(double a, double b) { if (Math.abs(a-b) <= DBL_EPSILON) return true; return false; } /** - * NOTE: If you are comparing Electric database units, DO NOT - * use this method. Use the corresponding method from DBMath.<p> * Method to compare two double-precision numbers within an approximate epsilon. + * <p>NOTE: If you are comparing Electric database units, DO NOT + * use this method. Use the corresponding method from DBMath. * @param a the first number. * @param b the second number. * @return true if the numbers are approximately equal (to a few decimal places). */ public static boolean doublesClose(double a, double b) { if (b != 0) { double ratio = a / b; if (ratio < 1.00001 && ratio > 0.99999) return true; } if (Math.abs(a-b) < 0.001) return true; return false; - -// if (a == 0 || b == 0) -// { -// if (Math.abs(a-b) < 0.001) return true; -// } else -// { -// double ratio = a / b; -// if (ratio < 1.00001 && ratio > 0.99999) return true; -// } -// return false; } /** - * NOTE: If you are comparing Electric database units, DO NOT - * use this method. Use the corresponding method from DBMath.<p> * Method to compare two double-precision coordinates within an approximate epsilon. + * <p>NOTE: If you are comparing Electric database units, DO NOT + * use this method. Use the corresponding method from DBMath. * @param a the first point. * @param b the second point. * @return true if the points are approximately equal (to a few decimal places). */ public static boolean pointsClose(Point2D a, Point2D b) { if (doublesClose(a.getX(), b.getX()) && doublesClose(a.getY(), b.getY())) return true; return false; } /** * Method to round floating-point values to sensible quantities. * Rounds these numbers to the nearest thousandth. * @param a the value to round. * @return the rounded value. */ public static double smooth(double a) { long i = Math.round(a * 1000.0); return i / 1000.0; } private static final int LEFT = 1; private static final int RIGHT = 2; private static final int BOTTOM = 4; private static final int TOP = 8; /** * Method to clip a line against a rectangle. * @param from one end of the line. * @param to the other end of the line. * @param lX the low X bound of the clip. * @param hX the high X bound of the clip. * @param lY the low Y bound of the clip. * @param hY the high Y bound of the clip. * The points are modified to fit inside of the clip area. * @return true if the line is not visible. */ public static boolean clipLine(Point2D from, Point2D to, double lX, double hX, double lY, double hY) { for(;;) { // compute code bits for "from" point int fc = 0; if (from.getX() < lX) fc |= LEFT; else if (from.getX() > hX) fc |= RIGHT; if (from.getY() < lY) fc |= BOTTOM; else if (from.getY() > hY) fc |= TOP; // compute code bits for "to" point int tc = 0; if (to.getX() < lX) tc |= LEFT; else if (to.getX() > hX) tc |= RIGHT; if (to.getY() < lY) tc |= BOTTOM; else if (to.getY() > hY) tc |= TOP; // look for trivial acceptance or rejection if (fc == 0 && tc == 0) return false; if (fc == tc || (fc & tc) != 0) return true; // make sure the "from" side needs clipping if (fc == 0) { double x = from.getX(); double y = from.getY(); from.setLocation(to); to.setLocation(x, y); int t = fc; fc = tc; tc = t; } if ((fc&LEFT) != 0) { if (to.getX() == from.getX()) return true; double t = (to.getY() - from.getY()) * (lX - from.getX()) / (to.getX() - from.getX()); from.setLocation(lX, from.getY() + t); } if ((fc&RIGHT) != 0) { if (to.getX() == from.getX()) return true; double t = (to.getY() - from.getY()) * (hX - from.getX()) / (to.getX() - from.getX()); from.setLocation(hX, from.getY() + t); } if ((fc&BOTTOM) != 0) { if (to.getY() == from.getY()) return true; double t = (to.getX() - from.getX()) * (lY - from.getY()) / ( to.getY() - from.getY()); from.setLocation(from.getX() + t, lY); } if ((fc&TOP) != 0) { if (to.getY() == from.getY()) return true; double t = (to.getX() - from.getX()) * (hY - from.getY()) / (to.getY() - from.getY()); from.setLocation(from.getX() + t, hY); } } } private static final double [] sineTable = { 0.0,0.0017453283658983088,0.003490651415223732,0.00523596383141958,0.0069812602979615525,0.008726535498373935, 0.010471784116245792,0.012217000835247169,0.013962180339145272,0.015707317311820675,0.01745240643728351,0.019197442399689665, 0.020942419883356957,0.022687333572781358,0.024432178152653153,0.02617694830787315,0.02792163872356888,0.029666244085110757, 0.03141075907812829,0.033155178388526274,0.03489949670250097,0.036643708706556276,0.03838780908751994,0.04013179253255973, 0.04187565372919962,0.043619387365336,0.04536298812925378,0.04710645070964266,0.04884976979561326,0.05059294007671331, 0.05233595624294383,0.05407881298477529,0.0558215049931638,0.057564026959567284,0.05930637357596162,0.061048539534856866, 0.06279051952931337,0.06453230825295798,0.06627390040000014,0.06801529066524817,0.0697564737441253,0.07149744433268591, 0.07323819712763169,0.0749787268263277,0.07671902812681863,0.07845909572784494,0.08019892432885892,0.08193850863004093, 0.08367784333231548,0.08541692313736746,0.08715574274765817,0.08889429686644151,0.09063258019778016,0.09237058744656158, 0.09410831331851431,0.095845752520224,0.09758289975914947,0.099319749743639,0.10105629718294634,0.1027925367872468, 0.10452846326765346,0.1062640713362332,0.10799935570602284,0.10973431109104527,0.11146893220632548,0.11320321376790671, 0.11493715049286661,0.11667073709933316,0.11840396830650095,0.1201368388346471,0.12186934340514746,0.12360147674049271, 0.12533323356430426,0.12706460860135046,0.1287955965775628,0.13052619222005157,0.13225639025712244,0.13398618541829205, 0.13571557243430438,0.13744454603714665,0.13917310096006544,0.14090123193758267,0.14262893370551163,0.1443562010009732, 0.14608302856241162,0.14780941112961063,0.14953534344370953,0.1512608202472192,0.15298583628403806,0.1547103862994681, 0.15643446504023087,0.15815806725448353,0.15988118769183485,0.1616038211033611,0.16332596224162227,0.16504760586067765, 0.16676874671610226,0.16848937956500257,0.17020949916603254,0.17192910027940955,0.17364817766693033,0.1753667260919871, 0.1770847403195833,0.17880221511634958,0.18051914525055998,0.18223552549214747,0.18395135061272017,0.1856666153855772, 0.1873813145857246,0.18909544298989128,0.19080899537654483,0.19252196652590742,0.19423435121997196,0.1959461442425177, 0.19765734037912613,0.1993679344171972,0.20107792114596468,0.2027872953565125,0.20449605184179032,0.20620418539662963, 0.20791169081775931,0.20961856290382183,0.21132479645538865,0.21303038627497656,0.2147353271670632,0.21643961393810285, 0.21814324139654254,0.21984620435283753,0.2215484976194673,0.22325011601095135,0.22495105434386498,0.22665130743685505, 0.22835087011065575,0.2300497371881044,0.23174790349415733,0.2334453638559054,0.23514211310259,0.23683814606561868, 0.23853345757858088,0.24022804247726373,0.2419218955996677,0.2436150117860225,0.24530738587880258,0.2469990127227429, 0.2486898871648548,0.2503800040544414,0.2520693582431136,0.25375794458480566,0.25544575793579055,0.25713279315469617, 0.25881904510252074,0.26050450864264835,0.2621891786408647,0.26387304996537286,0.2655561174868088,0.26723837607825685, 0.2689198206152657,0.27060044597586363,0.27228024704057435,0.27395921869243245,0.27563735581699916,0.2773146533023778, 0.2789911060392293,0.28066670892078777,0.2823414568428764,0.2840153447039226,0.28568836740497355,0.287360519849712, 0.2890317969444716,0.2907021935982525,0.29237170472273677,0.29404032523230395,0.29570805004404666,0.29737487407778596, 0.29904079225608665,0.3007057995042731,0.30236989075044446,0.3040330609254903,0.30569530496310565,0.30735661779980705, 0.3090169943749474,0.3106764296307318,0.31233491851223255,0.31399245596740494,0.31564903694710245,0.3173046564050921, 0.3189593092980699,0.32061299058567627,0.3222656952305111,0.3239174181981494,0.3255681544571567,0.3272178989791039, 0.32886664673858323,0.330514392713223,0.3321611318837033,0.3338068592337709,0.335451569750255,0.3370952584230821, 0.3387379202452914,0.34037955021305016,0.3420201433256687,0.34365969458561607,0.34529819899853464,0.34693565157325584, 0.3485720473218152,0.35020738125946743,0.3518416484047018,0.3534748437792571,0.35510696240813705,0.3567379993196252, 0.35836794954530027,0.3599968081200512,0.3616245700820923,0.36325123047297836,0.3648767843376196,0.36650122672429725, 0.3681245526846779,0.3697467572738293,0.3713678355502348,0.37298778257580895,0.37460659341591207,0.3762242631393656, 0.3778407868184671,0.3794561595290051,0.3810703763502741,0.3826834323650898,0.3842953226598037,0.38590604232431863, 0.38751558645210293,0.38912395014020623,0.39073112848927377,0.39233711660356146,0.3939419095909511,0.39554550256296495, 0.3971478906347806,0.3987490689252462,0.4003490325568949,0.4019477766559601,0.40354529635239,0.4051415867798625, 0.40673664307580015,0.40833046038138493,0.4099230338415728,0.41151435860510877,0.41310442982454176,0.414693242656239, 0.41628079226040116,0.41786707380107674,0.4194520824461771,0.421035813367491,0.4226182617406994,0.4241994227453902, 0.42577929156507266,0.4273578633871924,0.4289351334031459,0.43051109680829514,0.4320857488019823,0.43365908458754426, 0.43523109937232746,0.43680178836770217,0.4383711467890774,0.4399391698559151,0.4415058527917452,0.44307119082417973, 0.4446351791849275,0.44619781310980877,0.44775908783876966,0.4493189986158966,0.45087754068943076,0.4524347093117827, 0.45399049973954675,0.4555449072335155,0.4570979270586942,0.45864955448431494,0.46019978478385165,0.4617486132350339, 0.4632960351198617,0.4648420457246196,0.4663866403398912,0.46792981426057334,0.46947156278589075,0.47101188121940996, 0.47255076486905395,0.4740882090471163,0.47562420907027525,0.4771587602596084,0.4786918579406068,0.48022349744318893, 0.4817536741017153,0.4832823832550024,0.48480962024633695,0.48633538042349045,0.4878596591387326,0.4893824517488462, 0.4909037536151409,0.49242356010346716,0.493941866584231,0.4954586684324075,0.49697396102755526,0.49848773975383026, 0.49999999999999994,0.5015107371594573,0.503019946630235,0.5045276238150193,0.5060337641211637,0.5075383629607041, 0.5090414157503713,0.5105429179116057,0.5120428648705715,0.51354125205817,0.5150380749100542,0.5165333288666418, 0.5180270093731302,0.5195191118795094,0.5210096318405764,0.5224985647159488,0.5239859059700791,0.5254716510722678, 0.5269557954966776,0.5284383347223471,0.5299192642332049,0.5313985795180829,0.53287627607073,0.5343523493898263, 0.5358267949789967,0.5372996083468239,0.5387707850068629,0.540240320477655,0.5417082102827397,0.5431744499506707, 0.544639035015027,0.5461019610144291,0.5475632234925503,0.5490228179981317,0.5504807400849956,0.5519369853120581, 0.5533915492433441,0.5548444274479992,0.5562956155003048,0.5577451089796901,0.5591929034707469,0.5606389945632416, 0.5620833778521306,0.5635260489375715,0.5649670034249379,0.5664062369248328,0.5678437450531012,0.5692795234308442, 0.5707135676844316,0.5721458734455162,0.573576436351046,0.5750052520432786,0.5764323161697932,0.5778576243835053, 0.5792811723426788,0.5807029557109398,0.5821229701572894,0.5835412113561175,0.5849576749872154,0.5863723567357892, 0.5877852522924731,0.589196357353342,0.5906056676199254,0.5920131787992196,0.5934188866037015,0.5948227867513413, 0.5962248749656158,0.5976251469755212,0.5990235985155858,0.600420225325884,0.6018150231520482,0.6032079877452825, 0.6045991148623747,0.605988400265711,0.6073758397232867,0.6087614290087207,0.6101451639012676,0.6115270401858311, 0.6129070536529765,0.6142852000989432,0.6156614753256583,0.6170358751407485,0.6184083953575542,0.61977903179514, 0.6211477802783103,0.6225146366376195,0.6238795967093861,0.6252426563357052,0.6266038113644604,0.6279630576493379, 0.6293203910498374,0.6306758074312863,0.6320293026648508,0.6333808726275502,0.6347305132022676,0.636078220277764, 0.6374239897486897,0.6387678175155976,0.6401096994849556,0.6414496315691578,0.6427876096865393,0.6441236297613865, 0.6454576877239505,0.6467897795104596,0.6481199010631309,0.6494480483301835,0.6507742172658509,0.6520984038303922, 0.6534206039901054,0.6547408137173397,0.6560590289905073,0.6573752457940958,0.6586894601186803,0.6600016679609367, 0.6613118653236518,0.6626200482157375,0.6639262126522416,0.6652303546543609,0.6665324702494525,0.6678325554710466, 0.6691306063588582,0.6704266189587991,0.6717205893229902,0.6730125135097733,0.6743023875837234,0.6755902076156601, 0.6768759696826607,0.6781596698680706,0.6794413042615165,0.6807208689589178,0.6819983600624985,0.6832737736807992, 0.6845471059286886,0.6858183529273763,0.687087510804423,0.6883545756937539,0.6896195437356697,0.6908824110768583, 0.6921431738704068,0.693401828275813,0.6946583704589974,0.6959127965923143,0.6971651028545645,0.6984152854310058, 0.6996633405133654,0.7009092642998509,0.7021530529951624,0.7033947028105039,0.7046342099635946,0.705871570678681, 0.7071067811865475,0.7083398377245288,0.7095707365365209,0.7107994738729925,0.7120260459909965,0.7132504491541816, 0.7144726796328033,0.7156927337037359,0.7169106076504826,0.7181262977631888,0.7193398003386512,0.7205511116803304, 0.7217602280983622,0.7229671459095681,0.7241718614374675,0.7253743710122875,0.7265746709709759,0.7277727576572104, 0.7289686274214116,0.7301622766207523,0.7313537016191705,0.7325428987873788,0.7337298645028764,0.7349145951499599, 0.7360970871197343,0.7372773368101241,0.7384553406258837,0.7396310949786097,0.74080459628675,0.7419758409756163, 0.7431448254773942,0.744311546231154,0.7454759996828623,0.7466381822853914,0.7477980904985319,0.7489557207890021, 0.7501110696304595,0.7512641335035111,0.7524149088957244,0.7535633923016378,0.754709580222772,0.7558534691676396, 0.7569950556517564,0.7581343361976522,0.7592713073348808,0.7604059656000309,0.7615383075367367,0.7626683296956883, 0.7637960286346421,0.7649214009184317,0.7660444431189779,0.7671651518152995,0.7682835235935234,0.7693995550468951, 0.7705132427757893,0.77162458338772,0.7727335734973511,0.7738402097265061,0.7749444887041796,0.7760464070665459, 0.7771459614569709,0.778243148526021,0.7793379649314741,0.7804304073383297,0.7815204724188187,0.7826081568524139, 0.7836934573258397,0.7847763705330829,0.7858568931754019,0.7869350219613374,0.7880107536067219,0.7890840848346907, 0.7901550123756903,0.79122353296749,0.7922896433551907,0.7933533402912352,0.7944146205354181,0.7954734808548958, 0.7965299180241963,0.7975839288252284,0.7986355100472928,0.7996846584870905,0.8007313709487335,0.801775644243754, 0.8028174751911145,0.8038568606172174,0.8048937973559142,0.8059282822485158,0.8069603121438019,0.8079898838980305, 0.8090169943749475,0.810041640445796,0.8110638189893266,0.8120835268918062,0.8131007610470277,0.8141155183563192, 0.8151277957285542,0.8161375900801602,0.8171448983351285,0.8181497174250234,0.8191520442889918,0.820151875873772, 0.821149209133704,0.8221440410307373,0.8231363685344418,0.8241261886220157,0.8251134982782952,0.8260982944957639, 0.8270805742745618,0.8280603346224944,0.8290375725550416,0.8300122850953675,0.8309844692743282,0.8319541221304826, 0.8329212407100994,0.8338858220671681,0.8348478632634065,0.8358073613682702,0.8367643134589617,0.8377187166204387, 0.838670567945424,0.8396198645344132,0.8405666034956842,0.8415107819453062,0.8424523970071476,0.8433914458128856, 0.8443279255020151,0.8452618332218561,0.846193166127564,0.8471219213821372,0.8480480961564258,0.8489716876291414, 0.8498926929868639,0.8508111094240512,0.8517269341430476,0.8526401643540922,0.8535507972753273,0.8544588301328074, 0.8553642601605067,0.8562670846003282,0.8571673007021123,0.8580649057236446,0.8589598969306644,0.8598522715968734, 0.8607420270039435,0.8616291604415257,0.8625136692072574,0.8633955506067716,0.8642748019537047,0.8651514205697045, 0.8660254037844386,0.8668967489356028,0.8677654533689284,0.8686315144381913,0.869494929505219,0.8703556959398997, 0.8712138111201894,0.8720692724321206,0.8729220772698096,0.8737722230354652,0.8746197071393957,0.8754645270000179, 0.8763066800438636,0.8771461637055887,0.8779829754279805,0.8788171126619653,0.8796485728666165,0.8804773535091619, 0.8813034520649922,0.8821268660176678,0.8829475928589269,0.8837656300886935,0.8845809752150839,0.8853936257544159, 0.8862035792312147,0.8870108331782217,0.8878153851364013,0.8886172326549489,0.8894163732912975,0.8902128046111265, 0.8910065241883678,0.891797529605214,0.8925858184521255,0.8933713883278375,0.8941542368393681,0.894934361602025, 0.8957117602394129,0.8964864303834404,0.8972583696743284,0.8980275757606155,0.898794046299167,0.8995577789551804, 0.9003187714021935,0.9010770213220917,0.9018325264051138,0.9025852843498605,0.9033352928633008,0.9040825496607783, 0.9048270524660196,0.9055687990111395,0.9063077870366499,0.9070440142914649,0.9077774785329086,0.9085081775267219, 0.9092361090470685,0.9099612708765432,0.910683660806177,0.9114032766354453,0.912120116172273,0.9128341772330428, 0.9135454576426009,0.9142539552342637,0.9149596678498249,0.915662593339561,0.9163627295622396,0.917060074385124, 0.917754625683981,0.9184463813430871,0.9191353392552345,0.9198214973217376,0.9205048534524403,0.9211854055657211, 0.9218631515885005,0.9225380894562464,0.9232102171129808,0.9238795325112867,0.9245460336123131,0.9252097183857821, 0.9258705848099947,0.9265286308718373,0.9271838545667874,0.92783625389892,0.9284858268809135,0.9291325715340562, 0.9297764858882513,0.9304175679820246,0.9310558158625283,0.9316912275855489,0.9323238012155122,0.9329535348254889, 0.9335804264972017,0.9342044743210295,0.9348256763960144,0.9354440308298673,0.9360595357389733,0.9366721892483976, 0.9372819894918915,0.9378889346118976,0.9384930227595559,0.9390942520947091,0.9396926207859083,0.9402881270104189, 0.9408807689542255,0.9414705448120378,0.9420574527872967,0.9426414910921784,0.943222657947601,0.9438009515832294, 0.9443763702374811,0.9449489121575309,0.9455185755993167,0.9460853588275453,0.9466492601156964,0.9472102777460288, 0.9477684100095857,0.9483236552061993,0.9488760116444965,0.9494254776419038,0.9499720515246525,0.9505157316277837, 0.9510565162951535,0.9515944038794382,0.9521293927421386,0.9526614812535863,0.953190667792947,0.9537169507482268, 0.9542403285162768,0.9547607995027975,0.9552783621223436,0.9557930147983301,0.9563047559630354,0.9568135840576074, 0.9573194975320672,0.9578224948453149,0.9583225744651332,0.958819734868193,0.9593139745400575,0.9598052919751869, 0.9602936856769431,0.9607791541575941,0.9612616959383188,0.9617413095492113,0.9622179935292854,0.9626917464264787, 0.9631625667976581,0.9636304532086231,0.9640954042341101,0.9645574184577981,0.9650164944723114,0.9654726308792251, 0.9659258262890683,0.9663760793213293,0.9668233886044594,0.9672677527758767,0.9677091704819711,0.9681476403781077, 0.9685831611286311,0.9690157314068695,0.9694453498951389,0.9698720152847469,0.9702957262759965,0.9707164815781908, 0.971134279909636,0.9715491199976461,0.9719610005785463,0.9723699203976766,0.9727758782093965,0.9731788727770883, 0.9735789028731602,0.9739759672790516,0.9743700647852352,0.9747611941912218,0.9751493543055632,0.9755345439458565, 0.9759167619387474,0.9762960071199334,0.9766722783341679,0.9770455744352635,0.9774158942860959,0.9777832367586061, 0.9781476007338056,0.9785089851017784,0.978867388761685,0.9792228106217657,0.9795752495993441,0.9799247046208296, 0.9802711746217219,0.980614658546613,0.9809551553491915,0.9812926639922451,0.981627183447664,0.9819587126964436, 0.9822872507286887,0.9826127965436152,0.9829353491495543,0.9832549075639545,0.9835714708133859,0.9838850379335417, 0.9841956079692419,0.9845031799744366,0.984807753012208,0.9851093261547739,0.9854078984834901,0.9857034690888535, 0.9859960370705049,0.9862856015372313,0.9865721616069694,0.9868557164068072,0.9871362650729879,0.9874138067509114, 0.9876883405951377,0.9879598657693891,0.9882283814465528,0.9884938868086836,0.9887563810470058,0.9890158633619168, 0.9892723329629883,0.9895257890689694,0.989776230907789,0.9900236577165575,0.9902680687415704,0.9905094632383088, 0.9907478404714436,0.9909831997148363,0.9912155402515417,0.9914448613738104,0.9916711623830904,0.9918944425900297, 0.9921147013144778,0.9923319378854887,0.992546151641322,0.9927573419294455,0.9929655081065369,0.9931706495384861, 0.9933727656003964,0.9935718556765875,0.9937679191605964,0.9939609554551797,0.9941509639723154,0.9943379441332046, 0.9945218953682733,0.9947028171171742,0.9948807088287882,0.9950555699612263,0.9952273999818312,0.9953961983671789, 0.99556196460308,0.9957246981845821,0.9958843986159703,0.9960410654107695,0.9961946980917455,0.9963452961909064, 0.9964928592495044,0.9966373868180366,0.9967788784562471,0.996917333733128,0.9970527522269202,0.9971851335251157, 0.9973144772244581,0.997440782930944,0.9975640502598242,0.9976842788356053,0.99780146829205,0.997915618272179, 0.9980267284282716,0.9981347984218669,0.9982398279237653,0.9983418166140283,0.998440764181981,0.9985366703262117, 0.9986295347545738,0.9987193571841863,0.998806137341434,0.99888987496197,0.9989705697907146,0.9990482215818578, 0.9991228300988584,0.999194395114446,0.9992629164106211,0.9993283937786562,0.9993908270190958,0.9994502159417572, 0.9995065603657316,0.999559860119384,0.9996101150403544,0.9996573249755573,0.9997014897811831,0.9997426093226983, 0.9997806834748455,0.9998157121216442,0.9998476951563913,0.9998766324816606,0.9999025240093042,0.999925369660452, 0.9999451693655121,0.9999619230641713,0.9999756307053947,0.9999862922474267,0.9999939076577904,0.9999984769132877, 1.0}; /** * Method to compute the sine of an integer angle (in tenth-degrees). * @param angle the angle in tenth-degrees. * @return the sine of that angle. */ public static double sin(int angle) { while (angle < 0) angle += 3600; if (angle >= 3600) angle %= 3600; if (angle <= 900) return sineTable[angle]; if (angle <= 1800) return sineTable[1800-angle]; if (angle <= 2700) return -sineTable[angle-1800]; return -sineTable[3600-angle]; } /** * Method to compute the cosine of an integer angle (in tenth-degrees). * @param angle the angle in tenth-degrees. * @return the cosine of that angle. */ public static double cos(int angle) { while (angle < 0) angle += 3600; if (angle >= 3600) angle %= 3600; if (angle <= 900) return sineTable[900-angle]; if (angle <= 1800) return -sineTable[angle-900]; if (angle <= 2700) return -sineTable[2700-angle]; return sineTable[angle-2700]; } /** * Method to return a long that represents the unsigned * value of an integer. I.e., the passed int is a set of * bits, and this method returns a number as if those bits * were interpreted as an unsigned int. */ public static long unsignedIntValue(int n) { if (n > 0) return (long)n; // int is > 0 long num = 0; num = n | num; return num; } }
false
false
null
null
diff --git a/test/org/imagejdev/beans/FHTEJBEndpointTest.java b/test/org/imagejdev/beans/FHTEJBEndpointTest.java index 0311196..4c34423 100644 --- a/test/org/imagejdev/beans/FHTEJBEndpointTest.java +++ b/test/org/imagejdev/beans/FHTEJBEndpointTest.java @@ -1,81 +1,81 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.imagejdev.beans; import com.caucho.hessian.client.HessianProxyFactory; import java.net.MalformedURLException; import org.imagejdev.api.FHTEJBService; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * @author rick */ public class FHTEJBEndpointTest { private FHTEJBService fhtejbservice; @Before public void initProxy() throws MalformedURLException { String url = "http://144.92.92.76:8080/EJBHessianFHT/FHTEJBService"; HessianProxyFactory factory = new HessianProxyFactory(); this.fhtejbservice = (FHTEJBService) factory.create(FHTEJBService.class,url); assertNotNull(fhtejbservice); } @Test public void testProfile() { long time = System.currentTimeMillis(); float[][] expResult = new float[512][6]; //33MB for(int i = 0; i < 100; i++) { float[][] result = this.fhtejbservice.getProfileData( expResult ); assertArrayEquals( expResult, result ); System.out.println(i + " Time is " + (System.currentTimeMillis() - time) ); } } /** * Test of fht method, of class FHTEJBEndpoint. */ @Test public void testFht() { System.out.println("fht"); int width = 8; int height = 8; int depth = 8; float[][] data = { {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, }; boolean inverse = true; float[][] expResult = { {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, {0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f,0.0f,0.1f}, }; long time = System.currentTimeMillis(); for(int i = 0; i < 100; i++) { System.out.println(i + " FHT, mSec: " + (System.currentTimeMillis() - time) ); float[][] result = this.fhtejbservice.fht(width, height, depth, data, inverse); } //assertArrayEquals(expResult, result); } -} \ No newline at end of file +}
false
false
null
null
diff --git a/src/paulscode/android/mupen64plusae/input/map/AxisMap.java b/src/paulscode/android/mupen64plusae/input/map/AxisMap.java index 95032dfe..9c40c38b 100644 --- a/src/paulscode/android/mupen64plusae/input/map/AxisMap.java +++ b/src/paulscode/android/mupen64plusae/input/map/AxisMap.java @@ -1,170 +1,187 @@ package paulscode.android.mupen64plusae.input.map; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.annotation.TargetApi; import android.text.TextUtils; import android.util.SparseArray; import android.view.InputDevice; import android.view.InputDevice.MotionRange; import android.view.MotionEvent; @TargetApi( 9 ) public class AxisMap extends SerializableMap { public static final int AXIS_CLASS_UNKNOWN = 0; public static final int AXIS_CLASS_IGNORED = 1; public static final int AXIS_CLASS_STICK = 2; public static final int AXIS_CLASS_TRIGGER = 3; public static final int AXIS_CLASS_OUYA_LX_STICK = 101; public static final int AXIS_CLASS_RAPHNET_STICK = 102; public static final int AXIS_CLASS_RAPHNET_TRIGGER = 103; private static final int SIGNATURE_HASH_XBOX360 = 449832952; private static final int SIGNATURE_HASH_XBOX360_WIRELESS = -412618953; private static final int SIGNATURE_HASH_PS3 = -528816963; private static final int SIGNATURE_HASH_NYKO_PLAYPAD = 1245841466; private static final int SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD = 1247256123; + private static final String NAME_STRING_NYKO_PLAYPAD = "NYKO PLAYPAD"; + private static final String NAME_STRING_OUYA = "OUYA"; + private static final String NAME_STRING_RAPHNET = "raphnet.net GC/N64"; + private static final SparseArray<AxisMap> sAllMaps = new SparseArray<AxisMap>(); private final String mSignature; public static AxisMap getMap( InputDevice device ) { if( device == null ) return null; int id = device.hashCode(); AxisMap map = sAllMaps.get( id ); if( map == null ) { // Add an entry to the map if not found map = new AxisMap( device ); sAllMaps.put( id, map ); } return map; } @TargetApi( 12 ) public AxisMap( InputDevice device ) { // Auto-classify the axes List<MotionRange> motionRanges = device.getMotionRanges(); List<Integer> axisCodes = new ArrayList<Integer>(); for( MotionRange motionRange : motionRanges ) { if( motionRange.getSource() == InputDevice.SOURCE_JOYSTICK ) { int axisCode = motionRange.getAxis(); int axisClass = detectClass( motionRange ); setClass( axisCode, axisClass ); axisCodes.add( axisCode ); } } // Construct the signature based on the available axes Collections.sort( axisCodes ); mSignature = TextUtils.join( ",", axisCodes ); // Use the signature to override faulty auto-classifications switch( mSignature.hashCode() ) { case SIGNATURE_HASH_XBOX360: case SIGNATURE_HASH_XBOX360_WIRELESS: // Resting value is -1 on the analog triggers; fix that setClass( MotionEvent.AXIS_Z, AXIS_CLASS_TRIGGER ); setClass( MotionEvent.AXIS_RZ, AXIS_CLASS_TRIGGER ); break; case SIGNATURE_HASH_PS3: // Ignore pressure sensitive buttons (buggy on Android) setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_5, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_6, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_7, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_8, AXIS_CLASS_IGNORED ); break; case SIGNATURE_HASH_NYKO_PLAYPAD: - // Ignore AXIS_HAT_X/Y because they are sent with (and overpower) AXIS_X/Y - setClass( MotionEvent.AXIS_HAT_X, AXIS_CLASS_IGNORED ); - setClass( MotionEvent.AXIS_HAT_Y, AXIS_CLASS_IGNORED ); + if( !device.getName().contains( NAME_STRING_NYKO_PLAYPAD ) ) + { + // The first batch of Nyko Playpad controllers have a quirk in the firmware + // where AXIS_HAT_X/Y are sent with (and overpower) AXIS_X/Y, and do not + // provide a recognizable name for the controller. Newer batches of this + // controller fix the quirk, making it a vanilla controller. However the + // AXIS_HAT_X/Y channels are now used for the d-pad, so we can't apply a + // universal solution for all versions of this controller. Fortunately, the + // new version also returns a good name that we can use to differentiate + // controller firmware versions. + // + // For original firmware, ignore AXIS_HAT_X/Y because they are sent with (and + // overpower) AXIS_X/Y, so ignore the HAT_X/Y signals + setClass( MotionEvent.AXIS_HAT_X, AXIS_CLASS_IGNORED ); + setClass( MotionEvent.AXIS_HAT_Y, AXIS_CLASS_IGNORED ); + } break; case SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD: // Bug in controller firmware cross-wires throttle and right stick up/down setClass( MotionEvent.AXIS_THROTTLE, AXIS_CLASS_STICK ); break; } // Check if the controller is OUYA, to compensate for the +X axis bias - if( device.getName().contains( "OUYA" ) ) + if( device.getName().contains( NAME_STRING_OUYA ) ) { setClass( MotionEvent.AXIS_X, AXIS_CLASS_OUYA_LX_STICK ); } // Check if the controller is a raphnet N64/USB adapter, to compensate for range of motion // http://raphnet-tech.com/products/gc_n64_usb_adapters/ - if( device.getName().contains( "raphnet.net GC/N64" ) ) + if( device.getName().contains( NAME_STRING_RAPHNET ) ) { setClass( MotionEvent.AXIS_X, AXIS_CLASS_RAPHNET_STICK ); setClass( MotionEvent.AXIS_Y, AXIS_CLASS_RAPHNET_STICK ); setClass( MotionEvent.AXIS_RX, AXIS_CLASS_RAPHNET_STICK ); setClass( MotionEvent.AXIS_RY, AXIS_CLASS_RAPHNET_STICK ); setClass( MotionEvent.AXIS_RZ, AXIS_CLASS_RAPHNET_TRIGGER ); } } public void setClass( int axisCode, int axisClass ) { if( axisClass == AXIS_CLASS_UNKNOWN ) mMap.delete( axisCode ); else mMap.put( axisCode, axisClass ); } public int getClass( int axisCode ) { return mMap.get( axisCode ); } public String getSignature() { return mSignature; } public String getSignatureName() { switch( mSignature.hashCode() ) { case SIGNATURE_HASH_XBOX360: return "Xbox 360 compatible"; case SIGNATURE_HASH_XBOX360_WIRELESS: return "Xbox 360 wireless"; case SIGNATURE_HASH_PS3: return "PS3 compatible"; case SIGNATURE_HASH_NYKO_PLAYPAD: return "Nyko PlayPad series"; case SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD: return "Logitech Wingman Rumblepad"; default: return "Default"; } } @TargetApi( 12 ) private static int detectClass( MotionRange motionRange ) { if( motionRange != null ) { if( motionRange.getMin() == -1 ) return AXIS_CLASS_STICK; else if( motionRange.getMin() == 0 ) return AXIS_CLASS_TRIGGER; } return AXIS_CLASS_UNKNOWN; } }
false
false
null
null
diff --git a/src/net/xemnias/client/AnimationList.java b/src/net/xemnias/client/AnimationList.java index f5f2a4a..b29afdc 100644 --- a/src/net/xemnias/client/AnimationList.java +++ b/src/net/xemnias/client/AnimationList.java @@ -1,33 +1,33 @@ package net.xemnias.client; import org.newdawn.slick.Image; public class AnimationList { public static Animation playerStandingRight; public static Animation playerStandingLeft; public static Animation playerRunningRight; public static void init() { playerStandingRight = new Animation(new org.newdawn.slick.SpriteSheet(CommunityGame.loader.getAnimationByName("playerStandingRight.png"), 32,64), 150); playerStandingLeft = new Animation(new org.newdawn.slick.SpriteSheet(CommunityGame.loader.getAnimationByName("playerStandingLeft.png"), 32,64), 150); playerRunningRight = new Animation(playerRrunningRightSprite(), 150); } private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; - img[0] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(0, 0, 32, 64); - img[1] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(32, 0, 32, 64); - img[2] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(64, 0, 46, 64); - img[3] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(110, 0, 40, 64); - img[4] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(150, 0, 32, 64); - img[5] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(182, 0, 32, 64); - img[6] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(214, 0, 38, 64); - img[7] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(252, 0, 44, 64); + img[0] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(0, 0, 32, 64); + img[1] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(32, 0, 32, 64); + img[2] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(64, 0, 46, 64); + img[3] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(110, 0, 40, 64); + img[4] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(150, 0, 32, 64); + img[5] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(182, 0, 32, 64); + img[6] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(214, 0, 38, 64); + img[7] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(252, 0, 44, 64); return img; } }
true
true
private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; img[0] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(0, 0, 32, 64); img[1] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(32, 0, 32, 64); img[2] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(64, 0, 46, 64); img[3] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(110, 0, 40, 64); img[4] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(150, 0, 32, 64); img[5] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(182, 0, 32, 64); img[6] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(214, 0, 38, 64); img[7] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(252, 0, 44, 64); return img; }
private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; img[0] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(0, 0, 32, 64); img[1] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(32, 0, 32, 64); img[2] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(64, 0, 46, 64); img[3] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(110, 0, 40, 64); img[4] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(150, 0, 32, 64); img[5] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(182, 0, 32, 64); img[6] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(214, 0, 38, 64); img[7] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(252, 0, 44, 64); return img; }
diff --git a/src/main/java/org/encog/ml/data/basic/BasicMLSequenceSet.java b/src/main/java/org/encog/ml/data/basic/BasicMLSequenceSet.java index 362cbad78..3b2a259dd 100644 --- a/src/main/java/org/encog/ml/data/basic/BasicMLSequenceSet.java +++ b/src/main/java/org/encog/ml/data/basic/BasicMLSequenceSet.java @@ -1,331 +1,337 @@ /* * Encog(tm) Core v3.0 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2011 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.data.basic; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.encog.EncogError; import org.encog.ml.data.MLData; import org.encog.ml.data.MLDataError; import org.encog.ml.data.MLDataPair; import org.encog.ml.data.MLDataSet; import org.encog.ml.data.MLSequenceSet; import org.encog.ml.data.basic.BasicMLDataSet.BasicMLIterator; import org.encog.util.EngineArray; import org.encog.util.obj.ObjectCloner; public class BasicMLSequenceSet implements Serializable, MLSequenceSet { /** * An iterator to be used with the BasicMLDataSet. This iterator does not * support removes. * * @author jheaton */ public class BasicMLSeqIterator implements Iterator<MLDataPair> { /** * The index that the iterator is currently at. */ private int currentIndex = 0; private int currentSequenceIndex = 0; /** * {@inheritDoc} */ @Override public final boolean hasNext() { - if( this.currentSequenceIndex==(sequences.size()-1) ) { - return this.currentIndex < sequences.get(this.currentIndex).getRecordCount(); - } else { - return true; + if( this.currentSequenceIndex>=sequences.size() ) { + return false; + } + + MLDataSet seq = sequences.get(this.currentSequenceIndex); + + if(this.currentIndex>=seq.getRecordCount()) { + return false; } + + return true; } /** * {@inheritDoc} */ @Override public final MLDataPair next() { if (!hasNext()) { return null; } MLDataSet target = sequences.get(this.currentSequenceIndex); MLDataPair result = ((BasicMLDataSet)target).getData().get(this.currentIndex); this.currentIndex++; if( this.currentIndex>=target.getRecordCount()) { this.currentIndex = 0; this.currentSequenceIndex++; } return result; } /** * {@inheritDoc} */ @Override public final void remove() { throw new EncogError("Called remove, unsupported operation."); } } /** * The serial id. */ private static final long serialVersionUID = -2279722928570071183L; /** * The data held by this object. */ private List<MLDataSet> sequences = new ArrayList<MLDataSet>(); private MLDataSet currentSequence; /** * Default constructor. */ public BasicMLSequenceSet() { this.currentSequence = new BasicMLDataSet(); sequences.add(this.currentSequence); } public BasicMLSequenceSet(BasicMLSequenceSet other) { this.sequences = other.sequences; this.currentSequence = other.currentSequence; } /** * Construct a data set from an input and ideal array. * * @param input * The input into the machine learning method for training. * @param ideal * The ideal output for training. */ public BasicMLSequenceSet(final double[][] input, final double[][] ideal) { this.currentSequence = new BasicMLDataSet(input,ideal); this.sequences.add(this.currentSequence); } /** * Construct a data set from an already created list. Mostly used to * duplicate this class. * * @param theData * The data to use. */ public BasicMLSequenceSet(final List<MLDataPair> theData) { this.currentSequence = new BasicMLDataSet(theData); this.sequences.add(this.currentSequence); } /** * Copy whatever dataset type is specified into a memory dataset. * * @param set * The dataset to copy. */ public BasicMLSequenceSet(final MLDataSet set) { this.currentSequence = new BasicMLDataSet(); this.sequences.add(this.currentSequence); final int inputCount = set.getInputSize(); final int idealCount = set.getIdealSize(); for (final MLDataPair pair : set) { BasicMLData input = null; BasicMLData ideal = null; if (inputCount > 0) { input = new BasicMLData(inputCount); EngineArray.arrayCopy(pair.getInputArray(), input.getData()); } if (idealCount > 0) { ideal = new BasicMLData(idealCount); EngineArray.arrayCopy(pair.getIdealArray(), ideal.getData()); } this.currentSequence.add(new BasicMLDataPair(input, ideal)); } } /** * {@inheritDoc} */ @Override public void add(final MLData theData) { this.currentSequence.add(theData); } /** * {@inheritDoc} */ @Override public void add(final MLData inputData, final MLData idealData) { final MLDataPair pair = new BasicMLDataPair(inputData, idealData); this.currentSequence.add(pair); } /** * {@inheritDoc} */ @Override public void add(final MLDataPair inputData) { this.currentSequence.add(inputData); } /** * {@inheritDoc} */ @Override public final Object clone() { return ObjectCloner.deepCopy(this); } /** * {@inheritDoc} */ @Override public final void close() { // nothing to close } /** * {@inheritDoc} */ @Override public final int getIdealSize() { if (this.sequences.get(0).getRecordCount()==0) { return 0; } return this.sequences.get(0).getIdealSize(); } /** * {@inheritDoc} */ @Override public final int getInputSize() { if (this.sequences.get(0).getRecordCount()==0) { return 0; } return this.sequences.get(0).getIdealSize(); } /** * {@inheritDoc} */ @Override public final void getRecord(final long index, final MLDataPair pair) { long recordIndex = index; int sequenceIndex = 0; while( this.sequences.get(sequenceIndex).getRecordCount()<recordIndex) { recordIndex-=this.sequences.get(sequenceIndex).getRecordCount(); sequenceIndex++; if( sequenceIndex>this.sequences.size() ) { throw new MLDataError("Record out of range: " + index); } } this.sequences.get(sequenceIndex).getRecord(recordIndex, pair); } /** * {@inheritDoc} */ @Override public final long getRecordCount() { long result = 0; for(MLDataSet ds: this.sequences) { result+=ds.getRecordCount(); } return result; } /** * {@inheritDoc} */ @Override public final boolean isSupervised() { if (this.sequences.get(0).getRecordCount() == 0) { return false; } return this.sequences.get(0).isSupervised(); } /** * {@inheritDoc} */ @Override public final Iterator<MLDataPair> iterator() { final BasicMLSeqIterator result = new BasicMLSeqIterator(); return result; } /** * {@inheritDoc} */ @Override public final MLDataSet openAdditional() { return new BasicMLSequenceSet(this); } @Override public void startNewSequence() { if (this.currentSequence.getRecordCount() > 0) { this.currentSequence = new BasicMLDataSet(); this.sequences.add(this.currentSequence); } } @Override public int getSequenceCount() { return this.sequences.size(); } @Override public MLDataSet getSequence(int i) { return this.sequences.get(i); } @Override public Collection<MLDataSet> getSequences() { return this.sequences; } }
false
false
null
null
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/StudyPermissionsPage.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/StudyPermissionsPage.java index 01a169f4..f2f83027 100644 --- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/StudyPermissionsPage.java +++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/StudyPermissionsPage.java @@ -1,504 +1,504 @@ /* * Dataverse Network - A web application to distribute, share and analyze quantitative data. * Copyright (C) 2007 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses * or write to the Free Software Foundation,Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * StudyPermissionsPage.java * * Created on October 11, 2006, 2:03 PM * */ package edu.harvard.iq.dvn.core.web.study; import edu.harvard.iq.dvn.core.admin.GroupServiceLocal; import edu.harvard.iq.dvn.core.admin.NetworkRoleServiceBean; import edu.harvard.iq.dvn.core.admin.RoleServiceBean; import edu.harvard.iq.dvn.core.admin.UserGroup; import edu.harvard.iq.dvn.core.admin.UserServiceLocal; import edu.harvard.iq.dvn.core.admin.VDCRole; import edu.harvard.iq.dvn.core.admin.VDCUser; import edu.harvard.iq.dvn.core.study.EditStudyPermissionsService; import edu.harvard.iq.dvn.core.study.PermissionBean; import edu.harvard.iq.dvn.core.util.StringUtil; import edu.harvard.iq.dvn.core.web.common.VDCBaseBean; import java.util.Iterator; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import com.icesoft.faces.component.ext.HtmlInputText; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.inject.Named; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.http.HttpServletRequest; /** * <p>Page bean that corresponds to a similarly named JSP page. This * class contains component definitions (and initialization code) for * all components that you have defined on this page, as well as * lifecycle methods and event handlers where you may add behavior * to respond to incoming events.</p> */ @Named("StudyPermissionsPage") @ViewScoped @EJB(name="editStudyPermissions", beanInterface=edu.harvard.iq.dvn.core.study.EditStudyPermissionsService.class) public class StudyPermissionsPage extends VDCBaseBean implements java.io.Serializable { private EditStudyPermissionsService editStudyPermissions; @EJB private UserServiceLocal userService; @EJB GroupServiceLocal groupService; private boolean viewCurrentFiles = true; public boolean isViewCurrentFiles() { return viewCurrentFiles; } public void setViewCurrentFiles(boolean viewCurrentFiles) { this.viewCurrentFiles = viewCurrentFiles; } /** * <p>Construct a new Page bean instance.</p> */ public StudyPermissionsPage() { } public void init() { try { Context ctx = new InitialContext(); editStudyPermissions = (EditStudyPermissionsService) ctx.lookup("java:comp/env/editStudyPermissions"); } catch (NamingException e) { e.printStackTrace(); FacesContext context = FacesContext.getCurrentInstance(); FacesMessage errMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null); context.addMessage(null, errMessage); } editStudyPermissions.setStudy(getStudyId()); studyUI = new StudyUI(editStudyPermissions.getStudy()); long latestVersion = editStudyPermissions.getStudy().getLatestVersion().getVersionNumber(); editStudyPermissions.setStudy(getStudyId(), latestVersion); } public EditStudyPermissionsService getEditStudyPermissions() { return editStudyPermissions; } public void setEditStudyPermissions(EditStudyPermissionsService editStudyPermissions) { this.editStudyPermissions = editStudyPermissions; } /** * Holds value of property newStudyUser. */ private String newStudyUser; /** * Getter for property newStudyUser. * @return Value of property newStudyUser. */ public String getNewStudyUser() { return this.newStudyUser; } /** * Setter for property newStudyUser. * @param newStudyUser New value of property newStudyUser. */ public void setNewStudyUser(String newStudyUser) { this.newStudyUser = newStudyUser; } /** * Holds value of property newFileUser. */ private String newFileUser; /** * Getter for property newFileUser. * @return Value of property newFileUser. */ public String getNewFileUser() { return this.newFileUser; } /** * Setter for property newFileUser. * @param newFileUser New value of property newFileUser. */ public void setNewFileUser(String newFileUser) { this.newFileUser = newFileUser; } public void addStudyPermission(ActionEvent ae) { VDCUser user = userService.findByUserName(newStudyUser); UserGroup group = null; if (user==null) { group = groupService.findByName(newStudyUser); } if (user==null && group==null) { String msg = "Invalid user or group name."; FacesMessage message = new FacesMessage(msg); FacesContext.getCurrentInstance().addMessage(studyUserInputText.getClientId(FacesContext.getCurrentInstance()), message); } else { if (user!=null ) { if (validateStudyUserName(FacesContext.getCurrentInstance(),studyUserInputText, newStudyUser)) { this.editStudyPermissions.addStudyUser(user.getId()); newStudyUser=""; } } else { if (validateStudyGroupName(FacesContext.getCurrentInstance(),studyUserInputText, newStudyUser)) { this.editStudyPermissions.addStudyGroup(group.getId()); newStudyUser=""; } } } } public void addFilePermission(ActionEvent ae) { if (!StringUtil.isEmpty(newFileUser)) { VDCUser user = userService.findByUserName(newFileUser); UserGroup group = null; if (user==null) { group = groupService.findByName(newFileUser); } if (user==null && group==null) { String msg = "Invalid user or group name."; FacesMessage message = new FacesMessage(msg); FacesContext.getCurrentInstance().addMessage(fileUserInputText.getClientId(FacesContext.getCurrentInstance()), message); } else { if (user!=null ) { if (validateFileUserName(FacesContext.getCurrentInstance(),fileUserInputText, newFileUser)) { this.editStudyPermissions.addFileUser(user.getId()); newFileUser=""; } } else { this.editStudyPermissions.addFileGroup(group.getId()); newFileUser=""; } } } if (!StringUtil.isEmpty(this.selectFilePermission)) { editStudyPermissions.setFileRestriction(selectFilePermission.equals("Restricted")); } } public void viewAllFiles(ActionEvent ae) { setViewCurrentFiles(false); editStudyPermissions.setCurrentVersionFiles(false); } public void viewCurrentFiles(ActionEvent ae) { setViewCurrentFiles(true); editStudyPermissions.setCurrentVersionFiles(true); } public void removeStudyUserGroup(ActionEvent ae) { editStudyPermissions.removeStudyPermissions(); } public void removeFilePermissions(ActionEvent ae) { editStudyPermissions.removeFilePermissions(); } public void updateRequests(ActionEvent ae) { HttpServletRequest request = (HttpServletRequest)this.getExternalContext().getRequest(); String hostName=request.getLocalName(); int port = request.getLocalPort(); String portStr=""; if (port!=80) { portStr=":"+port; } String studyUrl = "http://"+hostName+portStr+request.getContextPath()+getVDCRequestBean().getCurrentVDCURL()+"/faces/study/StudyPage.xhtml?studyId="+studyId+"&tab=files"; editStudyPermissions.updateRequests(studyUrl); } /** * Holds value of property studyId. */ private Long studyId; /** * Getter for property studyId. * @return Value of property studyId. */ public Long getStudyId() { return this.studyId; } /** * Setter for property studyId. * @param studyId New value of property studyId. */ public void setStudyId(Long studyId) { this.studyId = studyId; } public String save() { Long studyId = editStudyPermissions.getStudy().getId(); this.editStudyPermissions.save(); return "/study/StudyPage?faces-redirect=true&studyId=" + studyId + "&versionNumber=" + getVDCRequestBean().getStudyVersionNumber() + "&vdcId=" + getVDCRequestBean().getCurrentVDCId(); } public boolean validateStudyUserName(FacesContext context, UIComponent toValidate, Object value) { String userNameStr = (String) value; String msg=null; boolean valid=true; VDCUser user = userService.findByUserName(userNameStr); if (user==null) { valid=false; msg = "User not found."; } if (valid) { for (Iterator it = this.editStudyPermissions.getStudyPermissions().iterator(); it.hasNext();) { PermissionBean pb = (PermissionBean)it.next(); if (pb.getUser()!=null && pb.getUser().getId().equals(user.getId())) { valid=false; msg = "User already in study permissions list."; break; } } } if (valid) { if ( !editStudyPermissions.getStudy().isStudyRestrictedForUser(user,null)) { valid=false; msg= "This user already has a Network or Dataverse Role that allows access to the study."; } } if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage(msg); context.addMessage(toValidate.getClientId(context), message); } return valid; } public boolean validateStudyGroupName(FacesContext context, UIComponent toValidate, Object value) { String groupNameStr = (String) value; String msg=null; boolean valid=true; UserGroup group = this.groupService.findByName(groupNameStr); if (group==null) { valid=false; msg = "Group not found."; } if (valid) { for (Iterator it = this.editStudyPermissions.getStudyPermissions().iterator(); it.hasNext();) { PermissionBean pb = (PermissionBean)it.next(); if (pb.getGroup()!=null && pb.getGroup().getId().equals(group.getId())) { valid=false; msg = "Group already in study permissions list."; break; } } } if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage(msg); context.addMessage(toValidate.getClientId(context), message); } return valid; } public boolean validateFileUserName(FacesContext context, UIComponent toValidate, Object value) { String userNameStr = (String) value; String msg=null; boolean valid=true; VDCUser user = userService.findByUserName(userNameStr); if (user==null) { valid=false; msg = "User not found."; } if (valid) { if (user.getNetworkRole()!=null && user.getNetworkRole().getName().equals(NetworkRoleServiceBean.ADMIN)) { valid=false; msg= "User is a Network Administrator and already has all privileges to this dataverse."; } } if (valid) { VDCRole vdcRole = user.getVDCRole(this.getVDCRequestBean().getCurrentVDC()); if ((vdcRole!=null && (vdcRole.getRole().getName().equals(RoleServiceBean.ADMIN) || vdcRole.getRole().getName().equals(RoleServiceBean.CURATOR))) || editStudyPermissions.getStudy().getCreator().getId().equals(user.getId())) { valid=false; msg= "User already has a Network or Dataverse Role that allows access to the restricted files."; } } if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage(msg); context.addMessage(toValidate.getClientId(context), message); } return valid; } public boolean validateFileGroupName(FacesContext context, UIComponent toValidate, Object value) { String groupNameStr = (String) value; String msg=null; boolean valid=true; UserGroup group = this.groupService.findByName(groupNameStr); if (group==null) { valid=false; msg = "Group not found."; } if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage(msg); context.addMessage(toValidate.getClientId(context), message); } return valid; } /** * Holds value of property studyUserInputText. */ private HtmlInputText studyUserInputText; /** * Getter for property studyUserInputText. * @return Value of property studyUserInputText. */ public HtmlInputText getStudyUserInputText() { return this.studyUserInputText; } /** * Setter for property studyUserInputText. * @param studyUserInputText New value of property studyUserInputText. */ public void setStudyUserInputText(HtmlInputText studyUserInputText) { this.studyUserInputText = studyUserInputText; } /** * Holds value of property fileUserInputText. */ private HtmlInputText fileUserInputText; /** * Getter for property fileUserInputText. * @return Value of property fileUserInputText. */ public HtmlInputText getFileUserInputText() { return this.fileUserInputText; } /** * Setter for property fileUserInputText. * @param fileUserInputText New value of property fileUserInputText. */ public void setFileUserInputText(HtmlInputText fileUserInputText) { this.fileUserInputText = fileUserInputText; } /** * Holds value of property selectFilePermission. */ private String selectFilePermission; /** * Getter for property selectFilePermission. * @return Value of property selectFilePermission. */ public String getSelectFilePermission() { return this.selectFilePermission; } /** * Setter for property selectFilePermission. * @param selectFilePermission New value of property selectFilePermission. */ public void setSelectFilePermission(String selectFilePermission) { this.selectFilePermission = selectFilePermission; } /** * Wrapper for Study object used to display Study Title information */ private StudyUI studyUI; public StudyUI getStudyUI() { return studyUI; } public void setStudyUI(StudyUI studyUI) { this.studyUI = studyUI; } public String cancel() { - String forwardPage="viewStudy"; editStudyPermissions.cancel(); this.sessionRemove(editStudyPermissions.getClass().getName()); getVDCRequestBean().setStudyId(studyId); - return forwardPage; + return "/study/StudyPage?faces-redirect=true&studyId=" + studyId + "&versionNumber=" + getVDCRequestBean().getStudyVersionNumber() + "&vdcId=" + getVDCRequestBean().getCurrentVDCId(); + } }
false
false
null
null
diff --git a/src/com/matburt/mobileorg/Synchronizers/Synchronizer.java b/src/com/matburt/mobileorg/Synchronizers/Synchronizer.java index 06da1c1..b7a7f54 100644 --- a/src/com/matburt/mobileorg/Synchronizers/Synchronizer.java +++ b/src/com/matburt/mobileorg/Synchronizers/Synchronizer.java @@ -1,267 +1,280 @@ package com.matburt.mobileorg.Synchronizers; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import com.matburt.mobileorg.Error.ReportableError; import com.matburt.mobileorg.MobileOrgDatabase; import com.matburt.mobileorg.R; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; abstract public class Synchronizer { public MobileOrgDatabase appdb = null; public SharedPreferences appSettings = null; public Context rootContext = null; public static final String LT = "MobileOrg"; public Resources r; final private int BUFFER_SIZE = 23 * 1024; public abstract void pull() throws NotFoundException, ReportableError; public abstract void push() throws NotFoundException, ReportableError; public abstract boolean checkReady(); public void close() { if (this.appdb != null) this.appdb.close(); } public BufferedReader fetchOrgFile(String orgPath) throws NotFoundException, ReportableError{ return null; } public void fetchAndSaveOrgFile(String orgPath, String destPath) throws ReportableError { BufferedReader reader = this.fetchOrgFile(orgPath); BufferedWriter writer = this.getWriteHandle(destPath); + if (writer == null) { + throw new ReportableError( + r.getString(R.string.error_file_write, destPath), + e); + } + + + if (reader == null) { + throw new ReportableError( + r.getString(R.string.error_file_read, orgPath), + e); + } + char[] baf = new char[BUFFER_SIZE]; int actual = 0; try { while (actual != -1) { writer.write(baf, 0, actual); actual = reader.read(baf, 0, BUFFER_SIZE); } writer.close(); } catch (java.io.IOException e) { throw new ReportableError( r.getString(R.string.error_file_write, orgPath), e); } } public String fetchOrgFileString(String orgPath) throws ReportableError { BufferedReader reader = this.fetchOrgFile(orgPath); if (reader == null) { return ""; } String fileContents = ""; String thisLine = ""; try { while ((thisLine = reader.readLine()) != null) { fileContents += thisLine + "\n"; } } catch (java.io.IOException e) { throw new ReportableError( r.getString(R.string.error_file_read, orgPath), e); } return fileContents; } BufferedWriter getWriteHandle(String localRelPath) throws ReportableError { String storageMode = this.appSettings.getString("storageMode", ""); BufferedWriter writer = null; if (storageMode.equals("internal") || storageMode == null) { FileOutputStream fs; try { String normalized = localRelPath.replace("/", "_"); fs = this.rootContext.openFileOutput(normalized, Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(fs)); } catch (java.io.FileNotFoundException e) { Log.e(LT, "Caught FNFE trying to open file " + localRelPath); throw new ReportableError( r.getString(R.string.error_file_not_found, localRelPath), e); } catch (java.io.IOException e) { Log.e(LT, "IO Exception initializing writer on file " + localRelPath); throw new ReportableError( r.getString(R.string.error_file_not_found, localRelPath), e); } } else if (storageMode.equals("sdcard")) { try { File root = Environment.getExternalStorageDirectory(); File morgDir = new File(root, "mobileorg"); morgDir.mkdir(); if (morgDir.canWrite()){ File orgFileCard = new File(morgDir, localRelPath); FileWriter orgFWriter = new FileWriter(orgFileCard, false); writer = new BufferedWriter(orgFWriter); } else { Log.e(LT, "Write permission denied on " + localRelPath); throw new ReportableError( r.getString(R.string.error_file_permissions, morgDir.getAbsolutePath()), null); } } catch (java.io.IOException e) { Log.e(LT, "IO Exception initializing writer on sdcard file: " + localRelPath); throw new ReportableError( "IO Exception initializing writer on sdcard file", e); } } else { Log.e(LT, "Unknown storage mechanism " + storageMode); throw new ReportableError( r.getString(R.string.error_local_storage_method_unknown, storageMode), null); } return writer; } BufferedReader getReadHandle(String localRelPath) throws ReportableError { String storageMode = this.appSettings.getString("storageMode", ""); BufferedReader reader; if (storageMode.equals("internal") || storageMode == null) { FileInputStream fs; try { fs = rootContext.openFileInput(localRelPath); reader = new BufferedReader(new InputStreamReader(fs)); } catch (java.io.FileNotFoundException e) { Log.i(LT, "Did not find " + localRelPath + " file, not pushing."); return null; } } else if (storageMode.equals("sdcard")) { try { File root = Environment.getExternalStorageDirectory(); File morgDir = new File(root, "mobileorg"); File morgFile = new File(morgDir, localRelPath); if (!morgFile.exists()) { Log.i(LT, "Did not find " + localRelPath + " file, not pushing."); return null; } FileReader orgFReader = new FileReader(morgFile); reader = new BufferedReader(orgFReader); } catch (java.io.IOException e) { throw new ReportableError( r.getString(R.string.error_file_read, localRelPath), e); } } else { throw new ReportableError( r.getString(R.string.error_local_storage_method_unknown, storageMode), null); } return reader; } void removeFile(String filePath) { this.appdb.removeFile(filePath); String storageMode = this.appSettings.getString("storageMode", ""); if (storageMode.equals("internal") || storageMode == null) { this.rootContext.deleteFile(filePath); } else if (storageMode.equals("sdcard")) { File root = Environment.getExternalStorageDirectory(); File morgDir = new File(root, "mobileorg"); File morgFile = new File(morgDir, filePath); morgFile.delete(); } } HashMap<String, String> getOrgFilesFromMaster(String master) { Pattern getOrgFiles = Pattern.compile("\\[file:(.*?)\\]\\[(.*?)\\]\\]"); Matcher m = getOrgFiles.matcher(master); HashMap<String, String> allOrgFiles = new HashMap<String, String>(); while (m.find()) { Log.i(LT, "Found org file: " + m.group(2)); allOrgFiles.put(m.group(2), m.group(1)); } return allOrgFiles; } HashMap<String, String> getChecksums(String master) { HashMap<String, String> chksums = new HashMap<String, String>(); for (String eachLine : master.split("[\\n\\r]+")) { if (TextUtils.isEmpty(eachLine)) continue; String[] chksTuple = eachLine.split("\\s+"); chksums.put(chksTuple[1], chksTuple[0]); } return chksums; } ArrayList<HashMap<String, Boolean>> getTodos(String master) { Pattern getTodos = Pattern.compile("#\\+TODO:\\s+([\\s\\w-]*)(\\| ([\\s\\w-]*))*"); Matcher m = getTodos.matcher(master); ArrayList<HashMap<String, Boolean>> todoList = new ArrayList<HashMap<String, Boolean>>(); while (m.find()) { String lastTodo = ""; HashMap<String, Boolean> holding = new HashMap<String, Boolean>(); Boolean isDone = false; for (int idx = 1; idx <= m.groupCount(); idx++) { if (m.group(idx) != null && m.group(idx).length() > 0) { if (m.group(idx).indexOf("|") != -1) { isDone = true; continue; } String[] grouping = m.group(idx).split("\\s+"); for (int jdx = 0; jdx < grouping.length; jdx++) { lastTodo = grouping[jdx].trim(); holding.put(grouping[jdx].trim(), isDone); } } } if (!isDone) { holding.put(lastTodo, true); } todoList.add(holding); } return todoList; } ArrayList<ArrayList<String>> getPriorities(String master) { Pattern getPriorities = Pattern.compile("#\\+ALLPRIORITIES:\\s+([A-Z\\s]*)"); Matcher t = getPriorities.matcher(master); ArrayList<ArrayList<String>> priorityList = new ArrayList<ArrayList<String>>(); while (t.find()) { ArrayList<String> holding = new ArrayList<String>(); if (t.group(1) != null && t.group(1).length() > 0) { String[] grouping = t.group(1).split("\\s+"); for (int jdx = 0; jdx < grouping.length; jdx++) { holding.add(grouping[jdx].trim()); } } priorityList.add(holding); } return priorityList; } }
true
false
null
null
diff --git a/src/com/android/camera/ActivityBase.java b/src/com/android/camera/ActivityBase.java index 22a0edf7..0df96d7a 100644 --- a/src/com/android/camera/ActivityBase.java +++ b/src/com/android/camera/ActivityBase.java @@ -1,793 +1,795 @@ /* * 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.camera; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.hardware.Camera.Parameters; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import com.android.camera.ui.CameraPicker; import com.android.camera.ui.LayoutChangeNotifier; import com.android.camera.ui.PopupManager; import com.android.camera.ui.RotateImageView; import com.android.gallery3d.app.AbstractGalleryActivity; import com.android.gallery3d.app.AppBridge; import com.android.gallery3d.app.GalleryActionBar; import com.android.gallery3d.app.PhotoPage; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.ui.ScreenNail; import com.android.gallery3d.util.MediaSetUtils; import java.io.File; /** * Superclass of Camera and VideoCamera activities. */ public abstract class ActivityBase extends AbstractGalleryActivity implements LayoutChangeNotifier.Listener { private static final String TAG = "ActivityBase"; private static final int CAMERA_APP_VIEW_TOGGLE_TIME = 100; // milliseconds private static final String ACTION_DELETE_PICTURE = "com.android.gallery3d.action.DELETE_PICTURE"; private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE = "android.media.action.STILL_IMAGE_CAMERA_SECURE"; public static final String ACTION_IMAGE_CAPTURE_SECURE = "android.media.action.IMAGE_CAPTURE_SECURE"; // The intent extra for camera from secure lock screen. True if the gallery // should only show newly captured pictures. sSecureAlbumId does not // increment. This is used when switching between camera, camcorder, and // panorama. If the extra is not set, it is in the normal camera mode. public static final String SECURE_CAMERA_EXTRA = "secure_camera"; private int mResultCodeForTesting; private Intent mResultDataForTesting; private OnScreenHint mStorageHint; private View mSingleTapArea; // The bitmap of the last captured picture thumbnail and the URI of the // original picture. protected Thumbnail mThumbnail; protected int mThumbnailViewWidth; // layout width of the thumbnail protected AsyncTask<Void, Void, Thumbnail> mLoadThumbnailTask; // An imageview showing the last captured picture thumbnail. protected RotateImageView mThumbnailView; protected CameraPicker mCameraPicker; protected boolean mOpenCameraFail; protected boolean mCameraDisabled; protected CameraManager.CameraProxy mCameraDevice; protected Parameters mParameters; // The activity is paused. The classes that extend this class should set // mPaused the first thing in onResume/onPause. protected boolean mPaused; protected GalleryActionBar mActionBar; // multiple cameras support protected int mNumberOfCameras; protected int mCameraId; // The activity is going to switch to the specified camera id. This is // needed because texture copy is done in GL thread. -1 means camera is not // switching. protected int mPendingSwitchCameraId = -1; protected MyAppBridge mAppBridge; protected ScreenNail mCameraScreenNail; // This shows camera preview. // The view containing only camera related widgets like control panel, // indicator bar, focus indicator and etc. protected View mCameraAppView; protected boolean mShowCameraAppView = true; private Animation mCameraAppViewFadeIn; private Animation mCameraAppViewFadeOut; // Secure album id. This should be incremented every time the camera is // launched from the secure lock screen. The id should be the same when // switching between camera, camcorder, and panorama. protected static int sSecureAlbumId; // True if the camera is started from secure lock screen. protected boolean mSecureCamera; private static boolean sFirstStartAfterScreenOn = true; private long mStorageSpace = Storage.LOW_STORAGE_THRESHOLD; private static final int UPDATE_STORAGE_HINT = 0; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_STORAGE_HINT: updateStorageHint(); return; } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING) || action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { updateStorageSpaceAndHint(); } } }; private boolean mUpdateThumbnailDelayed; private IntentFilter mDeletePictureFilter = new IntentFilter(ACTION_DELETE_PICTURE); private BroadcastReceiver mDeletePictureReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (mShowCameraAppView) { getLastThumbnailUncached(); } else { mUpdateThumbnailDelayed = true; } } }; // close activity when screen turns off private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; private static BroadcastReceiver sScreenOffReceiver; private static class ScreenOffReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { sFirstStartAfterScreenOn = true; } } public static boolean isFirstStartAfterScreenOn() { return sFirstStartAfterScreenOn; } public static void resetFirstStartAfterScreenOn() { sFirstStartAfterScreenOn = false; } protected class CameraOpenThread extends Thread { @Override public void run() { try { mCameraDevice = Util.openCamera(ActivityBase.this, mCameraId); mParameters = mCameraDevice.getParameters(); } catch (CameraHardwareException e) { mOpenCameraFail = true; } catch (CameraDisabledException e) { mCameraDisabled = true; } } } @Override public void onCreate(Bundle icicle) { super.disableToggleStatusBar(); // Set a theme with action bar. It is not specified in manifest because // we want to hide it by default. setTheme must happen before // setContentView. // // This must be set before we call super.onCreate(), where the window's // background is removed. setTheme(R.style.Theme_Gallery); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); if (ApiHelper.HAS_ACTION_BAR) { requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } else { requestWindowFeature(Window.FEATURE_NO_TITLE); } // Check if this is in the secure camera mode. Intent intent = getIntent(); String action = intent.getAction(); if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)) { mSecureCamera = true; // Use a new album when this is started from the lock screen. sSecureAlbumId++; } else if (ACTION_IMAGE_CAPTURE_SECURE.equals(action)) { mSecureCamera = true; } else { mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false); } if (mSecureCamera) { IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); registerReceiver(mScreenOffReceiver, filter); if (sScreenOffReceiver == null) { sScreenOffReceiver = new ScreenOffReceiver(); getApplicationContext().registerReceiver(sScreenOffReceiver, filter); } } super.onCreate(icicle); } public boolean isPanoramaActivity() { return false; } @Override protected void onResume() { super.onResume(); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.registerReceiver(mDeletePictureReceiver, mDeletePictureFilter); installIntentFilter(); if(updateStorageHintOnResume()) { updateStorageSpace(); mHandler.sendEmptyMessageDelayed(UPDATE_STORAGE_HINT, 200); } } @Override protected void onPause() { super.onPause(); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.unregisterReceiver(mDeletePictureReceiver); saveThumbnailToFile(); if (mLoadThumbnailTask != null) { mLoadThumbnailTask.cancel(true); mLoadThumbnailTask = null; } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } unregisterReceiver(mReceiver); } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); // getActionBar() should be after setContentView mActionBar = new GalleryActionBar(this); mActionBar.hide(); } @Override public boolean onSearchRequested() { return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Prevent software keyboard or voice search from showing up. if (keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_MENU) { if (event.isLongPress()) return true; } if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) { return true; } return super.onKeyUp(keyCode, event); } protected void setResultEx(int resultCode) { mResultCodeForTesting = resultCode; setResult(resultCode); } protected void setResultEx(int resultCode, Intent data) { mResultCodeForTesting = resultCode; mResultDataForTesting = data; setResult(resultCode, data); } public int getResultCode() { return mResultCodeForTesting; } public Intent getResultData() { return mResultDataForTesting; } @Override protected void onDestroy() { PopupManager.removeInstance(this); if (mSecureCamera) unregisterReceiver(mScreenOffReceiver); super.onDestroy(); } protected void installIntentFilter() { // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); } protected void updateStorageSpace() { mStorageSpace = Storage.getAvailableSpace(); } protected long getStorageSpace() { return mStorageSpace; } protected void updateStorageSpaceAndHint() { updateStorageSpace(); updateStorageHint(mStorageSpace); } protected void updateStorageHint() { updateStorageHint(mStorageSpace); } protected boolean updateStorageHintOnResume() { return true; } protected void updateStorageHint(long storageSpace) { String message = null; if (storageSpace == Storage.UNAVAILABLE) { message = getString(R.string.no_storage); } else if (storageSpace == Storage.PREPARING) { message = getString(R.string.preparing_sd); } else if (storageSpace == Storage.UNKNOWN_SIZE) { message = getString(R.string.access_sd_fail); } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD) { message = getString(R.string.spaceIsLow_content); } if (message != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, message); } else { mStorageHint.setText(message); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } protected void updateThumbnailView() { if (mThumbnail != null && mThumbnailView != null) { mThumbnailView.setBitmap(mThumbnail.getBitmap()); mThumbnailView.setVisibility(View.VISIBLE); } else if (mThumbnailView != null) { mThumbnailView.setBitmap(null); mThumbnailView.setVisibility(View.GONE); } } protected void getLastThumbnail() { mThumbnail = ThumbnailHolder.getLastThumbnail(getContentResolver()); // Suppose users tap the thumbnail view, go to the gallery, delete the // image, and coming back to the camera. Thumbnail file will be invalid. // Since the new thumbnail will be loaded in another thread later, the // view should be set to gone to prevent from opening the invalid image. updateThumbnailView(); if (mThumbnail == null && !mSecureCamera) { mLoadThumbnailTask = new LoadThumbnailTask(true).execute(); } } protected void getLastThumbnailUncached() { if (mSecureCamera) { // Check if the thumbnail is valid. if (mThumbnail != null && !Util.isUriValid( mThumbnail.getUri(), getContentResolver())) { mThumbnail = null; updateThumbnailView(); } } else { if (mLoadThumbnailTask != null) mLoadThumbnailTask.cancel(true); mLoadThumbnailTask = new LoadThumbnailTask(false).execute(); } } private class LoadThumbnailTask extends AsyncTask<Void, Void, Thumbnail> { private boolean mLookAtCache; public LoadThumbnailTask(boolean lookAtCache) { mLookAtCache = lookAtCache; } @Override protected Thumbnail doInBackground(Void... params) { // Load the thumbnail from the file. ContentResolver resolver = getContentResolver(); Thumbnail t = null; if (mLookAtCache) { t = Thumbnail.getLastThumbnailFromFile(getFilesDir(), resolver); } if (isCancelled()) return null; if (t == null) { Thumbnail result[] = new Thumbnail[1]; // Load the thumbnail from the media provider. int code = Thumbnail.getLastThumbnailFromContentResolver( resolver, result); switch (code) { case Thumbnail.THUMBNAIL_FOUND: return result[0]; case Thumbnail.THUMBNAIL_NOT_FOUND: return null; case Thumbnail.THUMBNAIL_DELETED: cancel(true); return null; } } return t; } @Override protected void onPostExecute(Thumbnail thumbnail) { if (isCancelled()) return; mThumbnail = thumbnail; updateThumbnailView(); } } protected void gotoGallery() { // Move the next picture with capture animation. "1" means next. mAppBridge.switchWithCaptureAnimation(1); } protected void saveThumbnailToFile() { if (mThumbnail != null && !mThumbnail.fromFile()) { new SaveThumbnailTask().execute(mThumbnail); } } private class SaveThumbnailTask extends AsyncTask<Thumbnail, Void, Void> { @Override protected Void doInBackground(Thumbnail... params) { final int n = params.length; final File filesDir = getFilesDir(); for (int i = 0; i < n; i++) { params[i].saveLastThumbnailToFile(filesDir); } return null; } } // Call this after setContentView. - protected void createCameraScreenNail(boolean getPictures) { + public ScreenNail createCameraScreenNail(boolean getPictures) { mCameraAppView = findViewById(R.id.camera_app_root); Bundle data = new Bundle(); String path; if (getPictures) { if (mSecureCamera) { path = "/secure/all/" + sSecureAlbumId; } else { path = "/local/all/" + MediaSetUtils.CAMERA_BUCKET_ID; } } else { path = "/local/all/0"; // Use 0 so gallery does not show anything. } data.putString(PhotoPage.KEY_MEDIA_SET_PATH, path); data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path); data.putBoolean(PhotoPage.KEY_SHOW_WHEN_LOCKED, mSecureCamera); // Send an AppBridge to gallery to enable the camera preview. mAppBridge = new MyAppBridge(); data.putParcelable(PhotoPage.KEY_APP_BRIDGE, mAppBridge); if (getStateManager().getStateCount() == 0) { getStateManager().startState(PhotoPage.class, data); } else { getStateManager().switchState(getStateManager().getTopState(), PhotoPage.class, data); } mCameraScreenNail = mAppBridge.getCameraScreenNail(); + return mCameraScreenNail; } // Call this after setContentView. - protected void reuseCameraScreenNail(boolean getPictures) { + protected ScreenNail reuseCameraScreenNail(boolean getPictures) { mCameraAppView = findViewById(R.id.camera_app_root); Bundle data = new Bundle(); String path; if (getPictures) { if (mSecureCamera) { path = "/secure/all/" + sSecureAlbumId; } else { path = "/local/all/" + MediaSetUtils.CAMERA_BUCKET_ID; } } else { path = "/local/all/0"; // Use 0 so gallery does not show anything. } data.putString(PhotoPage.KEY_MEDIA_SET_PATH, path); data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path); data.putBoolean(PhotoPage.KEY_SHOW_WHEN_LOCKED, mSecureCamera); // Send an AppBridge to gallery to enable the camera preview. if (mAppBridge == null) { mAppBridge = new MyAppBridge(); } data.putParcelable(PhotoPage.KEY_APP_BRIDGE, mAppBridge); if (getStateManager().getStateCount() == 0) { getStateManager().startState(PhotoPage.class, data); } mCameraScreenNail = mAppBridge.getCameraScreenNail(); + return mCameraScreenNail; } private class HideCameraAppView implements Animation.AnimationListener { @Override public void onAnimationEnd(Animation animation) { // We cannot set this as GONE because we want to receive the // onLayoutChange() callback even when we are invisible. mCameraAppView.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } } protected void updateCameraAppView() { // Initialize the animation. if (mCameraAppViewFadeIn == null) { mCameraAppViewFadeIn = new AlphaAnimation(0f, 1f); mCameraAppViewFadeIn.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME); mCameraAppViewFadeIn.setInterpolator(new DecelerateInterpolator()); mCameraAppViewFadeOut = new AlphaAnimation(1f, 0f); mCameraAppViewFadeOut.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME); mCameraAppViewFadeOut.setInterpolator(new DecelerateInterpolator()); mCameraAppViewFadeOut.setAnimationListener(new HideCameraAppView()); } if (mShowCameraAppView) { mCameraAppView.setVisibility(View.VISIBLE); // The "transparent region" is not recomputed when a sibling of // SurfaceView changes visibility (unless it involves GONE). It's // been broken since 1.0. Call requestLayout to work around it. mCameraAppView.requestLayout(); mCameraAppView.startAnimation(mCameraAppViewFadeIn); } else { mCameraAppView.startAnimation(mCameraAppViewFadeOut); } } protected void onFullScreenChanged(boolean full) { if (mShowCameraAppView == full) return; mShowCameraAppView = full; if (mPaused || isFinishing()) return; updateCameraAppView(); // If we received DELETE_PICTURE broadcasts while the Camera UI is // hidden, we update the thumbnail now. if (full && mUpdateThumbnailDelayed) { getLastThumbnailUncached(); mUpdateThumbnailDelayed = false; } } @Override public GalleryActionBar getGalleryActionBar() { return mActionBar; } // Preview frame layout has changed. @Override public void onLayoutChange(View v, int left, int top, int right, int bottom) { if (mAppBridge == null) return; int width = right - left; int height = bottom - top; if (ApiHelper.HAS_SURFACE_TEXTURE) { CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail; if (Util.getDisplayRotation(this) % 180 == 0) { screenNail.setPreviewFrameLayoutSize(width, height); } else { // Swap the width and height. Camera screen nail draw() is based on // natural orientation, not the view system orientation. screenNail.setPreviewFrameLayoutSize(height, width); } } // Find out the coordinates of the preview frame relative to GL // root view. View root = (View) getGLRoot(); int[] rootLocation = new int[2]; int[] viewLocation = new int[2]; root.getLocationInWindow(rootLocation); v.getLocationInWindow(viewLocation); int l = viewLocation[0] - rootLocation[0]; int t = viewLocation[1] - rootLocation[1]; int r = l + width; int b = t + height; Rect frame = new Rect(l, t, r, b); Log.d(TAG, "set CameraRelativeFrame as " + frame); mAppBridge.setCameraRelativeFrame(frame); } protected void setSingleTapUpListener(View singleTapArea) { mSingleTapArea = singleTapArea; } private boolean onSingleTapUp(int x, int y) { // Ignore if listener is null or the camera control is invisible. if (mSingleTapArea == null || !mShowCameraAppView) return false; int[] relativeLocation = Util.getRelativeLocation((View) getGLRoot(), mSingleTapArea); x -= relativeLocation[0]; y -= relativeLocation[1]; if (x >= 0 && x < mSingleTapArea.getWidth() && y >= 0 && y < mSingleTapArea.getHeight()) { onSingleTapUp(mSingleTapArea, x, y); return true; } return false; } protected void onSingleTapUp(View view, int x, int y) { } public void setSwipingEnabled(boolean enabled) { mAppBridge.setSwipingEnabled(enabled); } - protected void notifyScreenNailChanged() { + public void notifyScreenNailChanged() { mAppBridge.notifyScreenNailChanged(); } protected void onPreviewTextureCopied() { } protected void addSecureAlbumItemIfNeeded(boolean isVideo, Uri uri) { if (mSecureCamera) { int id = Integer.parseInt(uri.getLastPathSegment()); mAppBridge.addSecureAlbumItem(isVideo, id); } } public boolean isSecureCamera() { return mSecureCamera; } ////////////////////////////////////////////////////////////////////////// // The is the communication interface between the Camera Application and // the Gallery PhotoPage. ////////////////////////////////////////////////////////////////////////// class MyAppBridge extends AppBridge implements CameraScreenNail.Listener { @SuppressWarnings("hiding") private ScreenNail mCameraScreenNail; private Server mServer; @Override public ScreenNail attachScreenNail() { if (mCameraScreenNail == null) { if (ApiHelper.HAS_SURFACE_TEXTURE) { mCameraScreenNail = new CameraScreenNail(this); } else { Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper_picker_preview); mCameraScreenNail = new StaticBitmapScreenNail(b); } } return mCameraScreenNail; } @Override public void detachScreenNail() { mCameraScreenNail = null; } public ScreenNail getCameraScreenNail() { return mCameraScreenNail; } // Return true if the tap is consumed. @Override public boolean onSingleTapUp(int x, int y) { return ActivityBase.this.onSingleTapUp(x, y); } // This is used to notify that the screen nail will be drawn in full screen // or not in next draw() call. @Override public void onFullScreenChanged(boolean full) { ActivityBase.this.onFullScreenChanged(full); } @Override public void requestRender() { getGLRoot().requestRender(); } @Override public void onPreviewTextureCopied() { ActivityBase.this.onPreviewTextureCopied(); } @Override public void setServer(Server s) { mServer = s; } @Override public boolean isPanorama() { return ActivityBase.this.isPanoramaActivity(); } @Override public boolean isStaticCamera() { return !ApiHelper.HAS_SURFACE_TEXTURE; } public void addSecureAlbumItem(boolean isVideo, int id) { if (mServer != null) mServer.addSecureAlbumItem(isVideo, id); } private void setCameraRelativeFrame(Rect frame) { if (mServer != null) mServer.setCameraRelativeFrame(frame); } private void switchWithCaptureAnimation(int offset) { if (mServer != null) mServer.switchWithCaptureAnimation(offset); } private void setSwipingEnabled(boolean enabled) { if (mServer != null) mServer.setSwipingEnabled(enabled); } private void notifyScreenNailChanged() { if (mServer != null) mServer.notifyScreenNailChanged(); } } }
false
false
null
null
diff --git a/src/Tiger.java b/src/Tiger.java index bc43cb0..a35e957 100644 --- a/src/Tiger.java +++ b/src/Tiger.java @@ -1,164 +1,168 @@ import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import lexer.Lexer; import lexer.Token; import lexer.Token.Kind; import control.CommandLine; import control.Control; import parser.Parser; public class Tiger { public static void main(String[] args) { InputStream fstream; Parser parser; // /////////////////////////////////////////////////////// // handle command line arguments CommandLine cmd = new CommandLine(); String fname = cmd.scan(args); // ///////////////////////////////////////////////////// // to test the pretty printer on the "test/Fac.java" program if (control.Control.testFac) { System.out.println("Testing the Tiger compiler on Fac.java starting:"); ast.PrettyPrintVisitor pp = new ast.PrettyPrintVisitor(); ast.Fac.prog.accept(pp); // elaborate the given program, this step is necessary // for that it will annotate the AST with some // informations used by later phase. elaborator.ElaboratorVisitor elab = new elaborator.ElaboratorVisitor(); ast.Fac.prog.accept(elab); // Compile this program to C. System.out.println("code generation starting"); // code generation switch (control.Control.codegen) { case Bytecode: System.out.println("bytecode codegen"); codegen.bytecode.TranslateVisitor trans = new codegen.bytecode.TranslateVisitor(); ast.Fac.prog.accept(trans); codegen.bytecode.program.T bytecodeAst = trans.program; codegen.bytecode.PrettyPrintVisitor ppbc = new codegen.bytecode.PrettyPrintVisitor(); bytecodeAst.accept(ppbc); break; case C: System.out.println("C codegen"); codegen.C.TranslateVisitor transC = new codegen.C.TranslateVisitor(); ast.Fac.prog.accept(transC); codegen.C.program.T cAst = transC.program; codegen.C.PrettyPrintVisitor ppc = new codegen.C.PrettyPrintVisitor(); cAst.accept(ppc); break; + /* case Dalvik: codegen.dalvik.TranslateVisitor transDalvik = new codegen.dalvik.TranslateVisitor(); ast.Fac.prog.accept(transDalvik); codegen.dalvik.program.T dalvikAst = transDalvik.program; codegen.dalvik.PrettyPrintVisitor ppDalvik = new codegen.dalvik.PrettyPrintVisitor(); dalvikAst.accept(ppDalvik); break; case X86: // similar break; + */ default: break; } System.out.println("Testing the Tiger compiler on Fac.java finished."); System.exit(1); } if (fname == null) { cmd.usage(); return; } Control.fileName = fname; // ///////////////////////////////////////////////////// // it would be helpful to be able to test the lexer // independently. if (control.Control.testlexer) { System.out.println("Testing the lexer. All tokens:"); try { fstream = new BufferedInputStream(new FileInputStream(fname)); Lexer lexer = new Lexer(fname, fstream); Token token = lexer.nextToken(); while (token.kind != Kind.TOKEN_EOF) { System.out.println(token.toString()); token = lexer.nextToken(); } fstream.close(); } catch (Exception e) { e.printStackTrace(); } System.exit(1); } // ///////////////////////////////////////////////////////// // normal compilation phases. ast.program.T theAst = null; // parsing the file, get an AST. try { fstream = new BufferedInputStream(new FileInputStream(fname)); parser = new Parser(fname, fstream); theAst = parser.parse(); fstream.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // pretty printing the AST, if necessary if (control.Control.dumpAst) { ast.PrettyPrintVisitor pp = new ast.PrettyPrintVisitor(); theAst.accept(pp); } // elaborate the AST, report all possible errors. elaborator.ElaboratorVisitor elab = new elaborator.ElaboratorVisitor(); theAst.accept(elab); // code generation switch (control.Control.codegen) { case Bytecode: codegen.bytecode.TranslateVisitor trans = new codegen.bytecode.TranslateVisitor(); theAst.accept(trans); codegen.bytecode.program.T bytecodeAst = trans.program; codegen.bytecode.PrettyPrintVisitor ppbc = new codegen.bytecode.PrettyPrintVisitor(); bytecodeAst.accept(ppbc); break; case C: codegen.C.TranslateVisitor transC = new codegen.C.TranslateVisitor(); theAst.accept(transC); codegen.C.program.T cAst = transC.program; codegen.C.PrettyPrintVisitor ppc = new codegen.C.PrettyPrintVisitor(); cAst.accept(ppc); break; + /* case Dalvik: codegen.dalvik.TranslateVisitor transDalvik = new codegen.dalvik.TranslateVisitor(); theAst.accept(transDalvik); codegen.dalvik.program.T dalvikAst = transDalvik.program; codegen.dalvik.PrettyPrintVisitor ppDalvik = new codegen.dalvik.PrettyPrintVisitor(); dalvikAst.accept(ppDalvik); break; case X86: // similar break; + */ default: break; } // Lab3, exercise 6: add some glue code to // call gcc to compile the generated C or x86 // file, or call java to run the bytecode file, // or dalvik to run the dalvik bytecode. // Your code here: return; } } diff --git a/src/parser/Parser.java b/src/parser/Parser.java index 8af7c93..a443c34 100644 --- a/src/parser/Parser.java +++ b/src/parser/Parser.java @@ -1,533 +1,520 @@ package parser; import java.util.LinkedList; import java.util.NoSuchElementException; import lexer.Lexer; import lexer.Token; import lexer.Token.Kind; public class Parser { Lexer lexer; Token current; LinkedList<Token> savedToken; public Parser(String fname, java.io.InputStream fstream) { lexer = new Lexer(fname, fstream); current = lexer.nextToken(); savedToken = new LinkedList<Token>(); } // ///////////////////////////////////////////// // utility methods to connect the lexer // and the parser. private void advance() { // changed a little bit, we can save token now, use this tech to do look ahead Token token; try { token = savedToken.removeFirst(); current = token; } catch (NoSuchElementException e) { current = lexer.nextToken(); } } private void saveToken(Token token) { savedToken.addFirst(token); } private void eatToken(Kind kind) { if (kind == current.kind) advance(); else { System.out.format("in line %d: ", lexer.lineno); //because we can save token, lineno maybe not accurate System.out.println("Expects: " + kind.toString()); System.out.println("But got: " + current.kind.toString()); System.exit(1); } } private void error(String hint) { System.out.format("Syntax error: hint: %s, line %d, current kind %s\n", hint, lexer.lineno, current.kind.toString()); //because we can save token, lineno maybe not accurate System.exit(1); return; } // //////////////////////////////////////////////////////////// // below are method for parsing. // A bunch of parsing methods to parse expressions. The messy // parts are to deal with precedence and associativity. // ExpList -> Exp ExpRest* // -> // ExpRest -> , Exp private LinkedList<ast.exp.T> parseExpList() { LinkedList<ast.exp.T> result = new LinkedList<ast.exp.T>(); if (current.kind == Kind.TOKEN_RPAREN) return result; result.add(parseExp()); while (current.kind == Kind.TOKEN_COMMER) { advance(); result.add(parseExp()); } return result; } // AtomExp -> (exp) // -> INTEGER_LITERAL // -> true // -> false // -> this // -> id // -> new int [exp] // -> new id () private ast.exp.T parseAtomExp() { ast.exp.T result = null; switch (current.kind) { case TOKEN_LPAREN: advance(); result = parseExp(); eatToken(Kind.TOKEN_RPAREN); return result; case TOKEN_NUM: result = new ast.exp.Num(Integer.valueOf(current.lexeme)); advance(); return result; case TOKEN_TRUE: advance(); return new ast.exp.True(); case TOKEN_FALSE: advance(); return new ast.exp.False(); case TOKEN_THIS: advance(); return new ast.exp.This(); case TOKEN_ID: result = new ast.exp.Id(current.lexeme); advance(); return result; case TOKEN_NEW: { advance(); switch (current.kind) { case TOKEN_INT: advance(); eatToken(Kind.TOKEN_LBRACK); result = parseExp(); eatToken(Kind.TOKEN_RBRACK); return new ast.exp.NewIntArray(result); case TOKEN_ID: result = new ast.exp.NewObject(current.lexeme); advance(); eatToken(Kind.TOKEN_LPAREN); eatToken(Kind.TOKEN_RPAREN); return result; default: error("in parseAtomExp, TOKEN_NEW case"); return null; } } default: error("in parseAtomExp, default case"); return null; } } // NotExp -> AtomExp // -> AtomExp .id (expList) // -> AtomExp [exp] // -> AtomExp .length private ast.exp.T parseNotExp() { ast.exp.T atomExp = parseAtomExp(); while (current.kind == Kind.TOKEN_DOT || current.kind == Kind.TOKEN_LBRACK) { if (current.kind == Kind.TOKEN_DOT) { advance(); if (current.kind == Kind.TOKEN_LENGTH) { advance(); - return; - } - eatToken(Kind.TOKEN_ID); - eatToken(Kind.TOKEN_LPAREN); - parseExpList(); - eatToken(Kind.TOKEN_RPAREN); - } else { - advance(); - parseExp(); - eatToken(Kind.TOKEN_RBRACK); - } - } - return; atomExp = new ast.exp.Length(atomExp); } else { String id = current.lexeme; eatToken(Kind.TOKEN_ID); eatToken(Kind.TOKEN_LPAREN); LinkedList<ast.exp.T> expList = parseExpList(); eatToken(Kind.TOKEN_RPAREN); atomExp = new ast.exp.Call(atomExp, id, expList); } } else { // must be TOKEN_LBRACK advance(); ast.exp.T exp = parseExp(); eatToken(Kind.TOKEN_RBRACK); atomExp = new ast.exp.ArraySelect(atomExp, exp); } } return atomExp; } // TimesExp -> ! TimesExp // -> NotExp private ast.exp.T parseTimesExp() { int nest = 0; while (current.kind == Kind.TOKEN_NOT) { // handle nested not exp like !!!exp nest += 1; advance(); } ast.exp.T notExp = parseNotExp(); for (int i = 0; i < nest; i++) notExp = new ast.exp.Not(notExp); return notExp; } // AddSubExp -> TimesExp * TimesExp // -> TimesExp private ast.exp.T parseAddSubExp() { ast.exp.T timesExp = parseTimesExp(); while (current.kind == Kind.TOKEN_TIMES) { advance(); timesExp = new ast.exp.Times(timesExp, parseTimesExp()); } return timesExp; } // LtExp -> AddSubExp + AddSubExp // -> AddSubExp - AddSubExp // -> AddSubExp private ast.exp.T parseLtExp() { ast.exp.T addSubExp = parseAddSubExp(); while (current.kind == Kind.TOKEN_ADD || current.kind == Kind.TOKEN_SUB) { if (current.kind == Kind.TOKEN_ADD) { advance(); addSubExp = new ast.exp.Add(addSubExp, parseAddSubExp()); } else { //must Kind.TOKEN_SUB advance(); addSubExp = new ast.exp.Sub(addSubExp, parseAddSubExp()); } } return addSubExp; } // AndExp -> LtExp < LtExp // -> LtExp private ast.exp.T parseAndExp() { ast.exp.T ltExp = parseLtExp();; while (current.kind == Kind.TOKEN_LT) { advance(); ltExp = new ast.exp.Lt(ltExp, parseLtExp()); } return ltExp; } // Exp -> AndExp && AndExp // -> AndExp private ast.exp.T parseExp() { ast.exp.T andExp = parseAndExp(); while (current.kind == Kind.TOKEN_AND) { advance(); andExp = new ast.exp.And(andExp, parseAndExp()); } return andExp; } // Statement -> { Statement* } // -> if ( Exp ) Statement else Statement // -> while ( Exp ) Statement // -> System.out.println ( Exp ) ; // -> id = Exp ; // -> id [ Exp ]= Exp ; private ast.stm.T parseStatement() { switch (current.kind) { case TOKEN_LBRACE: advance(); LinkedList<ast.stm.T> statements = parseStatements(); eatToken(Kind.TOKEN_RBRACE); return new ast.stm.Block(statements); case TOKEN_IF: advance(); eatToken(Kind.TOKEN_LPAREN); ast.exp.T condition = parseExp(); eatToken(Kind.TOKEN_RPAREN); ast.stm.T if_body = parseStatement(); eatToken(Kind.TOKEN_ELSE); ast.stm.T else_body = parseStatement(); return new ast.stm.If(condition, if_body, else_body); case TOKEN_WHILE: advance(); eatToken(Kind.TOKEN_LPAREN); ast.exp.T cond = parseExp(); eatToken(Kind.TOKEN_RPAREN); ast.stm.T body = parseStatement(); return new ast.stm.While(cond, body); case TOKEN_SYSTEM: advance(); eatToken(Kind.TOKEN_DOT); eatToken(Kind.TOKEN_OUT); eatToken(Kind.TOKEN_DOT); eatToken(Kind.TOKEN_PRINTLN); eatToken(Kind.TOKEN_LPAREN); ast.exp.T exp = parseExp(); eatToken(Kind.TOKEN_RPAREN); eatToken(Kind.TOKEN_SEMI); return new ast.stm.Print(exp); case TOKEN_ID: String id = current.lexeme; advance(); if (current.kind == Kind.TOKEN_ASSIGN) { advance(); ast.exp.T exp1 = parseExp(); eatToken(Kind.TOKEN_SEMI); return new ast.stm.Assign(id, exp1); } else if (current.kind == Kind.TOKEN_LBRACK) { advance(); ast.exp.T index = parseExp(); eatToken(Kind.TOKEN_RBRACK); eatToken(Kind.TOKEN_ASSIGN); ast.exp.T exp2 = parseExp(); eatToken(Kind.TOKEN_SEMI); return new ast.stm.AssignArray(id, index, exp2); } else { error("in parseStatement, TOKEN_ID case"); return null; } default: error("in parseStatement, default case"); return null; } } // Statements -> Statement Statements // -> private LinkedList<ast.stm.T> parseStatements() { LinkedList<ast.stm.T> result = new LinkedList<ast.stm.T>(); while (current.kind == Kind.TOKEN_LBRACE || current.kind == Kind.TOKEN_IF || current.kind == Kind.TOKEN_WHILE || current.kind == Kind.TOKEN_SYSTEM || current.kind == Kind.TOKEN_ID) { result.add(parseStatement()); } return result; } // Type -> int [] // -> boolean // -> int // -> id private ast.type.T parseType() { switch (current.kind) { case TOKEN_INT: advance(); if (current.kind == Kind.TOKEN_LBRACK) { advance(); eatToken(Kind.TOKEN_RBRACK); return new ast.type.IntArray(); } else return new ast.type.Int(); case TOKEN_BOOLEAN: advance(); return new ast.type.Boolean(); case TOKEN_ID:// class type String id = current.lexeme; advance(); return new ast.type.Class(id); default: error("in parseType, default case"); return null; } } // VarDecl -> Type id ; private ast.dec.T parseVarDecl() { // to parse the "Type" nonterminal in this method, instead of writing // a fresh one. ast.type.T type = parseType(); String id = current.lexeme; eatToken(Kind.TOKEN_ID); eatToken(Kind.TOKEN_SEMI); return new ast.dec.Dec(type, id); } // VarDecls -> VarDecl VarDecls // -> private LinkedList<ast.dec.T> parseVarDecls() { LinkedList<ast.dec.T> result = new LinkedList<ast.dec.T>(); for (;;) { if (current.kind == Kind.TOKEN_INT || current.kind == Kind.TOKEN_BOOLEAN) result.add(parseVarDecl()); else if (current.kind == Kind.TOKEN_ID) { /* * * Here's a trick: because Type could be TOKEN_ID, and statement * could also started with TOKEN_ID, so we have to look ahead * for couple of tokens to see how to do it */ Token saved = current; advance(); if (current.kind == Kind.TOKEN_ID) { saveToken(current); current = saved; result.add(parseVarDecl()); } else { saveToken(current); current = saved; return result; } } else return result; } } // FormalList -> Type id FormalRest* // -> // FormalRest -> , Type id private LinkedList<ast.dec.T> parseFormalList() { LinkedList<ast.dec.T> result = new LinkedList<ast.dec.T>(); if (current.kind == Kind.TOKEN_INT || current.kind == Kind.TOKEN_BOOLEAN || current.kind == Kind.TOKEN_ID) { ast.type.T type = parseType(); String id = current.lexeme; eatToken(Kind.TOKEN_ID); result.add(new ast.dec.Dec(type, id)); while (current.kind == Kind.TOKEN_COMMER) { advance(); ast.type.T type1 = parseType(); String id1 = current.lexeme; eatToken(Kind.TOKEN_ID); result.add(new ast.dec.Dec(type1, id1)); } } return result; } // Method -> public Type id ( FormalList ) // { VarDecl* Statement* return Exp ;} private ast.method.Method parseMethod() { switch (current.kind) { case TOKEN_PUBLIC: advance(); ast.type.T type = parseType(); String id = current.lexeme; eatToken(Kind.TOKEN_ID); eatToken(Kind.TOKEN_LPAREN); LinkedList<ast.dec.T> formalList = parseFormalList(); eatToken(Kind.TOKEN_RPAREN); eatToken(Kind.TOKEN_LBRACE); LinkedList<ast.dec.T> varDecl = parseVarDecls(); LinkedList<ast.stm.T> statements = parseStatements(); eatToken(Kind.TOKEN_RETURN); ast.exp.T exp = parseExp(); eatToken(Kind.TOKEN_SEMI); eatToken(Kind.TOKEN_RBRACE); return new ast.method.Method(type, id, formalList, varDecl, statements, exp); default: error("in parseMethod, default case"); return null; } } // MethodDecls -> MethodDecl MethodDecls // -> private LinkedList<ast.method.T> parseMethodDecls() { LinkedList<ast.method.T> methodDecls = new LinkedList<ast.method.T>(); while (current.kind == Kind.TOKEN_PUBLIC) methodDecls.add(parseMethod()); return methodDecls; } // ClassDecl -> class id { VarDecl* MethodDecl* } // -> class id extends id { VarDecl* MethodDecl* } private ast.classs.T parseClassDecl() { eatToken(Kind.TOKEN_CLASS); String id = current.lexeme; eatToken(Kind.TOKEN_ID); String extendss = null; if (current.kind == Kind.TOKEN_EXTENDS) { eatToken(Kind.TOKEN_EXTENDS); extendss = current.lexeme; eatToken(Kind.TOKEN_ID); } eatToken(Kind.TOKEN_LBRACE); LinkedList<ast.dec.T> varDecls = parseVarDecls(); LinkedList<ast.method.T> methodDecl = parseMethodDecls(); eatToken(Kind.TOKEN_RBRACE); return new ast.classs.Class(id, extendss, varDecls, methodDecl); } // ClassDecls -> ClassDecl ClassDecls // -> private LinkedList<ast.classs.T> parseClassDecls() { LinkedList<ast.classs.T> classDecl = new LinkedList<ast.classs.T>(); while (current.kind == Kind.TOKEN_CLASS) classDecl.add(parseClassDecl()); return classDecl; } // MainClass -> class id // { // public static void main ( String [] id ) // { // Statement // } // } private ast.mainClass.T parseMainClass() { switch (current.kind) { case TOKEN_CLASS: advance(); String id = current.lexeme; eatToken(Kind.TOKEN_ID); eatToken(Kind.TOKEN_LBRACE); eatToken(Kind.TOKEN_PUBLIC); eatToken(Kind.TOKEN_STATIC); eatToken(Kind.TOKEN_VOID); eatToken(Kind.TOKEN_MAIN); eatToken(Kind.TOKEN_LPAREN); eatToken(Kind.TOKEN_STRING); eatToken(Kind.TOKEN_LBRACK); eatToken(Kind.TOKEN_RBRACK); String argsId = current.lexeme; eatToken(Kind.TOKEN_ID); eatToken(Kind.TOKEN_RPAREN); eatToken(Kind.TOKEN_LBRACE); ast.stm.T statement = parseStatement(); eatToken(Kind.TOKEN_RBRACE); eatToken(Kind.TOKEN_RBRACE); return new ast.mainClass.MainClass(id, argsId, statement); default: error("in parseMainClass, default case"); return null; } } // Program -> MainClass ClassDecl* private ast.program.T parseProgram() { ast.mainClass.T mainClass = parseMainClass(); LinkedList<ast.classs.T> classs = parseClassDecls(); eatToken(Kind.TOKEN_EOF); return new ast.program.Program(mainClass, classs); } public ast.program.T parse() { return parseProgram(); } }
false
false
null
null
diff --git a/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java b/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java index 6288f88..b597447 100644 --- a/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java +++ b/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java @@ -1,256 +1,257 @@ /* * Copyright 2009 JetBrains s.r.o. * * 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.jetbrains.plugins.clojure.psi.util; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.plugins.clojure.psi.api.ClBraced; import org.jetbrains.plugins.clojure.psi.api.ClList; import org.jetbrains.plugins.clojure.psi.api.ClojureFile; import org.jetbrains.plugins.clojure.psi.api.symbols.ClSymbol; import org.jetbrains.plugins.clojure.psi.ClojurePsiElement; import org.jetbrains.plugins.clojure.psi.impl.ClKeywordImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.intellij.openapi.util.Trinity; import com.intellij.util.containers.HashSet; import java.util.ArrayList; import java.util.Set; import java.util.Arrays; /** * @author ilyas * @author <a href="mailto:[email protected]">Ian Phillips</a> */ public class ClojurePsiUtil { public static final String JAVA_LANG = "java.lang"; public static final String CLOJURE_LANG = "clojure.lang"; public static final Set<String> DEFINITION_FROM_NAMES = new HashSet<String>(); static { DEFINITION_FROM_NAMES.addAll(Arrays.asList("fn")); } @Nullable public static ClList findFormByName(ClojurePsiElement container, @NotNull String name) { for (PsiElement element : container.getChildren()) { if (element instanceof ClList) { ClList list = (ClList) element; final ClSymbol first = list.getFirstSymbol(); if (first != null && name.equals(first.getNameString())) { return list; } } } return null; } @Nullable public static ClList findFormByNameSet(ClojurePsiElement container, @NotNull Set<String> names) { for (PsiElement element : container.getChildren()) { if (element instanceof ClList) { ClList list = (ClList) element; final ClSymbol first = list.getFirstSymbol(); if (first != null && names.contains(first.getNameString())) { return list; } } } return null; } public static ClKeywordImpl findNamespaceKeyByName(ClList ns, String keyName) { final ClList list = ns.findFirstChildByClass(ClList.class); if (list == null) return null; for (PsiElement element : list.getChildren()) { if (element instanceof ClKeywordImpl) { ClKeywordImpl key = (ClKeywordImpl) element; if (keyName.equals(key.getText())) { return key; } } } return null; } @Nullable public static PsiElement getNextNonWhiteSpace(PsiElement element) { PsiElement next = element.getNextSibling(); while (next != null && (next instanceof PsiWhiteSpace)) { next = next.getNextSibling(); } return next; } @NotNull public static Trinity<PsiElement, PsiElement, PsiElement> findCommonParentAndLastChildren(@NotNull PsiElement element1, @NotNull PsiElement element2) { if (element1 == element2) return new Trinity<PsiElement, PsiElement, PsiElement>(element1, element1, element1); final PsiFile containingFile = element1.getContainingFile(); final PsiElement topLevel = containingFile == element2.getContainingFile() ? containingFile : null; ArrayList<PsiElement> parents1 = getParents(element1, topLevel); ArrayList<PsiElement> parents2 = getParents(element2, topLevel); int size = Math.min(parents1.size(), parents2.size()); PsiElement parent = topLevel; for (int i = 1; i <= size; i++) { PsiElement parent1 = parents1.get(parents1.size() - i); PsiElement parent2 = parents2.get(parents2.size() - i); if (!parent1.equals(parent2)) { return new Trinity<PsiElement, PsiElement, PsiElement>(parent, parent1, parent2); } parent = parent1; } return new Trinity<PsiElement, PsiElement, PsiElement>(parent, parent, parent); } public static boolean lessThan(PsiElement elem1, PsiElement elem2) { if (elem1.getParent() != elem2.getParent() || elem1 == elem2) { return false; } PsiElement next = elem1; while (next != null && next != elem2) { next = next.getNextSibling(); } return next != null; } @NotNull public static ArrayList<PsiElement> getParents(@NotNull PsiElement element, @Nullable PsiElement topLevel) { ArrayList<PsiElement> parents = new ArrayList<PsiElement>(); PsiElement parent = element; while (parent != topLevel && parent != null) { parents.add(parent); parent = parent.getParent(); } return parents; } private static boolean isParameterSymbol(ClSymbol symbol) { //todo implement me! return false; } private static boolean anyOf(char c, String s) { return s.indexOf(c) != -1; } /** * Find the s-expression at the caret in a given editor. * * @param editor the editor to search in. * @param previous should the s-exp <i>behind</i> the caret be returned (rather than <i>around</i> the caret). * @return the s-expression, or {@code null} if none could be found. */ public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { + if (offset == chars.length()) --offset; // we want the offset positioned at the last character, not at EOF while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; } /** * Find the top most s-expression around the caret. * * @param editor the editor to search in. * @return the s-expression, or {@code null} if not currently inside one. */ public static @Nullable ClList findTopSexpAroundCaret(@NotNull Editor editor) { Project project = editor.getProject(); if (project == null) { return null; } Document document = editor.getDocument(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) { return null; } PsiElement element = file.findElementAt(editor.getCaretModel().getOffset()); ClList sexp = null; while (element != null) { if (element instanceof ClList) { sexp = (ClList) element; } element = element.getParent(); } return sexp; } public static PsiElement firstChildSexp(PsiElement element) { PsiElement[] children = element.getChildren(); return children.length != 0 ? children[0] : null; } public static PsiElement lastChildSexp(PsiElement element) { PsiElement[] children = element.getChildren(); return children[children.length - 1]; } public static boolean isValidClojureExpression(String text, @NotNull Project project) { if (text == null) return false; text = text.trim(); final ClojurePsiFactory factory = ClojurePsiFactory.getInstance(project); final ClojureFile file = factory.createClojureFileFromText(text); final PsiElement[] children = file.getChildren(); if (children.length == 0) return false; for (PsiElement child : children) { if (containsSyntaxErrors(child)) { return false; } } return true; } private static boolean containsSyntaxErrors(PsiElement elem) { if (elem instanceof PsiErrorElement) { return true; } for (PsiElement child : elem.getChildren()) { if (containsSyntaxErrors(child)) return true; } return false; } public static boolean isStrictlyBefore(PsiElement e1, PsiElement e2) { final Trinity<PsiElement, PsiElement, PsiElement> result = findCommonParentAndLastChildren(e1, e2); return result.second.getTextRange().getStartOffset() < result.third.getTextRange().getStartOffset(); } }
true
true
public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; }
public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { if (offset == chars.length()) --offset; // we want the offset positioned at the last character, not at EOF while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; }
diff --git a/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java b/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java index 12979cd2..0033d8ad 100644 --- a/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java +++ b/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java @@ -1,409 +1,421 @@ // ********************************************************************** // // <copyright> // // BBN Technologies, a Verizon Company // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> // ********************************************************************** // // $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java,v $ // $RCSfile: LabeledOMPoly.java,v $ -// $Revision: 1.1.1.1 $ -// $Date: 2003/02/14 21:35:49 $ +// $Revision: 1.2 $ +// $Date: 2003/04/08 18:54:26 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.omGraphics.labeled; import com.bbn.openmap.omGraphics.*; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.util.Debug; import java.awt.Font; import java.awt.Paint; import java.awt.Point; /** * This is an OMPoly that has been extended to manage a text label. */ public class LabeledOMPoly extends OMPoly implements LabeledOMGraphic { protected OMText label; protected Point offset; protected boolean locateAtCenter = false; protected int index = 0; public LabeledOMPoly() { super(); } /** * Create an LabeledOMPoly from a list of float lat/lon pairs. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(float[], int, int) */ public LabeledOMPoly(float[] llPoints, int units, int lType) { super(llPoints, units, lType); } /** * Create an LabeledOMPoly from a list of float lat/lon pairs. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(float[], int, int, int) */ public LabeledOMPoly(float[] llPoints, int units, int lType, int nsegs) { super(llPoints, units, lType, nsegs); } /** * Create an LabeledOMPoly from a list of xy pairs. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(int[]) */ public LabeledOMPoly(int[] xypoints) { super(xypoints); } /** * Create an x/y LabeledOMPoly. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(int[], int[]) */ public LabeledOMPoly(int[] xPoints, int[] yPoints) { super(xPoints, yPoints); } /** * Create an x/y LabeledOMPoly at an offset from lat/lon. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(float, float, int[], int) */ public LabeledOMPoly(float latPoint, float lonPoint, int[] xypoints, int cMode) { super(latPoint, lonPoint, xypoints, cMode); } /** * Create an x/y LabeledOMPoly at an offset from lat/lon. * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(float, float, int[], int[], int) */ public LabeledOMPoly(float latPoint, float lonPoint, int[] xPoints, int[] yPoints, int cMode) { super(latPoint, lonPoint, xPoints, yPoints, cMode); } /** * Set the String for the label. */ public void setText(String label) { getLabel().setData(label); } /** * Get the String for the label. */ public String getText() { return getLabel().getData(); } protected OMText getLabel() { if (label == null) { label = new OMText(-1, -1, "", OMText.JUSTIFY_LEFT); } return label; } /** * Set the Font for the label. */ public void setFont(Font f) { getLabel().setFont(f); } /** * Get the Font for the label. */ public Font getFont() { return getLabel().getFont(); } /** * Set the justification setting for the label. * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT */ public void setJustify(int just) { getLabel().setJustify(just); } /** * Get the justification setting for the label. * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT */ public int getJustify() { return getLabel().getJustify(); } /** * Tell the LabeledOMGraphic to calculate the location of the * String that would put it in the middle of the OMGraphic. */ public void setLocateAtCenter(boolean set) { locateAtCenter = set; if (set) { setJustify(OMText.JUSTIFY_CENTER); getLabel().setFMHeight(OMText.ASCENT); } } /** * Get whether the LabeledOMGraphic is placing the label String in * the center of the OMGraphic. */ public boolean isLocateAtCenter() { return locateAtCenter; } /** * Calculate the projected area of the poly. * Algorithm used is from some australian astronomy website =) * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea */ protected double calculateProjectedArea() { int j = 0; double area = 0.0; int[] xpts = xpoints[0]; int[] ypts = ypoints[0]; int npoints = xpts.length; for (int i=0; i<npoints; ++i) { j = (i + 1) % npoints; area += xpts[i] * ypts[j]; area -= ypts[i] * xpts[j]; } - area = area / 2.0; - return (area < 0.0 ? -area : area); + + return area / 2.0; + +// area = area / 2.0; +// return (area < 0.0 ? -area : area); } /** * Get the calculated center where the label string is drawn. * Algorithm used is from some australian astronomy website =) * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea */ public Point getCenter() { // if the OMPoly isn't generated, then you can't calculate it. // We're working in x/y space here, so it looks right. if (getNeedToRegenerate()) { return null; } float cx = 0.0f; float cy = 0.0f; float A = (float)calculateProjectedArea(); int j = 0; float factor = 0; int[] xpts = xpoints[0]; int[] ypts = ypoints[0]; int npoints = xpts.length; for (int i=0; i<npoints; ++i) { j = (i + 1) % npoints; factor = xpts[i] * ypts[j] - xpts[j] * ypts[i]; cx += (xpts[i] + xpts[j]) * factor; cy += (ypts[i] + ypts[j]) * factor; } A = A * 6.0f; factor = 1/A; // bbenyo: take the absolute value cause I was getting negative values // for polys with all positive vertices - cx = Math.abs(cx * factor); - cy = Math.abs(cy * factor); - +// cx = Math.abs(cx * factor); +// cy = Math.abs(cy * factor); + + // DFD and RS - let the area calculation return negative + // values, and don't do this absolute value calculation. + // Negative values get returned when the points are + // counterclockwise, indicating holes. We may want labels + // offscreen however, and the abs pushes them onscreen. + + cx *= factor; + cy *= factor; + Point center = new Point(Math.round(cx), Math.round(cy)); return center; } /** * Set the index of the OMGraphic coordinates where the drawing * point of the label should be attached. The meaning of the * point differs between OMGraphic types. */ public void setIndex(int index) { this.index = index; } /** * Get the index of the OMGraphic where the String will be * rendered. The meaning of the index differs from OMGraphic type * to OMGraphic type. */ public int getIndex() { return index; } /** * Set the x, y pixel offsets where the String should be rendered, * from the location determined from the index point, or from the * calculated center point. Point.x is the horizontal offset, * Point.y is the vertical offset. */ public void setOffset(Point p) { offset = p; } /** * Get the x, y pixel offsets set for the rendering of the point. */ public Point getOffset() { if (offset == null) { offset = new Point(); } return offset; } /** * Set the angle by which the text is to rotated. * @param angle the number of radians the text is to be * rotated. Measured clockwise from horizontal. Positive numbers * move the positive x axis toward the positive y axis. */ public void setRotationAngle(double angle) { getLabel().setRotationAngle(angle); } /** * Get the current rotation of the text. * @return the text rotation. */ public double getRotationAngle() { return getLabel().getRotationAngle(); } boolean matchPolyPaint = true; /** * Set the line paint for the polygon. If the text paint hasn't * been explicitly set, then the text paint will be set to this * paint, too. */ public void setLinePaint(Paint paint) { super.setLinePaint(paint); if (matchPolyPaint) { getLabel().setLinePaint(paint); } } /** * If not set to null, the text will be painted in a different * color. If set to null, the text paint will match the poly edge * paint. * @param paint the Paint object for the text */ public void setTextPaint(Paint paint) { if (paint != null) { matchPolyPaint = false; getLabel().setLinePaint(paint); } } /** * Used for the actual text location. */ Point handyPoint = new Point(); /** * Calculate where the text point ought to go. */ protected Point getTextPoint(Projection proj) { int i; int avgx = 0; int avgy = 0; // Assuming that the rendertype is not unknown... if (renderType == RENDERTYPE_LATLON) { int numPoints = rawllpts.length/2; if (rawllpts.length < 2) { // off screen... handyPoint.setLocation(-10, -10); return handyPoint; } if (locateAtCenter) { handyPoint = getCenter(); // New getCenter algorithm works better. // for (i = 0; i < rawllpts.length; i+=2) { // proj.forward(rawllpts[i], rawllpts[i+1], // handyPoint, true); // avgy += handyPoint.getY(); // avgx += handyPoint.getX(); // } // avgy = avgy/numPoints; // avgx = avgx/numPoints; // handyPoint.setLocation(avgx, avgy); } else { if (index < 0) index = 0; if (index > numPoints) index = numPoints - 1; proj.forward(rawllpts[2*index], rawllpts[2*index+1], handyPoint, true); } } else { int[][] x = xpoints; int[][] y = ypoints; if (x[0].length < 2) { // off screen... handyPoint.setLocation(-10, -10); return handyPoint; } if (locateAtCenter) { handyPoint = getCenter(); // New getCenter algorithm works better. // for (i = 0; i < x[0].length; i++) { // avgx += x[0][i]; // avgy += y[0][i]; // } // handyPoint.setLocation(avgx/x[0].length, avgy/x[0].length); } else { if (index < 0) index = 0; if (index >= x[0].length) index = x[0].length - 1; handyPoint.setLocation(x[0][index], y[0][index]); } } return handyPoint; } public boolean generate(Projection proj) { boolean ret = super.generate(proj); Point p = getTextPoint(proj); label.setX((int)(p.getX() + getOffset().getX())); label.setY((int)(p.getY() + getOffset().getY())); if (Debug.debugging("labeled")) { Debug.output("Setting label(" + label.getData() + ") to " + p); } label.generate(proj); return ret; } public void render(java.awt.Graphics g) { super.render(g); label.render(g); } }
false
false
null
null
diff --git a/core/src/test/java/org/infinispan/loaders/dummy/DummyInMemoryCacheStore.java b/core/src/test/java/org/infinispan/loaders/dummy/DummyInMemoryCacheStore.java index 32b2647bba..9be4d8909e 100644 --- a/core/src/test/java/org/infinispan/loaders/dummy/DummyInMemoryCacheStore.java +++ b/core/src/test/java/org/infinispan/loaders/dummy/DummyInMemoryCacheStore.java @@ -1,354 +1,357 @@ /* * JBoss, Home of Professional Open Source * Copyright 2009 Red Hat Inc. and/or its affiliates and other * contributors as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.infinispan.loaders.dummy; import org.infinispan.Cache; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.loaders.*; import org.infinispan.marshall.StreamingMarshaller; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.util.Util; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class DummyInMemoryCacheStore extends AbstractCacheStore { private static final Log log = LogFactory.getLog(DummyInMemoryCacheStore.class); private static final boolean trace = log.isTraceEnabled(); static final ConcurrentMap<String, Map<Object, InternalCacheEntry>> stores = new ConcurrentHashMap<String, Map<Object, InternalCacheEntry>>(); static final ConcurrentMap<String, Map<String, Integer>> storeStats = new ConcurrentHashMap<String, Map<String, Integer>>(); String storeName; Map<Object, InternalCacheEntry> store; Map<String, Integer> stats; Cfg config; private void record(String method) { int i = stats.get(method); stats.put(method, i + 1); } @Override public void store(InternalCacheEntry ed) { record("store"); if (ed != null) { if (trace) log.tracef("Store %s in dummy map store@%s", ed, Util.hexIdHashCode(store)); config.failIfNeeded(ed.getKey()); store.put(ed.getKey(), ed); } } @Override @SuppressWarnings("unchecked") public void fromStream(ObjectInput ois) throws CacheLoaderException { record("fromStream"); try { int numEntries = (Integer) marshaller.objectFromObjectStream(ois); for (int i = 0; i < numEntries; i++) { InternalCacheEntry e = (InternalCacheEntry) marshaller.objectFromObjectStream(ois); if (trace) log.tracef("Store %s from stream in dummy store@%s", e, Util.hexIdHashCode(store)); store.put(e.getKey(), e); } } catch (Exception e) { throw new CacheLoaderException(e); } } @Override public void toStream(ObjectOutput oos) throws CacheLoaderException { record("toStream"); try { marshaller.objectToObjectStream(store.size(), oos); for (InternalCacheEntry se : store.values()) marshaller.objectToObjectStream(se, oos); } catch (Exception e) { throw new CacheLoaderException(e); } } @Override public void clear() { record("clear"); if (trace) log.trace("Clear store"); store.clear(); } @Override public boolean remove(Object key) { record("remove"); if (store.remove(key) != null) { if (trace) log.tracef("Removed %s from dummy store", key); return true; } if (trace) log.tracef("Key %s not present in store, so don't remove", key); return false; } @Override protected void purgeInternal() throws CacheLoaderException { for (Iterator<InternalCacheEntry> i = store.values().iterator(); i.hasNext();) { InternalCacheEntry se = i.next(); if (se.isExpired()) i.remove(); } } @Override public void init(CacheLoaderConfig config, Cache cache, StreamingMarshaller m) throws CacheLoaderException { super.init(config, cache, m); this.config = (Cfg) config; storeName = this.config.getStoreName(); if (marshaller == null) marshaller = new TestObjectStreamMarshaller(); } @Override public InternalCacheEntry load(Object key) { record("load"); if (key == null) return null; InternalCacheEntry se = store.get(key); if (se == null) return null; if (se.isExpired()) { log.debugf("Key %s exists, but has expired. Entry is %s", key, se); store.remove(key); return null; } return se; } @Override public Set<InternalCacheEntry> loadAll() { record("loadAll"); Set<InternalCacheEntry> s = new HashSet<InternalCacheEntry>(); for (Iterator<InternalCacheEntry> i = store.values().iterator(); i.hasNext();) { InternalCacheEntry se = i.next(); if (se.isExpired()) { log.debugf("Key %s exists, but has expired. Entry is %s", se.getKey(), se); i.remove(); } else s.add(se); } return s; } @Override public Set<InternalCacheEntry> load(int numEntries) throws CacheLoaderException { record("load"); if (numEntries < 0) return loadAll(); Set<InternalCacheEntry> s = new HashSet<InternalCacheEntry>(numEntries); for (Iterator<InternalCacheEntry> i = store.values().iterator(); i.hasNext() && s.size() < numEntries;) { InternalCacheEntry se = i.next(); if (se.isExpired()) { log.debugf("Key %s exists, but has expired. Entry is %s", se.getKey(), se); i.remove(); } else if (s.size() < numEntries) { s.add(se); } } return s; } @Override public Set<Object> loadAllKeys(Set<Object> keysToExclude) throws CacheLoaderException { record("loadAllKeys"); Set<Object> set = new HashSet<Object>(); for (Object key: store.keySet()) { if (keysToExclude == null || !keysToExclude.contains(key)) set.add(key); } return set; } @Override public Class<? extends CacheLoaderConfig> getConfigurationClass() { record("getConfigurationClass"); return Cfg.class; } @Override public void start() throws CacheLoaderException { super.start(); if (store != null) return; store = new ConcurrentHashMap<Object, InternalCacheEntry>(); stats = newStatsMap(); if (storeName != null) { if (cache != null) storeName += "_" + cache.getName(); Map<Object, InternalCacheEntry> existing = stores.putIfAbsent(storeName, store); if (existing != null) { store = existing; log.debugf("Reusing in-memory cache store %s", storeName); } else { log.debugf("Creating new in-memory cache store %s", storeName); } Map<String, Integer> existingStats = storeStats.putIfAbsent(storeName, stats); if (existing != null) { stats = existingStats; } } // record at the end! record("start"); } private Map<String, Integer> newStatsMap() { Map<String, Integer> m = new ConcurrentHashMap<String, Integer>(); for (Method method: CacheStore.class.getMethods()) { m.put(method.getName(), 0); } return m; } @Override public void stop() { record("stop"); if (config.isPurgeOnStartup()) { - stores.remove(config.getStoreName()); + String storeName = config.getStoreName(); + if (storeName != null) { + stores.remove(storeName); + } } } public boolean isEmpty() { return store.isEmpty(); } public Map<String, Integer> stats() { return Collections.unmodifiableMap(stats); } public void clearStats() { for (String k: stats.keySet()) stats.put(k, 0); } public static class Cfg extends AbstractCacheStoreConfig { private static final long serialVersionUID = 4258914047690999424L; boolean debug; String storeName = null; private Object failKey; public Cfg() { this(null); } public Cfg(String name) { setCacheLoaderClassName(DummyInMemoryCacheStore.class.getName()); storeName(name); } public boolean isDebug() { return debug; } /** * @deprecated use {@link #debug(boolean)} */ @Deprecated public void setDebug(boolean debug) { this.debug = debug; } public Cfg debug(boolean debug) { setDebug(debug); return this; } public String getStoreName() { return storeName; } /** * @deprecated use {@link #storeName(String)} */ @Deprecated public void setStoreName(String store) { this.storeName = store; } public Cfg storeName(String store) { setStoreName(store); return this; } @Override public Cfg clone() { return (Cfg) super.clone(); } /** * @deprecated use {@link #failKey(Object)} */ @Deprecated public void setFailKey(Object failKey) { this.failKey = failKey; } public Cfg failKey(Object failKey) { setFailKey(failKey); return this; } public void failIfNeeded(Object key) { if(failKey != null && failKey.equals(key)) throw new RuntimeException("Induced failure on key:" + key); } @Override public Cfg fetchPersistentState(Boolean fetchPersistentState) { super.fetchPersistentState(fetchPersistentState); return this; } @Override public Cfg ignoreModifications(Boolean ignoreModifications) { super.ignoreModifications(ignoreModifications); return this; } @Override public Cfg purgeOnStartup(Boolean purgeOnStartup) { super.purgeOnStartup(purgeOnStartup); return this; } @Override public Cfg purgerThreads(Integer purgerThreads) { super.purgerThreads(purgerThreads); return this; } @Override public Cfg purgeSynchronously(Boolean purgeSynchronously) { super.purgeSynchronously(purgeSynchronously); return this; } } }
true
false
null
null
diff --git a/plugins/org.eclipse.ocl.ecore/src/org/eclipse/ocl/ecore/opposites/DefaultOppositeEndFinder.java b/plugins/org.eclipse.ocl.ecore/src/org/eclipse/ocl/ecore/opposites/DefaultOppositeEndFinder.java index dd7c78d847..070f2ee7d4 100644 --- a/plugins/org.eclipse.ocl.ecore/src/org/eclipse/ocl/ecore/opposites/DefaultOppositeEndFinder.java +++ b/plugins/org.eclipse.ocl.ecore/src/org/eclipse/ocl/ecore/opposites/DefaultOppositeEndFinder.java @@ -1,342 +1,336 @@ /** * <copyright> * * Copyright (c) 2009,2010 SAP 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: * Axel Uhl - Initial API and implementation * * </copyright> * - * $Id: DefaultOppositeEndFinder.java,v 1.2 2011/01/25 10:43:34 auhl Exp $ + * $Id: DefaultOppositeEndFinder.java,v 1.3 2011/02/23 10:56:34 auhl Exp $ */ package org.eclipse.ocl.ecore.opposites; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EPackage.Registry; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature.Setting; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.util.ECrossReferenceAdapter; import org.eclipse.emf.ecore.xmi.impl.EMOFExtendedMetaData; import org.eclipse.ocl.ecore.EcoreEnvironment; import org.eclipse.ocl.ecore.internal.OCLEcorePlugin; import org.eclipse.ocl.ecore.internal.OCLStatusCodes; import org.eclipse.ocl.util.CollectionUtil; /** * Opposite references declared by the annotation detail * {@link EcoreEnvironment#PROPERTY_OPPOSITE_ROLE_NAME_KEY} on an * {@link EAnnotation} with {@link EAnnotation#getSource() source} * {@link EMOFExtendedMetaData#EMOF_PACKAGE_NS_URI_2_0} are retrieved by * scanning and caching the Ecore packages that this opposite end finder is * aware of at the time of the request. The set of those packages is taken to be * the set of {@link EPackage}s resolved by an {@link EPackage.Registry} * provided to {@link #getInstance(Registry)}, or the default * {@link EPackage.Registry} otherwise. In particular, this won't load any Ecore * bundles not yet loaded. * <p> * * This also means that with this implementation of the {@link OppositeEndFinder} * interface it is necessary to resolve a package in the registry on which this * opposite end finder is based before issuing a request expecting to find * hidden opposites from that package. This can, e.g., be triggered by calling * {@link EPackage.Registry#getEPackage(String)} for the package's URI.<p> * * Navigation across those references is performed either by * {@link EObject#eContainer()} in case of containment references or by looking * for an {@link ECrossReferenceAdapter} along the containment hierarchy of the * source object from which to start the navigation. Only if such an adapter is * registered along the composition/containment hierarchy can the navigation be * performed successfully. Note also that this will only consider references * that have been currently loaded which can give rather random results. For * more predictable results, an implementation should be used that relies on a * well-defined query scope and a corresponding query engine.<p> * * Instances of this class are cached in a {@link WeakHashMap}, keyed by the * {@link EPackage.Registry} object used for {@link #getInstance(Registry)}. * This means that if the registry gets eligible for garbage collection then * so will this opposite end finder.<p> * * @author Axel Uhl * @since 3.1 * */ public class DefaultOppositeEndFinder implements OppositeEndFinder { private static DefaultOppositeEndFinder instanceForDefaultRegistry = null; /** * The set of packages for which the hidden opposites are already cached in * {@link #oppositeCache}. */ private final Set<EPackage> packages; private final Map<EClass, Map<String, Set<EReference>>> oppositeCache; /** * The package registry in which before each request the set of packages already * resolved is compared to {@link #packages}. Packages that got resolved in the * registry but weren't cached yet are cached before executing the request. */ private final Registry registry; /** * Scans all packages from the default {@link EPackage.Registry} that have already been * loaded. While this is convenient, please keep in mind that this may be fairly random a * definition of a package set as loading of packages happens on demand. You will get more * predictable results using {@link #getInstance(Set<EPackage>)}. */ public static DefaultOppositeEndFinder getInstance() { return getInstance(EPackage.Registry.INSTANCE); } /** * Scans all packages from the <code>registry</code> specified that have already been * loaded. While this is convenient, please keep in mind that this may be fairly random a * definition of a package set as loading of packages happens on demand. You will get more * predictable results using {@link #getInstance(Set<EPackage>)}. */ public static DefaultOppositeEndFinder getInstance(EPackage.Registry registry) { DefaultOppositeEndFinder result; if (registry == EPackage.Registry.INSTANCE) { if (instanceForDefaultRegistry == null) { instanceForDefaultRegistry = new DefaultOppositeEndFinder(EPackage.Registry.INSTANCE); } result = instanceForDefaultRegistry; } else { result = new DefaultOppositeEndFinder(registry); } return result; } - private Set<EPackage> getLoadedPackages() { - for (Object key : registry.values()) { - // if it's not a package descriptor indicating a not yet loaded package, add it - if (key instanceof EPackage) { - packages.add((EPackage) key); - cachePackage((EPackage) key); - } - } - return packages; - } - protected DefaultOppositeEndFinder(Registry registry) { this.registry = registry; this.packages = new HashSet<EPackage>(); this.oppositeCache = new HashMap<EClass, Map<String,Set<EReference>>>(); } public void findOppositeEnds(EClassifier classifier, String name, List<EReference> ends) { if (classifier instanceof EClass) { EClass eClass = (EClass) classifier; updateOppositeCache(); Map<String, Set<EReference>> oppositesOnEClass = oppositeCache.get(eClass); if (oppositesOnEClass != null) { Set<EReference> refs = oppositesOnEClass.get(name); if (refs != null) { Set<EReference> references = oppositesOnEClass.get(name); for (EReference ref : references) { ends.add(ref); } } } // search in superclasses if nothing found yet if (ends.isEmpty()) { for (EClassifier sup : eClass.getESuperTypes()) { findOppositeEnds(sup, name, ends); } } } } public Map<String, EReference> getAllOppositeEnds( EClassifier classifier) { Map<String, EReference> result = new HashMap<String, EReference>(); if (classifier instanceof EClass) { EClass eClass = (EClass) classifier; updateOppositeCache(); Map<String, Set<EReference>> oppositesOnClass = oppositeCache.get(eClass); if (oppositesOnClass != null) { for (String oppositeName : oppositesOnClass.keySet()) { Set<EReference> refs = oppositesOnClass.get(oppositeName); if (refs.size() > 0) { result.put(oppositeName, refs.iterator().next()); } } } // add all inherited opposite property definitions for (EClassifier sup : eClass.getESuperTypes()) { Map<String, EReference> supOppositeEnds = getAllOppositeEnds(sup); for (String supOppositeEndName : supOppositeEnds.keySet()) { // add superclass's opposite only if not already found in // subclass; this implements the "subclass definitions override" // behavior if (!result.containsKey(supOppositeEndName)) { result.put(supOppositeEndName, supOppositeEnds.get(supOppositeEndName)); } } } } return result; } /** * Lazily initialize the opposite cache for the {@link #packages} for which this opposite * end finder is responsible */ private synchronized void updateOppositeCache() { - for (EPackage ePackage : getLoadedPackages()) { - if (!packages.contains(ePackage)) { - cachePackage(ePackage); + for (Object pkg : registry.values()) { + // if it's not a package descriptor indicating a not yet loaded package... + if (pkg instanceof EPackage) { + EPackage ePackage = (EPackage) pkg; + // ... and it hasn't been cached yet, cache it + if (!packages.contains(ePackage)) { + cachePackage(ePackage); + } } } } private void cachePackage(EPackage ePackage) { for (EClassifier c : ePackage.getEClassifiers()) { if (c instanceof EClass) { EClass eClass = (EClass) c; for (EReference ref : eClass.getEReferences()) { EAnnotation ann = ref .getEAnnotation(EMOFExtendedMetaData.EMOF_PACKAGE_NS_URI_2_0); if (ann != null) { String oppositeName = ann.getDetails().get( OppositeEndFinder.PROPERTY_OPPOSITE_ROLE_NAME_KEY); if (oppositeName != null) { cache((EClass) ref.getEType(), oppositeName, ref); } } } } } } private void cache(EClass c, String oppositeName, EReference ref) { Map<String, Set<EReference>> cache = oppositeCache.get(c); if (cache == null) { cache = new HashMap<String, Set<EReference>>(); oppositeCache.put(c, cache); } Set<EReference> set = cache.get(oppositeName); if (set == null) { set = new HashSet<EReference>(); cache.put(oppositeName, set); } set.add(ref); } /** * If on the <code>target</code> or any of its containers up to the * {@link ResourceSet} there is a {@link ECrossReferenceAdapter} registered, * uses it for navigating <code>property</code> in reverse. In this case, a * non- <code>null</code> collection is returned which contains those * {@link EObject}s on which navigating <code>property</code> leads to * <code>target</code>. The "forward" scope is just whatever the * {@link ECrossReferenceAdapter} sees that is expected to be registered on * <code>target</code> * * @param target * must be a non-<code>null</code> {@link EObject} */ public Collection<EObject> navigateOppositePropertyWithForwardScope( EReference property, EObject target) { return navigateOppositePropertyWithSymmetricScope(property, target); } public Collection<EObject> navigateOppositePropertyWithBackwardScope( EReference property, EObject target) { return navigateOppositePropertyWithSymmetricScope(property, target); } private Collection<EObject> navigateOppositePropertyWithSymmetricScope( EReference property, EObject target) { Collection<EObject> result = null; if (property.isContainment()) { EObject resultCandidate = target.eContainer(); if (resultCandidate != null) { // first check if the container is assignment-compatible to the // property's owning type: if (property.getEContainingClass().isInstance(resultCandidate)) { Object propertyValue = resultCandidate.eGet(property); if (propertyValue == target || (propertyValue instanceof Collection<?> && ((Collection<?>) propertyValue) .contains(target))) { result = Collections.singleton(resultCandidate); } } } } else { ECrossReferenceAdapter crossReferenceAdapter = getCrossReferenceAdapter(target); if (crossReferenceAdapter != null) { result = CollectionUtil.createNewBag(); Collection<Setting> settings = crossReferenceAdapter .getInverseReferences(target); for (Setting setting : settings) { if (setting.getEStructuralFeature() == property) { result.add(setting.getEObject()); } } } else { OCLEcorePlugin.warning(OCLStatusCodes.IGNORED_EXCEPTION_WARNING, "Trying to reverse-navigate reference of " + target //$NON-NLS-1$ + " without ECrossReferenceAdapter attached"); //$NON-NLS-1$ } } return result; } /** * Search for an {@link ECrossReferenceAdapter} up <code>target</code>'s * containmeht hierarchy */ private ECrossReferenceAdapter getCrossReferenceAdapter(EObject target) { ECrossReferenceAdapter result = ECrossReferenceAdapter .getCrossReferenceAdapter(target); if (result == null && target.eContainer() != null) { result = getCrossReferenceAdapter(target.eContainer()); } return result; } /** * This default implementation uses an {@link AllInstancesContentAdapter} on * <code>context</code>'s root context (see * {@link AllInstancesContentAdapter#getInstanceForRootContextOf(Notifier)}) * which is created lazily if it isn't set yet. Note that for larger * resource sets with many resources and elements this won't scale very well * as all resources will be scanned for elements conforming to * <code>cls</code>. Also, no scoping other than tracing to the root context * based on <code>context</code> is performed. */ public Set<EObject> getAllInstancesSeeing(EClass cls, Notifier context) { return AllInstancesContentAdapter.getInstanceForRootContextOf(context) .allInstances(cls); } public Set<EObject> getAllInstancesSeenBy(EClass cls, Notifier context) { return getAllInstancesSeeing(cls, context); } }
false
false
null
null
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java index 1f7bdf97c..b2b8163d7 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java @@ -1,1046 +1,1045 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.core.session; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpSession; import javax.servlet.sip.ServletTimer; import javax.servlet.sip.SipApplicationSessionActivationListener; import javax.servlet.sip.SipApplicationSessionAttributeListener; import javax.servlet.sip.SipApplicationSessionBindingEvent; import javax.servlet.sip.SipApplicationSessionBindingListener; import javax.servlet.sip.SipApplicationSessionEvent; import javax.servlet.sip.SipApplicationSessionListener; import javax.servlet.sip.SipSession; import javax.servlet.sip.URI; import org.apache.catalina.security.SecurityUtil; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.address.RFC2396UrlDecoder; import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode; import org.mobicents.servlet.sip.message.MobicentsSipApplicationSessionFacade; import org.mobicents.servlet.sip.startup.SipContext; import org.mobicents.servlet.sip.utils.JvmRouteUtil; /** * <p>Implementation of the SipApplicationSession interface. * An instance of this sip application session can only be retrieved through the Session Manager * (extended class from Tomcat's manager classes implementing the <code>Manager</code> interface) * to constrain the creation of sip application session and to make sure that all sessions created * can be retrieved only through the session manager<p/> * * <p> * As a SipApplicationSession represents a call (that can contain multiple call legs, in the B2BUA case by example), * the call id and the app name are used as a unique key for a given SipApplicationSession instance. * </p> * * @author <A HREF="mailto:[email protected]">Jean Deruelle</A> */ public class SipApplicationSessionImpl implements MobicentsSipApplicationSession { private static transient Logger logger = Logger.getLogger(SipApplicationSessionImpl.class); /** * Timer task that will notify the listeners that the sip application session has expired * It is an improved timer task that is delayed every time setLastAccessedTime is called on it. * It is delayed of lastAccessedTime + lifetime * @author <A HREF="mailto:[email protected]">Jean Deruelle</A> */ public class SipApplicationSessionTimerTask implements Runnable { public void run() { if(logger.isDebugEnabled()) { logger.debug("initial kick off of SipApplicationSessionTimerTask running for sip application session " + getId()); } long now = System.currentTimeMillis(); if(expirationTime > now) { // if the session has been accessed since we started it, put it to sleep long sleep = getDelay(); if(logger.isDebugEnabled()) { logger.debug("expirationTime is " + expirationTime + ", now is " + now + " sleeping for " + sleep / 1000 + " seconds"); } expirationTimerTask = new SipApplicationSessionTimerTask(); expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) sipContext.getThreadPoolExecutor().schedule(expirationTimerTask, sleep, TimeUnit.MILLISECONDS); } else { tryToExpire(); } } private void tryToExpire() { notifySipApplicationSessionListeners(SipApplicationSessionEventType.EXPIRATION); //It is possible that the application grant an extension to the lifetime of the session, thus the sip application //should not be treated as expired. if(getDelay() <= 0) { expired = true; if(isValid) { sipContext.enterSipApp(null, null, null, true, false); try { invalidate(); } finally { sipContext.exitSipApp(null, null); } } } } public long getDelay() { return expirationTime - System.currentTimeMillis(); } } protected Map<String, Object> sipApplicationSessionAttributeMap; protected transient ConcurrentHashMap<String,MobicentsSipSession> sipSessions; protected transient ConcurrentHashMap<String, HttpSession> httpSessions; protected SipApplicationSessionKey key; protected long lastAccessedTime; protected long creationTime; protected long expirationTime; protected boolean expired; protected transient SipApplicationSessionTimerTask expirationTimerTask; protected transient ScheduledFuture<MobicentsSipApplicationSession> expirationTimerFuture; protected transient ConcurrentHashMap<String, ServletTimer> servletTimers; protected boolean isValid; protected boolean invalidateWhenReady = true; protected boolean readyToInvalidate = false; // protected transient ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1, // 90, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); /** * The first sip application for subsequent requests. */ protected transient SipContext sipContext; protected String currentRequestHandler; protected transient Semaphore semaphore; protected transient MobicentsSipApplicationSessionFacade facade = null; protected long sipApplicationSessionTimeout = -1; protected SipApplicationSessionImpl(SipApplicationSessionKey key, SipContext sipContext) { sipApplicationSessionAttributeMap = new ConcurrentHashMap<String,Object>() ; sipSessions = new ConcurrentHashMap<String,MobicentsSipSession>(); httpSessions = new ConcurrentHashMap<String,HttpSession>(); servletTimers = new ConcurrentHashMap<String, ServletTimer>(); if(!ConcurrencyControlMode.None.equals(sipContext.getConcurrencyControlMode())) { semaphore = new Semaphore(1); } this.key = key; this.sipContext = sipContext; this.currentRequestHandler = sipContext.getMainServlet(); lastAccessedTime = creationTime = System.currentTimeMillis(); expired = false; isValid = true; // the sip context can be null if the AR returned an application that was not deployed if(sipContext != null) { //scheduling the timer for session expiration if(sipContext.getSipApplicationSessionTimeout() > 0) { sipApplicationSessionTimeout = sipContext.getSipApplicationSessionTimeout() * 60 * 1000; expirationTimerTask = new SipApplicationSessionTimerTask(); if(logger.isDebugEnabled()) { logger.debug("Scheduling sip application session "+ key +" to expire in " + (expirationTime / 1000 / 60) + " minutes"); } expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) sipContext.getThreadPoolExecutor().schedule(expirationTimerTask, sipApplicationSessionTimeout, TimeUnit.MILLISECONDS); } else { if(logger.isDebugEnabled()) { logger.debug("The sip application session "+ key +" will never expire "); } // If the session timeout value is 0 or less, then an application session timer // never starts for the SipApplicationSession object and the container does // not consider the object to ever have expired // expirationTime = -1; } notifySipApplicationSessionListeners(SipApplicationSessionEventType.CREATION); } } /** * Notifies the listeners that a lifecycle event occured on that sip application session * @param sipApplicationSessionEventType the type of event that happened */ public void notifySipApplicationSessionListeners(SipApplicationSessionEventType sipApplicationSessionEventType) { List<SipApplicationSessionListener> listeners = sipContext.getListeners().getSipApplicationSessionListeners(); if(listeners.size() > 0) { ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader(); java.lang.Thread.currentThread().setContextClassLoader(sipContext.getLoader().getClassLoader()); SipApplicationSessionEvent event = new SipApplicationSessionEvent(this.getSession()); if(logger.isDebugEnabled()) { logger.debug("notifying sip application session listeners of context " + key.getApplicationName() + " of following event " + sipApplicationSessionEventType); } for (SipApplicationSessionListener sipApplicationSessionListener : listeners) { try { if(SipApplicationSessionEventType.CREATION.equals(sipApplicationSessionEventType)) { sipApplicationSessionListener.sessionCreated(event); } else if (SipApplicationSessionEventType.DELETION.equals(sipApplicationSessionEventType)) { sipApplicationSessionListener.sessionDestroyed(event); } else if (SipApplicationSessionEventType.EXPIRATION.equals(sipApplicationSessionEventType)) { sipApplicationSessionListener.sessionExpired(event); } else if (SipApplicationSessionEventType.READYTOINVALIDATE.equals(sipApplicationSessionEventType)) { sipApplicationSessionListener.sessionReadyToInvalidate(event); } } catch (Throwable t) { logger.error("SipApplicationSessionListener threw exception", t); } } java.lang.Thread.currentThread().setContextClassLoader(oldLoader); } } public void addSipSession(MobicentsSipSession mobicentsSipSession) { this.sipSessions.putIfAbsent(mobicentsSipSession.getKey().toString(), mobicentsSipSession); readyToInvalidate = false; // sipSessionImpl.setSipApplicationSession(this); } public MobicentsSipSession removeSipSession (MobicentsSipSession mobicentsSipSession) { return this.sipSessions.remove(mobicentsSipSession.getKey().toString()); } public void addHttpSession(HttpSession httpSession) { this.httpSessions.putIfAbsent(JvmRouteUtil.removeJvmRoute(httpSession.getId()), httpSession); readyToInvalidate = false; // TODO: We assume that there is only one HTTP session in the app session. In this case // we are safe to only assign jvmRoute once here. When we support multiple http sessions // we will need something more sophisticated. setJvmRoute(JvmRouteUtil.extractJvmRoute(httpSession.getId())); } public HttpSession removeHttpSession(HttpSession httpSession) { return this.httpSessions.remove(JvmRouteUtil.removeJvmRoute(httpSession.getId())); } public HttpSession findHttpSession (HttpSession httpSession) { return this.httpSessions.get(JvmRouteUtil.removeJvmRoute(httpSession.getId())); } /** * {@inheritDoc} */ public void encodeURI(URI uri) { uri.setParameter(SIP_APPLICATION_KEY_PARAM_NAME, RFC2396UrlDecoder.encode(getId())); } /** * {@inheritDoc} * Adds a get parameter to the URL like this: * http://hostname/link -> http://hostname/link?org.mobicents.servlet.sip.ApplicationSessionKey=0 * http://hostname/link?something=1 -> http://hostname/link?something=1&org.mobicents.servlet.sip.ApplicationSessionKey=0 */ public URL encodeURL(URL url) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } String urlStr = url.toExternalForm(); try { URL ret; if (urlStr.contains("?")) { ret = new URL(url + "&" + SIP_APPLICATION_KEY_PARAM_NAME + "=" + getId().toString()); } else { ret = new URL(url + "?" + SIP_APPLICATION_KEY_PARAM_NAME + "=" + getId().toString()); } return ret; } catch (Exception e) { throw new IllegalArgumentException("Failed encoding URL : " + url, e); } } /** * {@inheritDoc} */ public Object getAttribute(String name) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return this.sipApplicationSessionAttributeMap.get(name); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getAttributeNames() */ public Iterator<String> getAttributeNames() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return this.sipApplicationSessionAttributeMap.keySet().iterator(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getCreationTime() */ public long getCreationTime() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return creationTime; } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getExpirationTime() */ public long getExpirationTime() { if(!isValid) { throw new IllegalStateException("this sip application session is not valid anymore"); } long expirationTime = expirationTimerTask.getDelay(); if(expirationTimerTask == null || expirationTime <= 0) { return 0; } if(expired) { return Long.MIN_VALUE; } return expirationTime; } /** * {@inheritDoc} */ public String getId() { return key.toString(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getLastAccessedTime() */ public long getLastAccessedTime() { return lastAccessedTime; } private void setLastAccessedTime(long lastAccessTime) { this.lastAccessedTime = lastAccessTime; //JSR 289 Section 6.3 : starting the sip app session expiry timer anew if(sipApplicationSessionTimeout > 0) { expirationTime = lastAccessedTime + sipApplicationSessionTimeout; } } /** * Update the accessed time information for this session. This method * should be called by the context when a request comes in for a particular * session, even if the application does not reference it. */ //TODO : Section 6.3 : Whenever the last accessed time for a SipApplicationSession is updated, it is considered refreshed i.e., //the expiry timer for that SipApplicationSession starts anew. // this method should be called as soon as there is any modifications to the Sip Application Session public void access() { setLastAccessedTime(System.currentTimeMillis()); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getSessions() */ public Iterator<?> getSessions() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return sipSessions.values().iterator(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getSessions(java.lang.String) */ public Iterator<?> getSessions(String protocol) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } if(protocol == null) { throw new NullPointerException("protocol given in argument is null"); } if("SIP".equalsIgnoreCase(protocol)) { return sipSessions.values().iterator(); } else if("HTTP".equalsIgnoreCase(protocol)) { return httpSessions.values().iterator(); } else { throw new IllegalArgumentException(protocol + " sessions are not handled by this container"); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getSipSession(java.lang.String) */ public SipSession getSipSession(String id) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } if(logger.isDebugEnabled()) { logger.debug("Trying to find a session with the id " + id); dumpSipSessions(); } return sipSessions.get(id); } private void dumpSipSessions() { if(logger.isDebugEnabled()) { logger.debug("sessions contained in the following app session " + key); for (String sessionKey : sipSessions.keySet()) { logger.debug("session key " + sessionKey + ", value = " + sipSessions.get(sessionKey)); } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getTimers() */ public Collection<ServletTimer> getTimers() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return servletTimers.values(); } /** * Add a servlet timer to this application session * @param servletTimer the servlet timer to add */ public void addServletTimer(ServletTimer servletTimer){ servletTimers.putIfAbsent(servletTimer.getId(), servletTimer); } /** * Remove a servlet timer from this application session * @param servletTimer the servlet timer to remove */ public void removeServletTimer(ServletTimer servletTimer){ servletTimers.remove(servletTimer.getId()); updateReadyToInvalidateState(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#invalidate() */ public void invalidate() { //JSR 289 Section 6.1.2.2.1 //When the IllegalStateException is thrown, the application is guaranteed //that the state of the SipApplicationSession object will be unchanged from its state prior to the invalidate() //method call. Even session objects that were eligible for invalidation will not have been invalidated. if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } if(logger.isInfoEnabled()) { logger.info("Invalidating the following sip application session " + key); } //doing the invalidation for(MobicentsSipSession session: sipSessions.values()) { if(session.isValid()) { session.invalidate(); } } for(HttpSession session: httpSessions.values()) { if(session instanceof ConvergedSession) { ConvergedSession convergedSession = (ConvergedSession) session; if(convergedSession.isValid()) { convergedSession.invalidate(); } } else { try { session.invalidate(); } catch(IllegalStateException ignore) { //we ignore this exception, ugly but the only way to test for validity of the session since we cannot cast to catalina Session //See Issue 523 http://code.google.com/p/mobicents/issues/detail?id=523 } } } for (String key : sipApplicationSessionAttributeMap.keySet()) { removeAttribute(key); } notifySipApplicationSessionListeners(SipApplicationSessionEventType.DELETION); isValid = false; //cancelling the timers for (Map.Entry<String, ServletTimer> servletTimerEntry : servletTimers.entrySet()) { ServletTimer timerEntry = servletTimerEntry.getValue(); if(timerEntry != null) { timerEntry.cancel(); } } if(!expired && expirationTimerTask != null) { cancelExpirationTimer(); } /* * Compute how long this session has been alive, and update * session manager's related properties accordingly */ long timeNow = System.currentTimeMillis(); int timeAlive = (int) ((timeNow - creationTime)/1000); SipManager manager = sipContext.getSipManager(); synchronized (manager) { if (timeAlive > manager.getSipApplicationSessionMaxAliveTime()) { manager.setSipApplicationSessionMaxAliveTime(timeAlive); } int numExpired = manager.getExpiredSipApplicationSessions(); numExpired++; manager.setExpiredSipApplicationSessions(numExpired); int average = manager.getSipApplicationSessionAverageAliveTime(); average = ((average * (numExpired-1)) + timeAlive)/numExpired; manager.setSipApplicationSessionAverageAliveTime(average); } sipContext.getSipManager().removeSipApplicationSession(key); sipContext.getSipSessionsUtil().removeCorrespondingSipApplicationSession(key); expirationTimerTask = null; expirationTimerFuture = null; httpSessions.clear(); // key = null; servletTimers.clear(); sipApplicationSessionAttributeMap.clear(); sipSessions.clear(); httpSessions.clear(); // executorService.shutdown(); // executorService = null; httpSessions = null; sipSessions = null; sipApplicationSessionAttributeMap = null; servletTimers = null; if(logger.isInfoEnabled()) { logger.info("The following sip application session " + key + " has been invalidated"); } currentRequestHandler = null; if(semaphore != null) { semaphore.release(); semaphore = null; } facade = null; } // Counts the number of cancelled tasks private static int numCancelled = 0; private void cancelExpirationTimer() { //CANCEL needs to remove the shceduled timer see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6602600 //to improve perf // expirationTimerTask.cancel(); boolean removed = sipContext.getThreadPoolExecutor().remove(expirationTimerTask); if(logger.isDebugEnabled()) { logger.debug("expiration timer on sip application session " + key + " removed : " + removed); } boolean cancelled = expirationTimerFuture.cancel(true); if(logger.isDebugEnabled()) { logger.debug("expiration timer on sip application session " + key + " Cancelled : " + cancelled); } // Purge is expensive when called frequently, only call it every now and then. // We do not sync the numCancelled variable. We dont care about correctness of // the number, and we will still call purge rought once on every 25 cancels. numCancelled++; if(numCancelled % 25 == 0) { sipContext.getThreadPoolExecutor().purge(); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#isValid() */ public boolean isValid() { return isValid; } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { if (!isValid) throw new IllegalStateException( "Can not bind object to session that has been invalidated!!"); if (name == null) // throw new NullPointerException("Name of attribute to bind cant be // null!!!"); return; SipApplicationSessionBindingEvent event = null; Object value = this.sipApplicationSessionAttributeMap.remove(name); // Call the valueUnbound() method if necessary if (value != null && value instanceof SipApplicationSessionBindingListener) { event = new SipApplicationSessionBindingEvent(this, name); ((SipApplicationSessionBindingListener) value).valueUnbound(event); } SipListenersHolder listeners = sipContext.getListeners(); List<SipApplicationSessionAttributeListener> listenersList = listeners.getSipApplicationSessionAttributeListeners(); if(listenersList.size() > 0) { if(event == null) { event = new SipApplicationSessionBindingEvent(this, name); } for (SipApplicationSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipApplicationSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute removed on key "+ key); } try { listener.attributeRemoved(event); } catch (Throwable t) { logger.error("SipApplicationSessionAttributeListener threw exception", t); } } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String key, Object attribute) { if (!isValid) throw new IllegalStateException( "Can not bind object to session that has been invalidated!!"); if (key == null) throw new NullPointerException( "Name of attribute to bind cant be null!!!"); if (attribute == null) throw new NullPointerException( "Attribute that is to be bound cant be null!!!"); // Construct an event with the new value SipApplicationSessionBindingEvent event = null; // Call the valueBound() method if necessary if (attribute instanceof SipApplicationSessionBindingListener) { // Don't call any notification if replacing with the same value Object oldValue = sipApplicationSessionAttributeMap.get(key); if (attribute != oldValue) { event = new SipApplicationSessionBindingEvent(this, key); try { ((SipApplicationSessionBindingListener) attribute).valueBound(event); } catch (Throwable t){ logger.error("SipSessionBindingListener threw exception", t); } } } Object previousValue = this.sipApplicationSessionAttributeMap.put(key, attribute); if (previousValue != null && previousValue != attribute && previousValue instanceof SipApplicationSessionBindingListener) { try { ((SipApplicationSessionBindingListener) previousValue).valueUnbound (new SipApplicationSessionBindingEvent(this, key)); } catch (Throwable t) { logger.error("SipSessionBindingListener threw exception", t); } } SipListenersHolder listeners = sipContext.getListeners(); List<SipApplicationSessionAttributeListener> listenersList = listeners.getSipApplicationSessionAttributeListeners(); if(listenersList.size() > 0) { if(event == null) { event = new SipApplicationSessionBindingEvent(this, key); } if (previousValue == null) { for (SipApplicationSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipApplicationSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute added on key "+ key); } try { listener.attributeAdded(event); } catch (Throwable t) { logger.error("SipApplicationSessionAttributeListener threw exception", t); } } } else { for (SipApplicationSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipApplicationSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute replaced on key "+ key); } try { listener.attributeReplaced(event); } catch (Throwable t) { logger.error("SipApplicationSessionAttributeListener threw exception", t); } } } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#setExpires(int) */ public int setExpires(int deltaMinutes) { if(!isValid) { throw new IllegalStateException("Impossible to change the sip application " + "session timeout when it has been invalidated !"); } expired = false; if(logger.isDebugEnabled()) { logger.debug("Postponing the expiratin of the sip application session " + key +" to expire in " + deltaMinutes + " minutes."); } if(deltaMinutes <= 0) { if(logger.isDebugEnabled()) { logger.debug("The sip application session "+ key +" won't expire anymore "); } // If the session timeout value is 0 or less, then an application session timer // never starts for the SipApplicationSession object and the container // does not consider the object to ever have expired // this.expirationTime = -1; if(expirationTimerTask != null) { cancelExpirationTimer(); expirationTimerTask = null; } return Integer.MAX_VALUE; } else { long deltaMilliseconds = 0; if(expirationTimerTask != null) { //extending the app session life time // expirationTime = expirationTimerFuture.getDelay(TimeUnit.MILLISECONDS) + deltaMinutes * 1000 * 60; deltaMilliseconds = deltaMinutes * 1000 * 60; } else { //the app session was scheduled to never expire and now an expiration time is set deltaMilliseconds = deltaMinutes * 1000 * 60; } if(expirationTimerTask != null) { - expirationTime = System.currentTimeMillis() + sipApplicationSessionTimeout; + expirationTime = System.currentTimeMillis() + deltaMilliseconds; if(logger.isDebugEnabled()) { logger.debug("Re-Scheduling sip application session "+ key +" to expire in " + deltaMinutes + " minutes"); logger.debug("Re-Scheduling sip application session "+ key +" will expires in " + deltaMilliseconds + " milliseconds"); logger.debug("sip application session "+ key +" will expires at " + expirationTime); } -// cancelExpirationTimer(); -// expirationTimerTask = null; -// expirationTimerFuture = null; -// expirationTimerTask = new SipApplicationSessionTimerTask(expirationTime); -// timer.schedule(expirationTimerTask, expirationTime); -// expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) ExecutorServiceWrapper.getInstance().schedule(expirationTimerTask, expirationTime, TimeUnit.MILLISECONDS); + cancelExpirationTimer(); + expirationTimerTask = null; + expirationTimerFuture = null; + expirationTimerTask = new SipApplicationSessionTimerTask(); + expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) sipContext.getThreadPoolExecutor().schedule(expirationTimerTask, deltaMilliseconds, TimeUnit.MILLISECONDS); } return deltaMinutes; } } public boolean hasTimerListener() { return this.sipContext.getListeners().getTimerListener() != null; } public SipContext getSipContext() { return sipContext; } void expirationTimerFired() { notifySipApplicationSessionListeners(SipApplicationSessionEventType.EXPIRATION); } /** * @return the key */ public SipApplicationSessionKey getKey() { return key; } /** * @param key the key to set */ public void setKey(SipApplicationSessionKey key) { this.key = key; } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getApplicationName() */ public String getApplicationName() { return key.getApplicationName(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipApplicationSession#getTimer(java.lang.String) */ public ServletTimer getTimer(String id) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return servletTimers.get(id); } /** * Perform the internal processing required to passivate * this session. */ public void passivate() { // Notify ActivationListeners SipApplicationSessionEvent event = null; Set<String> keySet = sipApplicationSessionAttributeMap.keySet(); for (String key : keySet) { Object attribute = sipApplicationSessionAttributeMap.get(key); if (attribute instanceof SipApplicationSessionActivationListener) { if (event == null) event = new SipApplicationSessionEvent(this); try { ((SipApplicationSessionActivationListener)attribute) .sessionWillPassivate(event); } catch (Throwable t) { logger.error("SipApplicationSessionActivationListener threw exception", t); } } } } /** * Perform internal processing required to activate this * session. */ public void activate() { // Notify ActivationListeners SipApplicationSessionEvent event = null; Set<String> keySet = sipApplicationSessionAttributeMap.keySet(); for (String key : keySet) { Object attribute = sipApplicationSessionAttributeMap.get(key); if (attribute instanceof SipApplicationSessionActivationListener) { if (event == null) event = new SipApplicationSessionEvent(this); try { ((SipApplicationSessionActivationListener)attribute) .sessionDidActivate(event); } catch (Throwable t) { logger.error("SipApplicationSessionActivationListener threw exception", t); } } } } public boolean getInvalidateWhenReady() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return invalidateWhenReady; } /** * {@inheritDoc} */ public Object getSession(String id, Protocol protocol) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } if(id == null) { throw new NullPointerException("id is null"); } if(protocol == null) { throw new NullPointerException("protocol is null"); } switch (protocol) { case SIP : return sipSessions.get(id); case HTTP : return httpSessions.get(JvmRouteUtil.removeJvmRoute(id)); } return null; } public boolean isReadyToInvalidate() { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } updateReadyToInvalidateState(); return readyToInvalidate; } public void setInvalidateWhenReady(boolean invalidateWhenReady) { if(!isValid) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } this.invalidateWhenReady = invalidateWhenReady; } public void onSipSessionReadyToInvalidate(MobicentsSipSession mobicentsSipSession) { removeSipSession(mobicentsSipSession); updateReadyToInvalidateState(); } private void updateReadyToInvalidateState() { if(isValid && !readyToInvalidate) { for(MobicentsSipSession sipSession : this.sipSessions.values()) { if(sipSession.isValid() && !sipSession.isReadyToInvalidate()) { if(logger.isDebugEnabled()) { logger.debug("Session not ready to be invalidated : " + sipSession.getKey()); } return; } } if(this.servletTimers.size() <= 0) { this.readyToInvalidate = true; } else { if(logger.isDebugEnabled()) { logger.debug(servletTimers.size() + " Timers still alive, cannot invalidate this application session " + key); } } } else { if(logger.isDebugEnabled()) { logger.debug("Sip application session already invalidated "+ key); } this.readyToInvalidate = true; } } public void tryToInvalidate() { if(isValid && invalidateWhenReady) { notifySipApplicationSessionListeners(SipApplicationSessionEventType.READYTOINVALIDATE); if(readyToInvalidate) { boolean allSipSessionsInvalidated = true; for(MobicentsSipSession sipSession:this.sipSessions.values()) { if(sipSession.isValid()) { allSipSessionsInvalidated = false; break; } } boolean allHttpSessionsInvalidated = true; for(HttpSession httpSession:this.httpSessions.values()) { ConvergedSession convergedSession = (ConvergedSession) httpSession; if(convergedSession.isValid()) { allHttpSessionsInvalidated = false; break; } } if(allSipSessionsInvalidated && allHttpSessionsInvalidated) { this.invalidate(); } } } } /** * @return the expired */ public boolean isExpired() { return expired; } /** * @param currentServletHandler the currentServletHandler to set */ public void setCurrentRequestHandler(String currentRequestHandler) { this.currentRequestHandler = currentRequestHandler; } /** * @return the currentServletHandler */ public String getCurrentRequestHandler() { return currentRequestHandler; } // public ThreadPoolExecutor getExecutorService() { // return executorService; // } /** * @return the semaphore */ public Semaphore getSemaphore() { return semaphore; } public MobicentsSipApplicationSessionFacade getSession() { if (facade == null){ if (SecurityUtil.isPackageProtectionEnabled()){ final MobicentsSipApplicationSession fsession = this; facade = (MobicentsSipApplicationSessionFacade)AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ return new MobicentsSipApplicationSessionFacade(fsession); } }); } else { facade = new MobicentsSipApplicationSessionFacade(this); } } return (facade); } protected String jvmRoute; public String getJvmRoute() { return this.jvmRoute; } public void setJvmRoute(String jvmRoute) { // Assign the new jvmRoute this.jvmRoute = jvmRoute; } @Override public boolean equals(Object obj) { if(obj instanceof MobicentsSipApplicationSession) { return ((MobicentsSipApplicationSession)obj).getKey().equals(getKey()); } return false; } @Override public int hashCode() { return getKey().hashCode(); } @Override public String toString() { return getId(); } }
false
false
null
null
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java index 677178f63..d4c7f8902 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java @@ -1,77 +1,93 @@ /* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package com.badlogic.gdx.scenes.scene2d.actions; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; public class Parallel extends Action { static final Pool<Parallel> pool = new Pool<Parallel>(false, 4, 100) { protected Parallel newObject () { return new Parallel(); } }; public static Parallel $ (Action... actions) { Parallel action = pool.add(); action.actions.clear(); + if(action.finished == null || action.finished.length < actions.length) + action.finished = new boolean[actions.length]; int len = actions.length; for (int i = 0; i < len; i++) action.actions.add(actions[i]); return action; } protected final List<Action> actions = new ArrayList<Action>(); + protected boolean[] finished; @Override public void setTarget (Actor actor) { int len = actions.size(); for (int i = 0; i < len; i++) actions.get(i).setTarget(actor); } @Override public void act (float delta) { int len = actions.size(); - for (int i = 0; i < len; i++) - if (!actions.get(i).isDone()) actions.get(i).act(delta); + for (int i = 0; i < len; i++) { + if (!actions.get(i).isDone()) { + actions.get(i).act(delta); + } else { + if(!finished[i]) { + actions.get(i).finish(); + finished[i] = true; + } + } + } } @Override public boolean isDone () { int len = actions.size(); for (int i = 0; i < len; i++) if (actions.get(i).isDone() == false) return false; return true; } @Override public void finish () { pool.removeValue(this, true); int len = 0; - for (int i = 0; i < len; i++) - actions.get(i).finish(); + for (int i = 0; i < len; i++) { + if(!finished[i]) + actions.get(i).finish(); + } if(listener != null) listener.completed(this); } @Override public Action copy () { Parallel action = pool.add(); action.actions.clear(); int len = actions.size(); + for(int i = 0; i < len; i++) + action.finished[i] = false; + len = actions.size(); for (int i = 0; i < len; i++) action.actions.add(actions.get(i).copy()); return action; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java index ffc9081bb..882f466fd 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java @@ -1,83 +1,82 @@ /* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package com.badlogic.gdx.scenes.scene2d.actions; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Pool; public class Sequence extends Action { static final Pool<Sequence> pool = new Pool<Sequence>(false, 4, 100) { protected Sequence newObject () { return new Sequence(); } }; protected final List<Action> actions = new ArrayList<Action>(); protected Actor target; protected int currAction = 0; public static Sequence $ (Action... actions) { Sequence action = pool.add(); action.actions.clear(); int len = actions.length; for (int i = 0; i < len; i++) action.actions.add(actions[i]); return action; } @Override public void setTarget (Actor actor) { this.target = actor; if (actions.size() > 0) actions.get(0).setTarget(target); this.currAction = 0; } @Override public void act (float delta) { if (actions.size() == 0) { currAction = 1; return; } actions.get(currAction).act(delta); if (actions.get(currAction).isDone()) { + actions.get(currAction).finish(); currAction++; if (currAction < actions.size()) actions.get(currAction).setTarget(target); } } @Override public boolean isDone () { return currAction >= actions.size(); } @Override public void finish () { pool.removeValue(this, true); - int len = 0; - for (int i = 0; i < len; i++) - actions.get(i).finish(); + int len = 0; if(listener != null) listener.completed(this); } @Override public Action copy () { Sequence action = pool.add(); action.actions.clear(); int len = actions.size(); for (int i = 0; i < len; i++) action.actions.add(actions.get(i).copy()); return action; } }
false
false
null
null
diff --git a/src/org/openstreetmap/josm/data/Preferences.java b/src/org/openstreetmap/josm/data/Preferences.java index 9139d040..93993363 100644 --- a/src/org/openstreetmap/josm/data/Preferences.java +++ b/src/org/openstreetmap/josm/data/Preferences.java @@ -1,403 +1,422 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.data; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map.Entry; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.gui.preferences.ProxyPreferences; import org.openstreetmap.josm.tools.ColorHelper; /** * This class holds all preferences for JOSM. * * Other classes can register their beloved properties here. All properties will be * saved upon set-access. * * @author imi */ public class Preferences { - + + /** + * Internal storage for the preferenced directory. + * Do not access this variable directly! + * @see #getPreferencesDirFile() + */ + private File preferencesDirFile = null; + public static interface PreferenceChangedListener { void preferenceChanged(String key, String newValue); } /** * Class holding one bookmarkentry. * @author imi */ public static class Bookmark { public String name; public double[] latlon = new double[4]; // minlat, minlon, maxlat, maxlon @Override public String toString() { return name; } } public final ArrayList<PreferenceChangedListener> listener = new ArrayList<PreferenceChangedListener>(); /** * Map the property name to the property object. */ protected final SortedMap<String, String> properties = new TreeMap<String, String>(); protected final SortedMap<String, String> defaults = new TreeMap<String, String>(); /** * Override some values on read. This is intended to be used for technology previews * where we want to temporarily modify things without changing the user's preferences * file. */ protected static final SortedMap<String, String> override = new TreeMap<String, String>(); static { //override.put("osm-server.version", "0.5"); //override.put("osm-server.additional-versions", ""); //override.put("osm-server.url", "http://openstreetmap.gryph.de/api"); //override.put("plugins", null); } /** * Return the location of the user defined preferences file */ public String getPreferencesDir() { final String path = getPreferencesDirFile().getPath(); if (path.endsWith(File.separator)) return path; return path + File.separator; } - public File getPreferencesDirFile() { - if (System.getenv("APPDATA") != null) - return new File(System.getenv("APPDATA"), "JOSM"); - return new File(System.getProperty("user.home"), ".josm"); - } - + public File getPreferencesDirFile() { + if (preferencesDirFile != null) + return preferencesDirFile; + String path; + path = System.getProperty("josm.home"); + if (path != null) { + preferencesDirFile = new File(path); + } else { + path = System.getenv("APPDATA"); + if (path != null) { + preferencesDirFile = new File(path, "JOSM"); + } else { + preferencesDirFile = new File(System.getProperty("user.home"), ".josm"); + } + } + return preferencesDirFile; + } + public File getPluginsDirFile() { return new File(getPreferencesDirFile(), "plugins"); } /** * @return A list of all existing directories where resources could be stored. */ public Collection<String> getAllPossiblePreferenceDirs() { LinkedList<String> locations = new LinkedList<String>(); locations.add(Main.pref.getPreferencesDir()); String s; if ((s = System.getenv("JOSM_RESOURCES")) != null) { if (!s.endsWith(File.separator)) s = s + File.separator; locations.add(s); } if ((s = System.getProperty("josm.resources")) != null) { if (!s.endsWith(File.separator)) s = s + File.separator; locations.add(s); } String appdata = System.getenv("APPDATA"); if (System.getenv("ALLUSERSPROFILE") != null && appdata != null && appdata.lastIndexOf(File.separator) != -1) { appdata = appdata.substring(appdata.lastIndexOf(File.separator)); locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"), appdata), "JOSM").getPath()); } locations.add("/usr/local/share/josm/"); locations.add("/usr/local/lib/josm/"); locations.add("/usr/share/josm/"); locations.add("/usr/lib/josm/"); return locations; } synchronized public boolean hasKey(final String key) { return override.containsKey(key) ? override.get(key) != null : properties.containsKey(key); } synchronized public String get(final String key) { putDefault(key, null); if (override.containsKey(key)) return override.get(key); if (!properties.containsKey(key)) return ""; return properties.get(key); } synchronized public String get(final String key, final String def) { putDefault(key, def); if (override.containsKey(key)) return override.get(key); final String prop = properties.get(key); if (prop == null || prop.equals("")) return def; return prop; } synchronized public Map<String, String> getAllPrefix(final String prefix) { final Map<String,String> all = new TreeMap<String,String>(); for (final Entry<String,String> e : properties.entrySet()) if (e.getKey().startsWith(prefix)) all.put(e.getKey(), e.getValue()); for (final Entry<String,String> e : override.entrySet()) if (e.getKey().startsWith(prefix)) if (e.getValue() == null) all.remove(e.getKey()); else all.put(e.getKey(), e.getValue()); return all; } synchronized public Map<String, String> getDefaults() { return defaults; } synchronized public void putDefault(final String key, final String def) { if(!defaults.containsKey(key) || defaults.get(key) == null) defaults.put(key, def); else if(def != null && !defaults.get(key).equals(def)) System.out.println("Defaults for " + key + " differ: " + def + " != " + defaults.get(key)); } synchronized public boolean getBoolean(final String key) { putDefault(key, null); if (override.containsKey(key)) return override.get(key) == null ? false : Boolean.parseBoolean(override.get(key)); return properties.containsKey(key) ? Boolean.parseBoolean(properties.get(key)) : false; } synchronized public boolean getBoolean(final String key, final boolean def) { putDefault(key, Boolean.toString(def)); if (override.containsKey(key)) return override.get(key) == null ? def : Boolean.parseBoolean(override.get(key)); return properties.containsKey(key) ? Boolean.parseBoolean(properties.get(key)) : def; } synchronized public void put(final String key, String value) { String oldvalue = properties.get(key); if(value != null && value.length() == 0) value = null; if(!((oldvalue == null && value == null) || (value != null && oldvalue != null && oldvalue.equals(value)))) { if (value == null) properties.remove(key); else properties.put(key, value); save(); firePreferenceChanged(key, value); } } synchronized public void put(final String key, final boolean value) { put(key, Boolean.toString(value)); } private final void firePreferenceChanged(final String key, final String value) { for (final PreferenceChangedListener l : listener) l.preferenceChanged(key, value); } /** * Called after every put. In case of a problem, do nothing but output the error * in log. */ public void save() { try { setSystemProperties(); final PrintWriter out = new PrintWriter(new FileWriter(getPreferencesDir() + "preferences"), false); for (final Entry<String, String> e : properties.entrySet()) { out.println(e.getKey() + "=" + e.getValue()); } out.close(); } catch (final IOException e) { e.printStackTrace(); // do not message anything, since this can be called from strange // places. } } public void load() throws IOException { properties.clear(); final BufferedReader in = new BufferedReader(new FileReader(getPreferencesDir()+"preferences")); int lineNumber = 0; ArrayList<Integer> errLines = new ArrayList<Integer>(); for (String line = in.readLine(); line != null; line = in.readLine(), lineNumber++) { final int i = line.indexOf('='); if (i == -1 || i == 0) { errLines.add(lineNumber); continue; } properties.put(line.substring(0,i), line.substring(i+1)); } if (!errLines.isEmpty()) { throw new IOException("Malformed config file at lines " + errLines); } setSystemProperties(); } public final void resetToDefault() { properties.clear(); properties.put("projection", "org.openstreetmap.josm.data.projection.Epsg4326"); properties.put("draw.segment.direction", "true"); properties.put("draw.wireframe", "false"); properties.put("layerlist.visible", "true"); properties.put("propertiesdialog.visible", "true"); properties.put("selectionlist.visible", "true"); properties.put("commandstack.visible", "true"); properties.put("osm-server.url", "http://www.openstreetmap.org/api"); if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) { properties.put("laf", "javax.swing.plaf.metal.MetalLookAndFeel"); } else { properties.put("laf", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } save(); } public Collection<Bookmark> loadBookmarks() throws IOException { File bookmarkFile = new File(getPreferencesDir()+"bookmarks"); if (!bookmarkFile.exists()) bookmarkFile.createNewFile(); BufferedReader in = new BufferedReader(new FileReader(bookmarkFile)); Collection<Bookmark> bookmarks = new LinkedList<Bookmark>(); for (String line = in.readLine(); line != null; line = in.readLine()) { StringTokenizer st = new StringTokenizer(line, ","); if (st.countTokens() < 5) continue; Bookmark b = new Bookmark(); b.name = st.nextToken(); try { for (int i = 0; i < b.latlon.length; ++i) b.latlon[i] = Double.parseDouble(st.nextToken()); bookmarks.add(b); } catch (NumberFormatException x) { // line not parsed } } in.close(); return bookmarks; } public void saveBookmarks(Collection<Bookmark> bookmarks) throws IOException { File bookmarkFile = new File(Main.pref.getPreferencesDir()+"bookmarks"); if (!bookmarkFile.exists()) bookmarkFile.createNewFile(); PrintWriter out = new PrintWriter(new FileWriter(bookmarkFile)); for (Bookmark b : bookmarks) { b.name.replace(',', '_'); out.print(b.name+","); for (int i = 0; i < b.latlon.length; ++i) out.print(b.latlon[i]+(i<b.latlon.length-1?",":"")); out.println(); } out.close(); } /** * Convenience method for accessing colour preferences. * * @param colName name of the colour * @param def default value * @return a Color object for the configured colour, or the default value if none configured. */ synchronized public Color getColor(String colName, Color def) { String colStr = get("color."+colName); if (colStr.equals("")) { put("color."+colName, ColorHelper.color2html(def)); return def; } return ColorHelper.html2color(colStr); } // only for compatibility. Don't use any more. @Deprecated public static Color getPreferencesColor(String colName, Color def) { return Main.pref.getColor(colName, def); } /** * Convenience method for accessing colour preferences. * * @param colName name of the colour * @param specName name of the special colour settings * @param def default value * @return a Color object for the configured colour, or the default value if none configured. */ synchronized public Color getColor(String colName, String specName, Color def) { String colStr = get("color."+specName); if(colStr.equals("")) { colStr = get("color."+colName); if (colStr.equals("")) { put("color."+colName, ColorHelper.color2html(def)); return def; } } putDefault("color."+colName, ColorHelper.color2html(def)); return ColorHelper.html2color(colStr); } synchronized public void putColor(String colName, Color val) { put("color."+colName, val != null ? ColorHelper.color2html(val) : null); } synchronized public int getInteger(String key, int def) { putDefault(key, Integer.toString(def)); String v = get(key); if(null == v) return def; try { return Integer.parseInt(v); } catch(NumberFormatException e) { // fall out } return def; } synchronized public double getDouble(String key, double def) { putDefault(key, Double.toString(def)); String v = get(key); if(null == v) return def; try { return Double.parseDouble(v); } catch(NumberFormatException e) { // fall out } return def; } private void setSystemProperties() { Properties sysProp = System.getProperties(); if (getBoolean(ProxyPreferences.PROXY_ENABLE)) { sysProp.put("proxySet", "true"); sysProp.put("http.proxyHost", get(ProxyPreferences.PROXY_HOST)); sysProp.put("proxyPort", get(ProxyPreferences.PROXY_PORT)); if (!getBoolean(ProxyPreferences.PROXY_ANONYMOUS)) { sysProp.put("proxyUser", get(ProxyPreferences.PROXY_USER)); sysProp.put("proxyPassword", get(ProxyPreferences.PROXY_PASS)); } } else { sysProp.put("proxySet", "false"); sysProp.remove("http.proxyHost"); sysProp.remove("proxyPort"); sysProp.remove("proxyUser"); sysProp.remove("proxyPassword"); } System.setProperties(sysProp); } }
false
false
null
null
diff --git a/src/haven/HavenPanel.java b/src/haven/HavenPanel.java index 3b484a7..e06afa2 100644 --- a/src/haven/HavenPanel.java +++ b/src/haven/HavenPanel.java @@ -1,329 +1,329 @@ package haven; import java.awt.GraphicsConfiguration; import java.awt.Cursor; import java.awt.Toolkit; import java.awt.event.*; import java.util.*; import javax.media.opengl.*; import javax.media.opengl.glu.GLU; public class HavenPanel extends GLCanvas implements Runnable { UI ui; boolean inited = false, rdr = false; int w, h; long fd = 20, fps = 0; int dth = 0, dtm = 0; public static int texhit = 0, texmiss = 0; Queue<InputEvent> events = new LinkedList<InputEvent>(); public Coord mousepos = new Coord(0, 0); public Profile prof = new Profile(300); private Profile.Frame curf; private SyncFSM fsm = null; public HavenPanel(int w, int h) { setSize(this.w = w, this.h = h); initgl(); setCursor(Toolkit.getDefaultToolkit().createCustomCursor(TexI.mkbuf(new Coord(1, 1)), new java.awt.Point(), "")); } private void initgl() { final Thread caller = Thread.currentThread(); addGLEventListener(new GLEventListener() { public void display(GLAutoDrawable d) { GL gl = d.getGL(); if(inited && rdr) redraw(gl); TexGL.disposeall(gl); } public void init(GLAutoDrawable d) { GL gl = d.getGL(); if(caller.getThreadGroup() instanceof haven.error.ErrorHandler) { haven.error.ErrorHandler h = (haven.error.ErrorHandler)caller.getThreadGroup(); h.lsetprop("gl.vendor", gl.glGetString(gl.GL_VENDOR)); h.lsetprop("gl.version", gl.glGetString(gl.GL_VERSION)); h.lsetprop("gl.renderer", gl.glGetString(gl.GL_RENDERER)); h.lsetprop("gl.exts", Arrays.asList(gl.glGetString(gl.GL_EXTENSIONS).split(" "))); } gl.glClearColor(0, 0, 0, 1); gl.glColor3f(1, 1, 1); gl.glPointSize(4); gl.setSwapInterval(1); gl.glEnable(GL.GL_BLEND); //gl.glEnable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } public void reshape(GLAutoDrawable d, int x, int y, int w, int h) { GL gl = d.getGL(); GLU glu = new GLU(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluOrtho2D(0, w, h, 0); } public void displayChanged(GLAutoDrawable d, boolean cp1, boolean cp2) {} }); } public void init() { setFocusTraversalKeysEnabled(false); ui = new UI(new Coord(w, h), null); addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } public void keyPressed(KeyEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } public void keyReleased(KeyEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } public void mouseReleased(MouseEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { checkfs(); synchronized(events) { events.add(e); } } public void mouseMoved(MouseEvent e) { checkfs(); synchronized(events) { events.add(e); } } }); addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { checkfs(); synchronized(events) { events.add(e); events.notifyAll(); } } }); inited = true; } private class SyncFSM implements FSMan { private FSMan wrapped; private boolean tgt; private SyncFSM(FSMan wrapped) { this.wrapped = wrapped; tgt = wrapped.hasfs(); } public void setfs() { tgt = true; } public void setwnd() { tgt = false; } public boolean hasfs() { return(tgt); } private void check() { synchronized(ui) { if(tgt && !wrapped.hasfs()) wrapped.setfs(); if(!tgt && wrapped.hasfs()) wrapped.setwnd(); } } } private void checkfs() { if(fsm != null) { fsm.check(); } } public void setfsm(FSMan fsm) { this.fsm = new SyncFSM(fsm); ui.fsm = this.fsm; } UI newui(Session sess) { ui = new UI(new Coord(w, h), sess); ui.root.gprof = prof; ui.fsm = this.fsm; return(ui); } void redraw(GL gl) { ui.tooltip = null; gl.glClear(GL.GL_COLOR_BUFFER_BIT); curf.tick("cls"); GOut g = new GOut(gl, getContext(), new Coord(800, 600)); synchronized(ui) { ui.draw(g); } curf.tick("draw"); if(Utils.getprop("haven.dbtext", "off").equals("on")) { if(Resource.qdepth() > 0) g.atext(String.format("RQ depth: %d (%d)", Resource.qdepth(), Resource.numloaded()), new Coord(10, 470), 0, 1); g.atext("FPS: " + fps, new Coord(10, 545), 0, 1); g.atext("Texhit: " + dth, new Coord(10, 530), 0, 1); g.atext("Texmiss: " + dtm, new Coord(10, 515), 0, 1); Runtime rt = Runtime.getRuntime(); long free = rt.freeMemory(), total = rt.totalMemory(); - g.atext(String.format("Mem: %,010d/%,010d/%,010d/%,010d", free, total - free, total, rt.maxMemory()), new Coord(10, 500), 0, 1); + g.atext(String.format("Mem: %,011d/%,011d/%,011d/%,011d", free, total - free, total, rt.maxMemory()), new Coord(10, 500), 0, 1); g.atext(String.format("LCache: %d/%d", Layered.cache.size(), Layered.cache.cached()), new Coord(10, 485), 0, 1); } Object tooltip = ui.tooltip; if(tooltip == null) tooltip = ui.tooltipat(mousepos); if(tooltip != null) { Tex tt = null; if(tooltip instanceof Text) { tt = ((Text)tooltip).tex(); } else if(tooltip instanceof Tex) { tt = (Tex)tooltip; } else if(tooltip instanceof String) { tt = (Text.render((String)tooltip)).tex(); } Coord sz = tt.sz(); Coord pos = mousepos.add(sz.inv()); g.chcolor(244, 247, 21, 192); g.rect(pos.add(-3, -3), sz.add(6, 6)); g.chcolor(35, 35, 35, 192); g.frect(pos.add(-2, -2), sz.add(4, 4)); g.chcolor(); g.image(tt, pos); } Resource curs = ui.root.getcurs(mousepos); if(!curs.loading) { Coord dc = mousepos.add(curs.layer(Resource.negc).cc.inv()); g.image(curs.layer(Resource.imgc).tex(), dc); } } void dispatch() { synchronized(events) { InputEvent e = null; while((e = events.poll()) != null) { if(e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; if(me.getID() == MouseEvent.MOUSE_PRESSED) { if((me.getX() < 10) && (me.getY() < 10)) throw(new RuntimeException("test")); ui.mousedown(me, new Coord(me.getX(), me.getY()), me.getButton()); } else if(me.getID() == MouseEvent.MOUSE_RELEASED) { ui.mouseup(me, new Coord(me.getX(), me.getY()), me.getButton()); } else if(me.getID() == MouseEvent.MOUSE_MOVED || me.getID() == MouseEvent.MOUSE_DRAGGED) { mousepos = new Coord(me.getX(), me.getY()); ui.mousemove(me, mousepos); } else if(me instanceof MouseWheelEvent) { ui.mousewheel(me, new Coord(me.getX(), me.getY()), ((MouseWheelEvent)me).getWheelRotation()); } } else if(e instanceof KeyEvent) { KeyEvent ke = (KeyEvent)e; if(ke.getID() == KeyEvent.KEY_PRESSED) { ui.keydown(ke); } else if(ke.getID() == KeyEvent.KEY_RELEASED) { ui.keyup(ke); } else if(ke.getID() == KeyEvent.KEY_TYPED) { ui.type(ke); } } ui.lastevent = System.currentTimeMillis(); } } } public void uglyjoglhack() throws InterruptedException { try { rdr = true; display(); } catch(GLException e) { if(e.getCause() instanceof InterruptedException) { throw((InterruptedException)e.getCause()); } else { e.printStackTrace(); throw(e); } } finally { rdr = false; } } public void run() { try { long now, fthen, then; int frames = 0; fthen = System.currentTimeMillis(); while(true) { then = System.currentTimeMillis(); curf = prof.new Frame(); synchronized(ui) { if(ui.sess != null) ui.sess.glob.oc.ctick(); dispatch(); } curf.tick("dsp"); uglyjoglhack(); curf.tick("aux"); frames++; now = System.currentTimeMillis(); if(now - then < fd) { synchronized(events) { events.wait(fd - (now - then)); } } curf.tick("wait"); if(now - fthen > 1000) { fps = frames; frames = 0; dth = texhit; dtm = texmiss; texhit = texmiss = 0; fthen = now; } curf.fin(); if(Thread.interrupted()) throw(new InterruptedException()); } } catch(InterruptedException e) {} } public GraphicsConfiguration getconf() { return(getGraphicsConfiguration()); } } diff --git a/src/haven/MapView.java b/src/haven/MapView.java index 5021db8..f9f7299 100644 --- a/src/haven/MapView.java +++ b/src/haven/MapView.java @@ -1,585 +1,590 @@ package haven; import static haven.MCache.cmaps; import static haven.MCache.tilesz; import haven.Resource.Tile; import haven.Resource.Tileset; import java.awt.Color; import java.util.*; public class MapView extends Widget implements DTarget { Coord mc, mousepos; List<Drawable> clickable = new ArrayList<Drawable>(); private int[] visol = new int[31]; private long olftimer = 0; private int olflash = 0; static Color[] olc = new Color[31]; Grabber grab = null; ILM mask; final MCache map; final Glob glob; Collection<Gob> plob = null; boolean plontile; int plrad = 0; int playergob = -1; Coord mousemoveorig = null; Coord mousemoveorigmc = null; public Profile prof = new Profile(300); private Profile.Frame curf; public static final Coord mapborder = new Coord(250, 150); static { Widget.addtype("mapview", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { - return(new MapView(c, (Coord)args[0], parent, (Coord)args[1], (Integer)args[2])); + Coord sz = (Coord)args[0]; + Coord mc = (Coord)args[1]; + int pgob = -1; + if(args.length > 2) + pgob = (Integer)args[2]; + return(new MapView(c, sz, parent, mc, pgob)); } }); olc[0] = new Color(255, 0, 128); olc[1] = new Color(0, 0, 255); olc[2] = new Color(255, 0, 0); olc[3] = new Color(128, 0, 255); olc[16] = new Color(0, 255, 0); olc[17] = new Color(255, 255, 0); } public interface Grabber { void mmousedown(Coord mc, int button); void mmouseup(Coord mc, int button); void mmousemove(Coord mc); } @SuppressWarnings("serial") private class Loading extends RuntimeException {} public MapView(Coord c, Coord sz, Widget parent, Coord mc, int playergob) { super(c, sz, parent); mask = new ILM(sz); this.mc = mc; this.playergob = playergob; setcanfocus(true); glob = ui.sess.glob; map = glob.map; } public static Coord m2s(Coord c) { return(new Coord((c.x * 2) - (c.y * 2), c.x + c.y)); } public static Coord s2m(Coord c) { return(new Coord((c.x / 4) + (c.y / 2), (c.y / 2) - (c.x / 4))); } static Coord viewoffset(Coord sz, Coord vc) { return(m2s(vc).inv().add(new Coord(sz.x / 2, sz.y / 2))); } public void grab(Grabber grab) { this.grab = grab; } public void release(Grabber grab) { if(this.grab == grab) this.grab = null; } public boolean mousedown(Coord c, int button) { setfocus(this); Drawable hit = null; for(Drawable d : clickable) { Gob g = d.gob; Coord ulc = g.sc.add(d.getoffset().inv()); if(c.isect(ulc, d.getsize())) { if(d.checkhit(c.add(ulc.inv()))) { hit = d; break; } } } Coord mc = s2m(c.add(viewoffset(sz, this.mc).inv())); if(grab != null) { grab.mmousedown(mc, button); } else if(button == 2) { mousemoveorig = c; mousemoveorigmc = null; } else if(plob != null) { Gob gob = null; for(Gob g : plob) gob = g; wdgmsg("place", gob.rc, button, ui.modflags()); } else { if(hit == null) wdgmsg("click", c, mc, button, ui.modflags()); else wdgmsg("click", c, mc, button, ui.modflags(), hit.gob.id, hit.gob.getc()); } return(true); } public boolean mouseup(Coord c, int button) { Coord mc = s2m(c.add(viewoffset(sz, this.mc).inv())); if(grab != null) { grab.mmouseup(mc, button); return(true); } else { if((button == 2) && (mousemoveorig != null)) { Coord off = c.add(mousemoveorig.inv()); if(mousemoveorigmc == null) this.mc = mc; mousemoveorig = null; } return(true); } } public void mousemove(Coord c) { Coord mc = s2m(c.add(viewoffset(sz, this.mc).inv())); this.mousepos = mc; Collection<Gob> plob = this.plob; if(grab != null) { grab.mmousemove(mc); } else if(mousemoveorig != null) { Coord off = c.add(mousemoveorig.inv()); if((mousemoveorigmc == null) && ((Math.abs(off.x) > 5) || (Math.abs(off.y) > 5))) mousemoveorigmc = this.mc; if(mousemoveorigmc != null) this.mc = mousemoveorigmc.add(s2m(off).inv()); } else if(plob != null) { Gob gob = null; for(Gob g : plob) gob = g; boolean plontile = this.plontile ^ ui.modshift; gob.move(plontile?tilify(mc):mc); } } public void move(Coord mc, boolean trimall) { this.mc = mc; Coord cc = mc.div(cmaps.mul(tilesz)); if(trimall) map.trimall(); else map.trim(cc); } private static Coord tilify(Coord c) { c = c.div(tilesz); c = c.mul(tilesz); c = c.add(tilesz.div(2)); return(c); } private void unflashol() { for(int i = 0; i < visol.length; i++) { if((olflash & (1 << i)) != 0) visol[i]--; } olflash = 0; olftimer = 0; } public void uimsg(String msg, Object... args) { if(msg == "move") { move((Coord)args[0], (Integer)args[1] != 0); } else if(msg == "flashol") { unflashol(); olflash = (Integer)args[0]; for(int i = 0; i < visol.length; i++) { if((olflash & (1 << i)) != 0) visol[i]++; } olftimer = System.currentTimeMillis() + (Integer)args[1]; } else if(msg == "place") { Collection<Gob> plob = this.plob; if(plob != null) { this.plob = null; glob.oc.lrem(plob); } plob = new LinkedList<Gob>(); plontile = (Integer)args[2] != 0; Gob gob = new Gob(glob, plontile?tilify(mousepos):mousepos); Resource res = Resource.load((String)args[0], (Integer)args[1]); gob.setattr(new ResDrawable(gob, res)); plob.add(gob); glob.oc.ladd(plob); if(args.length > 3) plrad = (Integer)args[3]; this.plob = plob; } else if(msg == "unplace") { if(plob != null) glob.oc.lrem(plob); plob = null; plrad = 0; } else { super.uimsg(msg, args); } } public void enol(int... overlays) { for(int ol : overlays) visol[ol]++; } public void disol(int... overlays) { for(int ol : overlays) visol[ol]--; } private int gettilen(Coord tc) { int r = map.gettilen(tc); if(r == -1) throw(new Loading()); return(r); } private Tile getground(Coord tc) { Tile r = map.getground(tc); if(r == null) throw(new Loading()); return(r); } private Tile[] gettrans(Coord tc) { Tile[] r = map.gettrans(tc); if(r == null) throw(new Loading()); return(r); } private int getol(Coord tc) { int ol = map.getol(tc); if(ol == -1) throw(new Loading()); return(ol); } private void drawtile(GOut g, Coord tc, Coord sc) { Tile t; t = getground(tc); //t = gettile(tc).ground.pick(0); g.image(t.tex(), sc); //g.setColor(FlowerMenu.pink); //Utils.drawtext(g, Integer.toString(t.i), sc); for(Tile tt : gettrans(tc)) { g.image(tt.tex(), sc); } } private void drawol(GOut g, Coord tc, Coord sc) { int ol; int i; double w = 2; ol = getol(tc); if(ol == 0) return; Coord c1 = sc; Coord c2 = sc.add(m2s(new Coord(0, tilesz.y))); Coord c3 = sc.add(m2s(new Coord(tilesz.x, tilesz.y))); Coord c4 = sc.add(m2s(new Coord(tilesz.x, 0))); for(i = 0; i < olc.length; i++) { if(olc[i] == null) continue; if(((ol & (1 << i)) == 0) || (visol[i] < 1)) continue; Color fc = new Color(olc[i].getRed(), olc[i].getGreen(), olc[i].getBlue(), 32); g.chcolor(fc); g.frect(c1, c2, c3, c4); if(((ol & ~getol(tc.add(new Coord(-1, 0)))) & (1 << i)) != 0) { g.chcolor(olc[i]); g.line(c2, c1, w); } if(((ol & ~getol(tc.add(new Coord(0, -1)))) & (1 << i)) != 0) { g.chcolor(olc[i]); g.line(c1.add(1, 0), c4.add(1, 0), w); } if(((ol & ~getol(tc.add(new Coord(1, 0)))) & (1 << i)) != 0) { g.chcolor(olc[i]); g.line(c4.add(1, 0), c3.add(1, 0), w); } if(((ol & ~getol(tc.add(new Coord(0, 1)))) & (1 << i)) != 0) { g.chcolor(olc[i]); g.line(c3, c2, w); } } g.chcolor(Color.WHITE); } private void drawplobeffect(GOut g) { if(plob == null) return; Gob gob = null; for(Gob tg : plob) gob = tg; if(gob.sc == null) return; if(plrad > 0) { g.chcolor(0, 255, 0, 32); g.fellipse(gob.sc, new Coord(plrad * 2, plrad)); g.chcolor(); } } public void drawmap(GOut g) { int x, y, i; int stw, sth; Coord oc, tc, ctc, sc; curf = prof.new Frame(); stw = (tilesz.x * 4) - 2; sth = tilesz.y * 2; oc = viewoffset(sz, mc); tc = mc.div(tilesz); tc.x += -(sz.x / (2 * stw)) - (sz.y / (2 * sth)) - 2; tc.y += (sz.x / (2 * stw)) - (sz.y / (2 * sth)); for(y = 0; y < (sz.y / sth) + 2; y++) { for(x = 0; x < (sz.x / stw) + 3; x++) { for(i = 0; i < 2; i++) { ctc = tc.add(new Coord(x + y, -x + y + i)); sc = m2s(ctc.mul(tilesz)).add(oc); sc.x -= tilesz.x * 2; drawtile(g, ctc, sc); } } } for(y = 0; y < (sz.y / sth) + 2; y++) { for(x = 0; x < (sz.x / stw) + 3; x++) { for(i = 0; i < 2; i++) { ctc = tc.add(new Coord(x + y, -x + y + i)); sc = m2s(ctc.mul(tilesz)).add(oc); drawol(g, ctc, sc); } } } curf.tick("map"); drawplobeffect(g); curf.tick("plobeff"); final ArrayList<Sprite.Part> sprites = new ArrayList<Sprite.Part>(); ArrayList<Drawable> clickable = new ArrayList<Drawable>(); ArrayList<Speaking> speaking = new ArrayList<Speaking>(); ArrayList<Lumin> lumin = new ArrayList<Lumin>(); Sprite.Drawer drawer = new Sprite.Drawer() { public void addpart(Sprite.Part p) { sprites.add(p); } }; synchronized(glob.oc) { for(Gob gob : glob.oc) { Coord dc = m2s(gob.getc()).add(oc); gob.sc = dc; gob.drawsetup(drawer, dc, sz); Drawable d = gob.getattr(Drawable.class); if(d != null) clickable.add(d); Speaking s = gob.getattr(Speaking.class); if(s != null) speaking.add(s); Lumin l = gob.getattr(Lumin.class); if(l != null) lumin.add(l); } Collections.sort(clickable, new Comparator<Drawable>() { public int compare(Drawable a, Drawable b) { if(a.gob.clprio != b.gob.clprio) return(a.gob.clprio - b.gob.clprio); return(b.gob.sc.y - a.gob.sc.y); } }); this.clickable = clickable; Collections.sort(sprites); curf.tick("sort"); for(Sprite.Part part : sprites) part.draw(g); if(Utils.getprop("haven.bounddb", "off").equals("on") && ui.modshift) { g.chcolor(255, 0, 0, 128); synchronized(glob.oc) { for(Gob gob : glob.oc) { Drawable d = gob.getattr(Drawable.class); Resource.Neg neg; if(d instanceof ResDrawable) { ResDrawable rd = (ResDrawable)d; if(rd.spr == null) continue; if(rd.spr.res == null) continue; neg = rd.spr.res.layer(Resource.negc); } else if(d instanceof Layered) { Layered lay = (Layered)d; if(lay.base.get() == null) continue; neg = lay.base.get().layer(Resource.negc); } else { continue; } if((neg.bs.x > 0) && (neg.bs.y > 0)) { Coord c1 = gob.getc().add(neg.bc); Coord c2 = gob.getc().add(neg.bc).add(neg.bs); g.frect(m2s(c1).add(oc), m2s(new Coord(c2.x, c1.y)).add(oc), m2s(c2).add(oc), m2s(new Coord(c1.x, c2.y)).add(oc)); } } } g.chcolor(); } curf.tick("draw"); mask.update(lumin); g.image(mask, Coord.z); for(Speaking s : speaking) { s.draw(g, s.gob.sc.add(s.off)); } curf.tick("aux"); curf.fin(); //System.out.println(curf); } } private double clip(double d, double min, double max) { if(d < min) return(min); if(d > max) return(max); return(d); } private Color mkc(double r, double g, double b, double a) { return(new Color((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255))); } private double anorm(double d) { return((d + 1) / 2); } private void fixlight() { Astronomy a = glob.ast; if(a == null) { mask.amb = new Color(0, 0, 0, 0); return; } double p2 = Math.PI * 2; double sa = -Math.cos(a.dt * p2); double la = anorm(-Math.cos(a.mp * p2)); double hs = Math.pow(Math.sin(a.dt * p2), 2); double nl = clip(-sa * 2, 0, 1); hs = clip((hs - 0.5) * 2, 0, 1); double ml = 0.1 + la * 0.2; sa = anorm(clip(sa * 1.5, -1, 1)); double ll = ml + ((1 - ml) * sa); mask.amb = mkc(hs * 0.4, hs * 0.2, nl * 0.25 * ll, 1 - ll); } public void drawarrows(GOut g) { Coord oc = viewoffset(sz, mc); Coord hsz = sz.div(2); double ca = -Coord.z.angle(hsz); for(Party.Member m : glob.party.memb.values()) { //Gob gob = glob.oc.getgob(id); if(m.getc() == null) continue; Coord sc = m2s(m.getc()).add(oc); if(!sc.isect(Coord.z, sz)) { double a = -hsz.angle(sc); Coord ac; if((a > ca) && (a < -ca)) { ac = new Coord(sz.x, hsz.y - (int)(Math.tan(a) * hsz.x)); } else if((a > -ca) && (a < Math.PI + ca)) { ac = new Coord(hsz.x - (int)(Math.tan(a - Math.PI / 2) * hsz.y), 0); } else if((a > -Math.PI - ca) && (a < ca)) { ac = new Coord(hsz.x + (int)(Math.tan(a + Math.PI / 2) * hsz.y), sz.y); } else { ac = new Coord(0, hsz.y + (int)(Math.tan(a) * hsz.x)); } g.chcolor(m.col); Coord bc = ac.add(Coord.sc(a, -10)); g.line(bc, bc.add(Coord.sc(a, -40)), 2); g.line(bc, bc.add(Coord.sc(a + Math.PI / 4, -10)), 2); g.line(bc, bc.add(Coord.sc(a - Math.PI / 4, -10)), 2); g.chcolor(Color.WHITE); } } } private void checkmappos() { Coord oc = m2s(mc).inv(); Gob player = glob.oc.getgob(playergob); int bt = -((sz.y / 2) - mapborder.y); int bb = (sz.y / 2) - mapborder.y; int bl = -((sz.x / 2) - mapborder.x); int br = (sz.x / 2) - mapborder.x; SlenHud slen = ui.root.findchild(SlenHud.class); if(slen != null) bb -= slen.foldheight(); if(player != null) { Coord sc = m2s(player.getc()).add(oc); if(sc.x < bl) mc = mc.add(s2m(new Coord(sc.x - bl, 0))); if(sc.x > br) mc = mc.add(s2m(new Coord(sc.x - br, 0))); if(sc.y < bt) mc = mc.add(s2m(new Coord(0, sc.y - bt))); if(sc.y > bb) mc = mc.add(s2m(new Coord(0, sc.y - bb))); } } public void draw(GOut g) { checkmappos(); Coord requl = mc.add(-500, -500).div(tilesz).div(cmaps); Coord reqbr = mc.add(500, 500).div(tilesz).div(cmaps); Coord cgc = new Coord(0, 0); for(cgc.y = requl.y; cgc.y <= reqbr.y; cgc.y++) { for(cgc.x = requl.x; cgc.x <= reqbr.x; cgc.x++) { if(map.grids.get(cgc) == null) map.request(new Coord(cgc)); } } if((olftimer != 0) && (olftimer < System.currentTimeMillis())) unflashol(); map.sendreqs(); try { fixlight(); drawmap(g); drawarrows(g); g.chcolor(Color.WHITE); if(Utils.getprop("haven.dbtext", "off").equals("on")) g.atext(mc.toString(), new Coord(10, 560), 0, 1); } catch(Loading l) { String text = "Loading..."; g.chcolor(Color.BLACK); g.frect(Coord.z, sz); g.chcolor(Color.WHITE); g.atext(text, sz.div(2), 0.5, 0.5); } super.draw(g); } public boolean drop(Coord cc, Coord ul) { wdgmsg("drop", ui.modflags()); return(true); } public boolean iteminteract(Coord cc, Coord ul) { Drawable hit = null; for(Drawable d : clickable) { Gob g = d.gob; Coord ulc = g.sc.add(d.getoffset().inv()); if(cc.isect(ulc, d.getsize())) { if(d.checkhit(cc.add(ulc.inv()))) { hit = d; break; } } } Coord mc = s2m(cc.add(viewoffset(sz, this.mc).inv())); if(hit == null) wdgmsg("itemact", cc, mc, ui.modflags()); else wdgmsg("itemact", cc, mc, ui.modflags(), hit.gob.id, hit.gob.getc()); return(true); } }
false
false
null
null
diff --git a/src/main/java/org/zkoss/fiddle/component/ClosableWindow.java b/src/main/java/org/zkoss/fiddle/component/ClosableWindow.java new file mode 100755 index 0000000..94e2163 --- /dev/null +++ b/src/main/java/org/zkoss/fiddle/component/ClosableWindow.java @@ -0,0 +1,10 @@ +package org.zkoss.fiddle.component; + +import org.zkoss.zul.Window; + +public class ClosableWindow extends Window{ + + public void onClose() { + this.setVisible(false); + } +} \ No newline at end of file diff --git a/src/main/java/org/zkoss/fiddle/composer/ViewResultComposer.java b/src/main/java/org/zkoss/fiddle/composer/ViewResultComposer.java index 8411e62..8bd1a63 100755 --- a/src/main/java/org/zkoss/fiddle/composer/ViewResultComposer.java +++ b/src/main/java/org/zkoss/fiddle/composer/ViewResultComposer.java @@ -1,102 +1,101 @@ package org.zkoss.fiddle.composer; import javax.servlet.http.HttpServletRequest; import org.zkoss.fiddle.composer.event.FiddleEventQueues; import org.zkoss.fiddle.composer.event.ShowResultEvent; import org.zkoss.fiddle.model.FiddleSandbox; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.EventQueue; import org.zkoss.zk.ui.event.EventQueues; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.A; import org.zkoss.zul.Div; import org.zkoss.zul.Iframe; import org.zkoss.zul.Label; import org.zkoss.zul.Textbox; import org.zkoss.zul.api.Window; public class ViewResultComposer extends GenericForwardComposer { private Textbox directly; private Iframe content; private Window viewEditor; private Label zkver; private Label msg; private A directlyLink; private Div directLinkContainer; /** * we use desktop level event queue. */ private EventQueue queue = EventQueues.lookup(FiddleEventQueues.SHOW_RESULT, true); private String hostpath; private String getHostpath(){ if (hostpath == null) { HttpServletRequest request = (HttpServletRequest) Executions.getCurrent().getNativeRequest(); StringBuffer hostName = new StringBuffer(request.getServerName()); if (request.getLocalPort() != 80) { hostName.append(":" + request.getLocalPort()); } if ("".equals(request.getContextPath())) { hostName.append("/" + request.getContextPath()); } else { hostName.append("/"); } hostpath = "http://" + hostName.toString() ; } return hostpath; } public void doAfterCompose(final Component comp) throws Exception { super.doAfterCompose(comp); //save the host name in member field. (it's coming from FiddleDispatcherFilter ) hostpath = (String) requestScope.get("hostName"); queue.subscribe(new EventListener() { public void onEvent(Event event) throws Exception { if (event instanceof ShowResultEvent) { ShowResultEvent evt = (ShowResultEvent) event; FiddleSandbox inst = evt.getInstance(); zkver.setValue(inst.getZKVersion()); viewEditor.setTitle("Running sandbox:" + inst.getName()); if(evt.getCase().getVersion() != 0){ String tokenpath = evt.getCase().getCaseUrl( inst.getZKVersion()); directly.setText( getHostpath() + "view/" + tokenpath + "?run=" + inst.getName()); directlyLink.setHref( getHostpath() + "direct/" + tokenpath + "?run=" + inst.getName()); directLinkContainer.setVisible(true); }else{ directLinkContainer.setVisible(false); } msg.setValue(""); //force it doing the update job msg.setValue("loading..."); content.setSrc(inst.getPath() + evt.getCase().getToken() + "/" + evt.getCase().getVersion()); - viewEditor.doModal(); } } }); } - public void onMinimize$viewEditor(ForwardEvent e) { + public void onClose$viewEditor(ForwardEvent e) { content.setSrc(""); } }
false
false
null
null
diff --git a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java index 2e3cfe856..b0fa710b0 100644 --- a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java +++ b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java @@ -1,559 +1,559 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.ui.wizards; import java.io.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.resource.*; import org.eclipse.jface.viewers.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.help.*; import org.eclipse.update.configuration.*; import org.eclipse.update.core.*; import org.eclipse.update.internal.operations.*; import org.eclipse.update.internal.ui.*; import org.eclipse.update.internal.ui.parts.*; import org.eclipse.update.operations.*; public class TargetPage extends BannerPage implements IDynamicPage { private TableViewer jobViewer; private TableViewer siteViewer; private IInstallConfiguration config; private ConfigListener configListener; private Label requiredSpaceLabel; private Label availableSpaceLabel; private IInstallFeatureOperation[] jobs; private Button addButton; private Button deleteButton; private HashSet added; class JobsContentProvider extends DefaultContentProvider implements IStructuredContentProvider { public Object[] getElements(Object parent) { return jobs; } } class SitesContentProvider extends DefaultContentProvider implements IStructuredContentProvider { public Object[] getElements(Object parent) { return config.getConfiguredSites(); } } class JobsLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object obj, int col) { UpdateLabelProvider provider = UpdateUI.getDefault().getLabelProvider(); IInstallFeatureOperation job = (IInstallFeatureOperation) obj; ImageDescriptor base = job.getFeature().isPatch() ? UpdateUIImages.DESC_EFIX_OBJ : UpdateUIImages.DESC_FEATURE_OBJ; int flags = 0; if (job.getTargetSite() == null) flags = UpdateLabelProvider.F_ERROR; return provider.get(base, flags); } public String getColumnText(Object obj, int col) { if (col == 0) { IFeature feature = ((IInstallFeatureOperation) obj).getFeature(); return feature.getLabel() + " " //$NON-NLS-1$ + feature.getVersionedIdentifier().getVersion().toString(); } return null; } } class SitesLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object obj, int col) { UpdateLabelProvider provider = UpdateUI.getDefault().getLabelProvider(); return provider.getLocalSiteImage((IConfiguredSite) obj); } public String getColumnText(Object obj, int col) { if (col == 0) { ISite site = ((IConfiguredSite) obj).getSite(); return new File(site.getURL().getFile()).toString(); } return null; } } class ConfigListener implements IInstallConfigurationChangedListener { public void installSiteAdded(IConfiguredSite csite) { siteViewer.add(csite); if (added == null) added = new HashSet(); added.add(csite); // set the site as target for all jobs without a target for (int i=0; jobs != null && i<jobs.length; i++) if (jobs[i].getTargetSite() == null && getSiteVisibility(csite, jobs[i])) { jobs[i].setTargetSite(csite); } jobViewer.refresh(); siteViewer.setSelection(new StructuredSelection(csite)); siteViewer.getControl().setFocus(); } public void installSiteRemoved(IConfiguredSite csite) { siteViewer.remove(csite); if (added != null) added.remove(csite); // remove the target site for all jobs that use it // set the site as target for all jobs without a target boolean refreshJobs = false; for (int i=0; jobs != null && i<jobs.length; i++) if (jobs[i].getTargetSite() == csite) { jobs[i].setTargetSite(null); refreshJobs = true; } pageChanged(); jobViewer.refresh(); if (refreshJobs) { jobViewer.getControl().setFocus(); } else siteViewer.getControl().setFocus(); } } /** * Constructor for ReviewPage2 */ public TargetPage(IInstallConfiguration config) { super("Target"); //$NON-NLS-1$ setTitle(UpdateUI.getString("InstallWizard.TargetPage.title")); //$NON-NLS-1$ setDescription(UpdateUI.getString("InstallWizard.TargetPage.desc")); //$NON-NLS-1$ this.config = config; UpdateUI.getDefault().getLabelProvider().connect(this); configListener = new ConfigListener(); } public void setJobs(IInstallFeatureOperation[] jobs) { this.jobs = jobs; } public void dispose() { UpdateUI.getDefault().getLabelProvider().disconnect(this); config.removeInstallConfigurationChangedListener(configListener); super.dispose(); } public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); - addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); + addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); - deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); + deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; } private void createJobViewer(Composite parent) { jobViewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 150; jobViewer.getTable().setLayoutData(gd); jobViewer.setContentProvider(new JobsContentProvider()); jobViewer.setLabelProvider(new JobsLabelProvider()); jobViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); IInstallFeatureOperation job = (IInstallFeatureOperation) selection.getFirstElement(); if (job != null) { siteViewer.setInput(job); //IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, job.getFeature()); IConfiguredSite affinitySite = UpdateUtils.getDefaultTargetSite(config, job, true); addButton.setEnabled(affinitySite == null); if (job.getTargetSite() != null) { siteViewer.setSelection(new StructuredSelection(job.getTargetSite())); } } } }); } private void createSiteViewer(Composite parent) { siteViewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 200; siteViewer.getTable().setLayoutData(gd); siteViewer.setContentProvider(new SitesContentProvider()); siteViewer.setLabelProvider(new SitesLabelProvider()); siteViewer.addFilter(new ViewerFilter() { public boolean select(Viewer v, Object parent, Object obj) { IInstallFeatureOperation job = (IInstallFeatureOperation) siteViewer.getInput(); return getSiteVisibility((IConfiguredSite) obj, job); } }); siteViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection ssel = (IStructuredSelection) event.getSelection(); selectTargetSite(ssel); jobViewer.refresh(); updateDeleteButton(ssel); } }); if (config != null) config.addInstallConfigurationChangedListener(configListener); } private void updateDeleteButton(IStructuredSelection selection) { boolean enable = added != null && !added.isEmpty(); if (enable) { for (Iterator iter = selection.iterator(); iter.hasNext();) { if (!added.contains(iter.next())) { enable = false; break; } } } deleteButton.setEnabled(enable); } public void setVisible(boolean visible) { if (visible) { initializeDefaultTargetSites(); jobViewer.setInput(jobs); if (jobViewer.getSelection().isEmpty() && jobs.length > 0) jobViewer.setSelection(new StructuredSelection(jobs[0])); } super.setVisible(visible); } private void verifyNotEmpty(boolean empty) { String errorMessage = null; if (empty) errorMessage = UpdateUI.getString("InstallWizard.TargetPage.location.empty"); //$NON-NLS-1$ setErrorMessage(errorMessage); setPageComplete(!empty); } private void selectTargetSite(IStructuredSelection selection) { IConfiguredSite site = (IConfiguredSite) selection.getFirstElement(); IInstallFeatureOperation job = (IInstallFeatureOperation) siteViewer.getInput(); if (job != null) { if (site != null) job.setTargetSite(site); pageChanged(); } updateStatus(site); } private void addTargetLocation() { DirectoryDialog dd = new DirectoryDialog(getContainer().getShell()); dd.setMessage(UpdateUI.getString("InstallWizard.TargetPage.location.message")); //$NON-NLS-1$ String path = dd.open(); if (path != null) { addConfiguredSite(getContainer().getShell(), config, new File(path)); } } private void removeSelection() throws CoreException { IStructuredSelection selection = (IStructuredSelection) siteViewer.getSelection(); for (Iterator iter = selection.iterator(); iter.hasNext();) { IConfiguredSite targetSite = (IConfiguredSite) iter.next(); config.removeConfiguredSite(targetSite); } } private IConfiguredSite addConfiguredSite( Shell shell, IInstallConfiguration config, File file) { try { IConfiguredSite csite = config.createConfiguredSite(file); IStatus status = csite.verifyUpdatableStatus(); if (status.isOK()) config.addConfiguredSite(csite); else throw new CoreException(status); return csite; } catch (CoreException e) { String title = UpdateUI.getString("InstallWizard.TargetPage.location.error.title"); //$NON-NLS-1$ ErrorDialog.openError(shell, title, null, e.getStatus()); UpdateUI.logException(e,false); return null; } } private void updateStatus(Object element) { if (element == null) { requiredSpaceLabel.setText(""); //$NON-NLS-1$ availableSpaceLabel.setText(""); //$NON-NLS-1$ return; } IConfiguredSite site = (IConfiguredSite) element; File file = new File(site.getSite().getURL().getFile()); long available = LocalSystemInfo.getFreeSpace(file); long required = computeRequiredSizeFor(site); if (required == -1) requiredSpaceLabel.setText(UpdateUI.getString("InstallWizard.TargetPage.unknownSize")); //$NON-NLS-1$ else requiredSpaceLabel.setText( UpdateUI.getFormattedMessage("InstallWizard.TargetPage.size", "" + required)); //$NON-NLS-1$ //$NON-NLS-2$ if (available == LocalSystemInfo.SIZE_UNKNOWN) availableSpaceLabel.setText(UpdateUI.getString("InstallWizard.TargetPage.unknownSize")); //$NON-NLS-1$ else availableSpaceLabel.setText( UpdateUI.getFormattedMessage("InstallWizard.TargetPage.size", "" + available)); //$NON-NLS-1$ //$NON-NLS-2$ } private long computeRequiredSizeFor(IConfiguredSite site) { long totalSize = 0; for (int i = 0; i < jobs.length; i++) { if (site.equals(jobs[i].getTargetSite())) { long jobSize = site.getSite().getInstallSizeFor(jobs[i].getFeature()); if (jobSize == -1) return -1; totalSize += jobSize; } } return totalSize; } private void pageChanged() { boolean empty = false; for (int i=0; jobs!=null && i<jobs.length; i++) { if (jobs[i].getTargetSite() == null) { empty = true; break; } IFeature feature = jobs[i].getFeature(); if (feature.isPatch()) { // Patches must go together with the features // they are patching. // Check current jobs IInstallFeatureOperation patchedFeatureJob = findPatchedFeature(feature); if (patchedFeatureJob != null && patchedFeatureJob.getTargetSite() != null && !jobs[i].getTargetSite().equals(patchedFeatureJob.getTargetSite())) { String msg = UpdateUI.getFormattedMessage( "InstallWizard.TargetPage.patchError", //$NON-NLS-1$ new String[] { feature.getLabel(), patchedFeatureJob.getFeature().getLabel()}); setErrorMessage(msg); setPageComplete(false); return; } // Check installed features IFeature patchedFeature = UpdateUtils.getPatchedFeature(feature); if (patchedFeature != null && !jobs[i].getTargetSite().equals(patchedFeature.getSite().getCurrentConfiguredSite())) { String msg = UpdateUI.getFormattedMessage( "InstallWizard.TargetPage.patchError2", //$NON-NLS-1$ new String[] { feature.getLabel(), patchedFeature.getLabel(), patchedFeature.getSite().getCurrentConfiguredSite().getSite().getURL().getFile()}); setErrorMessage(msg); setPageComplete(false); return; } } } verifyNotEmpty(empty); } void removeAddedSites() { if (added != null) { while (!added.isEmpty()) { Iterator it = added.iterator(); if (it.hasNext()) config.removeConfiguredSite((IConfiguredSite) it.next()); } } } private boolean getSiteVisibility(IConfiguredSite site, IInstallFeatureOperation job) { // Do not allow installing into a non-updateable site if (!site.isUpdatable()) return false; // If affinity site is known, only it should be shown IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, job.getFeature()); if (affinitySite != null) { // Must compare referenced sites because // configured sites themselves may come from // different configurations return site.getSite().equals(affinitySite.getSite()); } // Co-locate updates with the old feature if (job.getOldFeature() != null) { IConfiguredSite oldSite = UpdateUtils.getSiteWithFeature(config, job.getOldFeature().getVersionedIdentifier().getIdentifier()); return (site == oldSite); } // Allow installing into any site that is updateable and there is no affinity specified return true; } private void initializeDefaultTargetSites() { for (int i = 0; i < jobs.length; i++) { if (jobs[i].getTargetSite() != null) continue; IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, jobs[i].getFeature()); if (affinitySite != null) { jobs[i].setTargetSite(affinitySite); continue; } IConfiguredSite defaultSite = UpdateUtils.getDefaultTargetSite(config, jobs[i], false); if (defaultSite != null) { jobs[i].setTargetSite(defaultSite); continue; } jobs[i].setTargetSite(getFirstTargetSite(jobs[i])); } } private IConfiguredSite getFirstTargetSite(IInstallFeatureOperation job) { IConfiguredSite[] sites = config.getConfiguredSites(); for (int i = 0; i < sites.length; i++) { IConfiguredSite csite = sites[i]; if (getSiteVisibility(csite, job)) return csite; } return null; } public IInstallFeatureOperation findPatchedFeature(IFeature patch) { for (int i=0; i<jobs.length; i++) { IFeature target = jobs[i].getFeature(); if (!target.equals(patch) && UpdateUtils.isPatch(target, patch)) return jobs[i]; } return null; } }
false
true
public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; }
public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; }
diff --git a/service/src/main/java/com/pms/service/service/AbstractService.java b/service/src/main/java/com/pms/service/service/AbstractService.java index 0ebead10..3b51462f 100644 --- a/service/src/main/java/com/pms/service/service/AbstractService.java +++ b/service/src/main/java/com/pms/service/service/AbstractService.java @@ -1,758 +1,769 @@ package com.pms.service.service; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.validator.Arg; import org.apache.commons.validator.Field; import org.apache.commons.validator.Form; import org.apache.commons.validator.Validator; import org.apache.commons.validator.ValidatorAction; import org.apache.commons.validator.ValidatorException; import org.apache.commons.validator.ValidatorResources; import org.apache.commons.validator.ValidatorResult; import org.apache.commons.validator.ValidatorResults; import org.apache.poi.hssf.util.HSSFColor.ROYAL_BLUE; import com.pms.service.annotation.RoleValidConstants; import com.pms.service.dao.ICommonDao; import com.pms.service.dbhelper.DBQuery; import com.pms.service.dbhelper.DBQueryOpertion; import com.pms.service.dbhelper.DBQueryUtil; import com.pms.service.exception.ApiResponseException; import com.pms.service.mockbean.ApiConstants; import com.pms.service.mockbean.DBBean; import com.pms.service.mockbean.GroupBean; import com.pms.service.mockbean.ProjectBean; import com.pms.service.mockbean.PurchaseBack; import com.pms.service.mockbean.PurchaseRequest; import com.pms.service.mockbean.RoleBean; import com.pms.service.mockbean.SalesContractBean; import com.pms.service.mockbean.ShipBean; import com.pms.service.mockbean.UserBean; import com.pms.service.service.impl.PurchaseServiceImpl.PurchaseStatus; import com.pms.service.util.ApiThreadLocal; import com.pms.service.util.ApiUtil; import com.pms.service.util.DateUtil; import com.pms.service.validators.ValidatorUtil; public abstract class AbstractService { protected ICommonDao dao = null; protected ISalesContractService scs; public abstract String geValidatorFileName(); @SuppressWarnings({ "rawtypes", "deprecation" }) public void validate(Map<String, Object> map, String validatorForm) { ValidatorUtil.init(); if (map == null) { map = new HashMap<String, Object>(); } map.put("dao", this.getDao()); ValidatorResources resources = ValidatorUtil.initValidatorResources().get(geValidatorFileName()); // Create a validator with the ValidateBean actions for the bean // we're interested in. Validator validator = new Validator(resources, validatorForm); // Tell the validator which bean to validate against. validator.setParameter(Validator.BEAN_PARAM, map); ValidatorResults results = null; try { results = validator.validate(); } catch (ValidatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Start by getting the form for the current locale and Bean. Form form = resources.getForm(Locale.CHINA, validatorForm); // Iterate over each of the properties of the Bean which had messages. Iterator propertyNames = results.getPropertyNames().iterator(); while (propertyNames.hasNext()) { String propertyName = (String) propertyNames.next(); // Get the Field associated with that property in the Form Field field = form.getField(propertyName); // Get the result of validating the property. ValidatorResult result = results.getValidatorResult(propertyName); // Get all the actions run against the property, and iterate over // their names. Map actionMap = result.getActionMap(); Iterator keys = actionMap.keySet().iterator(); String msg = ""; while (keys.hasNext()) { String actName = (String) keys.next(); // Get the Action for that name. ValidatorAction action = resources.getValidatorAction(actName); String actionMsgKey = field.getArg(0).getKey() + "." + action.getName(); // Look up the formatted name of the field from the Field arg0 String prettyFieldName = ValidatorUtil.intiBundle().getString(field.getArg(0).getKey()); boolean customMsg = false; if (isArgExists(actionMsgKey, field)) { customMsg = true; prettyFieldName = ValidatorUtil.intiBundle().getString(actionMsgKey); } if (!result.isValid(actName)) { String message = "{0}"; if (!customMsg) { message = ValidatorUtil.intiBundle().getString(action.getMsg()); } Object[] argsss = { prettyFieldName }; try { msg = msg.concat(new String(MessageFormat.format(message, argsss).getBytes("ISO-8859-1"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } if (!ApiUtil.isEmpty(msg)) { throw new ApiResponseException(String.format("Validate [%s] failed with paramters [%s]", validatorForm, map), null, msg); } } map.remove("dao"); } private boolean isArgExists(String key, Field field) { Arg[] args = field.getArgs(""); for (Arg arg : args) { if (arg.getKey().equalsIgnoreCase(key)) { return true; } } return false; } protected boolean isCoo() { return inGroup(GroupBean.COO_VALUE); } //部门助理 protected boolean isProjectAssistant() { return inGroup(GroupBean.DEPARTMENT_ASSISTANT_VALUE); } protected boolean isAdmin() { return inGroup(GroupBean.GROUP_ADMIN_VALUE); } //采购 protected boolean isPurchase() { return inGroup(GroupBean.PURCHASE_VALUE); } //采购 protected boolean isPM() { return inGroup(GroupBean.PM); } //助理 protected boolean isDepartmentAssistant() { return inGroup(GroupBean.DEPARTMENT_ASSISTANT_VALUE); } //库管 protected boolean isDepotManager() { return inGroup(GroupBean.DEPOT_MANAGER_VALUE); } //财务 protected boolean isFinance() { return inGroup(GroupBean.FINANCE); } protected String getCurrentUserId() { return ApiThreadLocal.getCurrentUserId(); } protected boolean isInDepartment(String depart) { Map<String,Object> query = new HashMap<String,Object>(); query.put(UserBean.DEPARTMENT, depart); query.put(ApiConstants.MONGO_ID, ApiThreadLocal.getCurrentUserId()); return dao.exist(query, DBBean.USER); } private boolean inGroup(String groupName){ if(ApiThreadLocal.get(UserBean.USER_ID) == null){ return false; }else{ String userId = ApiThreadLocal.get(UserBean.USER_ID).toString(); Map<String, Object> query = new HashMap<String, Object>(); query.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); query.put(GroupBean.GROUP_NAME, groupName); Map<String, Object> group = this.dao.findOneByQuery(query, DBBean.USER_GROUP); String id = group == null? null : group.get(ApiConstants.MONGO_ID).toString(); Map<String, Object> userQuery = new HashMap<String, Object>(); userQuery.put(ApiConstants.MONGO_ID, userId); userQuery.put(UserBean.GROUPS, new DBQuery(DBQueryOpertion.IN, id)); return this.dao.exist(userQuery, DBBean.USER); } } private boolean inRole(String roleId) { if (ApiThreadLocal.get(UserBean.USER_ID) == null) { return false; } else { String userId = ApiThreadLocal.get(UserBean.USER_ID).toString(); Map<String, Object> query = new HashMap<String, Object>(); query.put(RoleBean.ROLE_ID, roleId); query.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); Map<String, Object> role = this.dao.findOneByQuery(query, DBBean.ROLE_ITEM); List<String> roles = listUserRoleIds(userId); if (role != null && role.get(ApiConstants.MONGO_ID) != null) { return roles.contains(role.get(ApiConstants.MONGO_ID).toString()); } return false; } } public List<String> listUserRoleIds(String userId) { Map<String, Object> query = new HashMap<String, Object>(); query.put(ApiConstants.MONGO_ID, userId); query.put(ApiConstants.LIMIT_KEYS, new String[] { UserBean.GROUPS }); Map<String, Object> user = dao.findOneByQuery(query, DBBean.USER); List<String> groups = (List<String>) user.get(UserBean.GROUPS); Map<String, Object> limitQuery = new HashMap<String, Object>(); limitQuery.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, groups)); limitQuery.put(ApiConstants.LIMIT_KEYS, new String[]{GroupBean.ROLES}); List<Object> list = dao.listLimitKeyValues(limitQuery, DBBean.USER_GROUP); List<String> roles = new ArrayList<String>(); for(Object role: list){ roles.addAll((Collection<? extends String>) role); } if(user.get(UserBean.OTHER_ROLES)!=null){ roles.addAll((List<? extends String>) user.get(UserBean.OTHER_ROLES)); } return roles; } /** * * @param params * 页面传递来的参数 * @param myRealQueryKey * 页面搜索外键的字段,比如数据存的是customerId,页面传递过来的是customerName,customerId就是myQueryKey,customerName 就是mySearchDataKey * @param mySearchDataKey * @param refSearchKey * @param db * 相关联的数据库 */ protected void mergeRefSearchQuery(Map<String, Object> params, String myRealQueryKey, String mySearchDataKey, String refSearchKey, String db) { if (params.get(mySearchDataKey) != null && !ApiUtil.isEmpty(params)) { if (params.get(mySearchDataKey) instanceof DBQuery) { DBQuery query = (DBQuery) params.get(mySearchDataKey); Map<String, Object> refQuery = new HashMap<String, Object>(); refQuery.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); refQuery.put(refSearchKey, new DBQuery(query.getOperation(), query.getValue())); params.remove(mySearchDataKey); params.put(myRealQueryKey, new DBQuery(DBQueryOpertion.IN, this.dao.listLimitKeyValues(refQuery, db))); } } } protected void mergeDataRoleQueryWithProject(Map<String, Object> param) { Map<String, Object> pmQuery = new HashMap<String, Object>(); if (isAdmin() || isFinance() || isPurchase() || isCoo() || isDepotManager() || isDepartmentAssistant()) { // query all data } else { pmQuery.put(ProjectBean.PROJECT_MANAGER, getCurrentUserId()); pmQuery.put(ApiConstants.CREATOR, getCurrentUserId()); // list creator or manager's data param.put(ProjectBean.PROJECT_MANAGER, DBQueryUtil.buildQueryObject(pmQuery, false)); } } protected void mergeDataRoleQueryWithProjectAndScType(Map<String, Object> param) { Map<String, Object> pmQuery = new HashMap<String, Object>(); if (isAdmin() || isFinance() || isPurchase() || isCoo() || isDepotManager() || isDepartmentAssistant()) { // query all data } else { pmQuery.put(ProjectBean.PROJECT_MANAGER, getCurrentUserId()); pmQuery.put(ApiConstants.CREATOR, getCurrentUserId()); Map<String, Object> userQuery = new HashMap<String, Object>(); userQuery.put(ApiConstants.MONGO_ID, getCurrentUserId()); userQuery.put(ApiConstants.LIMIT_KEYS, UserBean.DEPARTMENT); Map<String, Object> user = this.dao.findOneByQuery(userQuery, DBBean.USER); if (user.get(UserBean.DEPARTMENT) != null) { String dep = user.get(UserBean.DEPARTMENT).toString(); // FIXME: put into constants List<String> scTypesIn = new ArrayList<String>(); scTypesIn.add("弱电工程"); scTypesIn.add("产品集成(灯控/布线)"); scTypesIn.add("产品集成(楼控)"); scTypesIn.add("产品集成(其他)"); if (dep.equalsIgnoreCase(UserBean.USER_DEPARTMENT_PROJECT)) { pmQuery.put(SalesContractBean.SC_TYPE, new DBQuery(DBQueryOpertion.IN, scTypesIn)); } else { pmQuery.put(SalesContractBean.SC_TYPE, new DBQuery(DBQueryOpertion.NOT_IN, scTypesIn)); } } // list creator or manager's data param.put(ProjectBean.PROJECT_MANAGER, DBQueryUtil.buildQueryObject(pmQuery, false)); } } protected Map<String, Object> getMyApprovedQuery() { Map<String, Object> taskQuery = new HashMap<String, Object>(); taskQuery.put(ApiConstants.CREATOR, ApiThreadLocal.getCurrentUserId()); Map<String, Object> statusQuery = new HashMap<String, Object>(); statusQuery.put("status", new DBQuery(DBQueryOpertion.IN, new String[]{PurchaseRequest.STATUS_APPROVED, ShipBean.SHIP_STATUS_FINAL_APPROVE, PurchaseRequest.STATUS_IN_REPOSITORY})); statusQuery.put(PurchaseBack.paStatus, new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseStatus.approved.toString(), PurchaseStatus.firstApprove.toString(), PurchaseStatus.finalApprove.toString() })); //or query taskQuery.put("status", DBQueryUtil.buildQueryObject(statusQuery, false)); return taskQuery; } protected Map<String, Object> getMyRejectedQuey() { Map<String, Object> taskQuery = new HashMap<String, Object>(); taskQuery.put(ApiConstants.CREATOR, ApiThreadLocal.getCurrentUserId()); Map<String, Object> statusQuery = new HashMap<String, Object>(); statusQuery.put("status", new DBQuery(DBQueryOpertion.IN, new String[]{PurchaseRequest.STATUS_REJECTED, ShipBean.SHIP_STATUS_REJECT})); statusQuery.put(PurchaseBack.pbStatus, PurchaseStatus.rejected.toString()); statusQuery.put(PurchaseBack.paStatus, new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseStatus.rejected.toString(), PurchaseStatus.firstRejected.toString(), PurchaseStatus.finalRejected.toString() })); //or query taskQuery.put("status", DBQueryUtil.buildQueryObject(statusQuery, false)); return taskQuery; } protected Map<String, Object> getMyInprogressQuery(String db) { //我的待批 Map<String, Object> statusQuery = new HashMap<String, Object>(); Map<String, Object> ownerQuery = new HashMap<String, Object>(); ownerQuery.put(ApiConstants.CREATOR, ApiThreadLocal.getCurrentUserId()); //FIXME 根据部门查询数据 if (db.equalsIgnoreCase(DBBean.PURCHASE_REQUEST)) { if (inRole(RoleValidConstants.PURCHASE_REQUEST_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } mergeDataRoleQueryWithProjectAndScType(ownerQuery); } if (db.equalsIgnoreCase(DBBean.PURCHASE_ORDER)) { if (inRole(RoleValidConstants.PURCHASE_ORDER_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } mergeDataRoleQueryWithProjectAndScType(ownerQuery); } if (db.equalsIgnoreCase(DBBean.PURCHASE_CONTRACT)) { if (inRole(RoleValidConstants.PURCHASE_CONTRACT_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } } if (db.equalsIgnoreCase(DBBean.BORROWING)) { if (inRole(RoleValidConstants.BORROWING_MANAGEMENT_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } } if (db.equalsIgnoreCase(DBBean.PURCHASE_ALLOCATE)) { if (inRole(RoleValidConstants.PURCHASE_ALLOCATE_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } mergeDataRoleQueryWithProjectAndScType(ownerQuery); } if (db.equalsIgnoreCase(DBBean.REPOSITORY)) { if (inRole(RoleValidConstants.REPOSITORY_MANAGEMENT_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } } if (db.equalsIgnoreCase(DBBean.SHIP)) { if (inRole(RoleValidConstants.SHIP_MANAGEMENT_PROCESS) || inRole(RoleValidConstants.SHIP_MANAGEMENT_FINAL_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } } if (db.equalsIgnoreCase(DBBean.PURCHASE_BACK)) { if (inRole(RoleValidConstants.PURCHASE_BACK_PROCESS)) { ownerQuery.remove(ApiConstants.CREATOR); } mergeDataRoleQueryWithProjectAndScType(ownerQuery); statusQuery.put(PurchaseBack.pbStatus, PurchaseStatus.submited.toString()); } - if (db.equalsIgnoreCase(DBBean.PURCHASE_ALLOCATE)) { - if (inRole(RoleValidConstants.PURCHASE_ALLOCATE_PROCESS)) { - statusQuery.put(PurchaseBack.paStatus, PurchaseStatus.submited.toString()); - ownerQuery.remove(ApiConstants.CREATOR); - } else if (inRole(RoleValidConstants.PURCHASE_ALLOCATE_FINAL_PROCESS)) { - statusQuery.put(PurchaseBack.paStatus, PurchaseStatus.firstApprove.toString()); - ownerQuery.remove(ApiConstants.CREATOR); - } - }else{ + if (db.equalsIgnoreCase(DBBean.PURCHASE_ALLOCATE) || db.equalsIgnoreCase(DBBean.SHIP)) { + + if (db.equalsIgnoreCase(DBBean.PURCHASE_ALLOCATE)) { + if (inRole(RoleValidConstants.PURCHASE_ALLOCATE_PROCESS)) { + statusQuery.put(PurchaseBack.paStatus, PurchaseStatus.submited.toString()); + ownerQuery.remove(ApiConstants.CREATOR); + } else if (inRole(RoleValidConstants.PURCHASE_ALLOCATE_FINAL_PROCESS)) { + statusQuery.put(PurchaseBack.paStatus, PurchaseStatus.firstApprove.toString()); + ownerQuery.remove(ApiConstants.CREATOR); + } + } else { + if (inRole(RoleValidConstants.SHIP_MANAGEMENT_PROCESS)) { + statusQuery.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_SUBMIT); + ownerQuery.remove(ApiConstants.CREATOR); + } else if (inRole(RoleValidConstants.SHIP_MANAGEMENT_FINAL_PROCESS)) { + statusQuery.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_FINAL_APPROVE); + ownerQuery.remove(ApiConstants.CREATOR); + } + } + }else{ statusQuery.put("status", new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseRequest.STATUS_NEW, PurchaseRequest.STATUS_REPOSITORY_NEW, ShipBean.SHIP_STATUS_SUBMIT })); } // or query ownerQuery.put("status", DBQueryUtil.buildQueryObject(statusQuery, false)); return ownerQuery; } protected Map<String, Object> getMyDraftQuery() { // 我的草稿 Map<String, Object> taskQuery = new HashMap<String, Object>(); taskQuery.put(ApiConstants.CREATOR, ApiThreadLocal.getCurrentUserId()); Map<String, Object> statusQuery = new HashMap<String, Object>(); statusQuery.put("status", new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseRequest.STATUS_DRAFT, ShipBean.SHIP_STATUS_DRAFT })); statusQuery.put(PurchaseBack.pbStatus, PurchaseStatus.saved.toString()); // or query taskQuery.put("status", DBQueryUtil.buildQueryObject(statusQuery, false)); return taskQuery; } protected void mergeMyTaskQuery(Map<String, Object> param, String db) { if (ApiThreadLocal.getMyTask() != null) { String task = ApiThreadLocal.getMyTask(); if (task.equalsIgnoreCase("draft")) { param.putAll(getMyDraftQuery()); } else if (task.equalsIgnoreCase("inprogress")) { param.putAll(getMyInprogressQuery(db)); } else if (task.equalsIgnoreCase("rejected")) { param.putAll(getMyRejectedQuey()); } else if (task.equalsIgnoreCase("approved")) { param.putAll(getMyApprovedQuery()); } else if (task.equalsIgnoreCase("tip")) { } } } /** * 某个字段更新,相关联冗余存放该字段的地方都要同时更新。 * @param collections 冗余存放某字段,需要同时更新的 集合 * @param query 待更新记录的条件 * @param updateKey 更新字段 * @param updateValue 更新字段新的值 */ public void updateRelatedCollectionForTheSameField(String[] collections,Map<String, Object> query, String updateKey, String updateValue){ query.put(ApiConstants.LIMIT_KEYS, new String[] {ApiConstants.MONGO_ID}); for (int i=0; i<collections.length; i++){ String cName = collections[i]; List<Object> ids = dao.listLimitKeyValues(query, cName); for (Object id : ids){ Map<String, Object> updateQuery = new HashMap<String, Object>(); updateQuery.put(updateKey, updateValue); updateQuery.put(ApiConstants.MONGO_ID, id); dao.updateById(updateQuery, cName); } } } public Map<String, Integer> countEqByKey(Map<String, Object> query, String db, String queryKey, Map<String, Integer> count) { return countEqByKey(query, db, queryKey, count, null); } public Map<String, Integer> countEqByKey(Map<String, Object> query, String db, String queryKey, Map<String, Integer> count, Map<String, Object> compare) { query.put(ApiConstants.LIMIT_KEYS, SalesContractBean.SC_EQ_LIST); List<Object> list = this.dao.listLimitKeyValues(query, db); Map<String, Integer> eqCountMap = new HashMap<String, Integer>(); if(count != null){ eqCountMap = count; } if (list != null) { for (Object obj : list) { if (obj != null) { List<Map<String, Object>> eqlistMap = (List<Map<String, Object>>) obj; for (Map<String, Object> eqMap : eqlistMap) { boolean needCount = true; if(compare !=null && !compare.isEmpty()){ for(String key: compare.keySet()){ if(eqMap.get(key) == null){ needCount = false; }else if(!eqMap.get(key).equals(compare.get(key))){ needCount = false; } } }else{ needCount = true; } if (needCount) { if (eqCountMap.get(eqMap.get(ApiConstants.MONGO_ID).toString()) != null) { eqCountMap.put(eqMap.get(ApiConstants.MONGO_ID).toString(), ApiUtil.getInteger(eqMap.get(queryKey), 0) + ApiUtil.getInteger(eqCountMap.get(eqMap.get(ApiConstants.MONGO_ID).toString()), 0)); } else { eqCountMap.put(eqMap.get(ApiConstants.MONGO_ID).toString(), ApiUtil.getInteger(eqMap.get(queryKey), 0)); } } } } } } return eqCountMap; } public Map<String, Integer> countEqByKeyWithMultiKey(Map<String, Object> query, String db, String queryKey, Map<String, Integer> count, String[] keys) { query.put(ApiConstants.LIMIT_KEYS, SalesContractBean.SC_EQ_LIST); List<Object> list = this.dao.listLimitKeyValues(query, db); Map<String, Integer> eqCountMap = new HashMap<String, Integer>(); if (count != null) { eqCountMap = count; } if (list != null) { for (Object obj : list) { if (obj != null) { List<Map<String, Object>> eqlistMap = (List<Map<String, Object>>) obj; for (Map<String, Object> eqMap : eqlistMap) { String multKey = ""; if (keys != null && keys.length > 0) { for (String key : keys) { if (eqMap.get(key) != null) { multKey = multKey + eqMap.get(key).toString(); } } } String id = eqMap.get(ApiConstants.MONGO_ID).toString(); id = (id + multKey).trim(); if (eqCountMap.get(id) != null) { eqCountMap.put(id, ApiUtil.getInteger(eqMap.get(queryKey), 0) + ApiUtil.getInteger(eqCountMap.get(id), 0)); } else { eqCountMap.put(id, ApiUtil.getInteger(eqMap.get(queryKey), 0)); } } } } } return eqCountMap; } /** * * 根据设备清单中的某个key来过滤数据小于等于0的数据 * @param eqCostList * @param key */ public void removeEmptyEqList(List<Map<String, Object>> eqCostList, String key) { List<Map<String, Object>> removedList = new ArrayList<Map<String, Object>>(); for (Map<String, Object> data : eqCostList) { if(data.get(key) == null || ApiUtil.isEmpty(data.get(key))){ removedList.add(data); }else if (! key.equalsIgnoreCase("eqCostList") && ApiUtil.getInteger(data.get(key), 0) <= 0) { removedList.add(data); } } for (Map<String, Object> orderMap : removedList) { eqCostList.remove(orderMap); } } /** * * 根据设备清单中的某个key来过滤数据小于等于0的数据 * @param eqCostList * @param key */ public void removeEmptyEqList(Map<String, Object> eqListMap, String key) { if (eqListMap.get("eqcostList") != null) { List<Map<String, Object>> eqCostList = (List<Map<String, Object>>) eqListMap.get("eqcostList"); removeEmptyEqList(eqCostList, key); } } public String generateCode(String prefix, String db, String codeKey) { Map<String, Object> map = new HashMap<String, Object>(); String[] limitKeys = { codeKey }; Map<String, Object> queryMap = new HashMap<String, Object>(); int year = DateUtil.getNowYearString(); queryMap.put(codeKey, new DBQuery(DBQueryOpertion.LIKE, year)); Map<String, Object> re = dao.getLastRecordByCreatedOn(db, queryMap, limitKeys); String code = null; if (re != null) { code = (String) re.get(codeKey); } Integer scCodeNo = 0; if (re != null && !ApiUtil.isEmpty(code)) { String scCodeNoString = code.substring(code.lastIndexOf("-") + 1, code.length()); try { scCodeNo = Integer.parseInt(scCodeNoString); } catch (NumberFormatException e) { // TODO Auto-generated catch block // e.printStackTrace(); 旧数据会出异常,就pCodeNo=1 开始 } } scCodeNo = scCodeNo + 1; String codeNum = "000" + scCodeNo; codeNum = codeNum.substring(codeNum.length() - 4, codeNum.length()); String genCode = prefix + "-" + year + "-" + codeNum; while (this.dao.exist(codeKey, genCode, db)) { scCodeNo = scCodeNo + 1; codeNum = "000" + scCodeNo; codeNum = codeNum.substring(codeNum.length() - 4, codeNum.length()); genCode = prefix + "-" + year + "-" + codeNum; } return genCode; } public String recordComment(String action,String newComment,String oldComment){ StringBuilder str = new StringBuilder(); String name = ApiThreadLocal.getCurrentUserName(); if(oldComment != null) str.append(oldComment).append("\n"); str.append(DateUtil.getDateString(new Date())).append(" ").append(name).append("").append(action); if(newComment != null) str.append(": ").append(newComment); return str.toString(); } protected void mergeCreatorInfo(Map<String,Object> params){ List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); if(params.containsKey(ApiConstants.RESULTS_DATA)){ list = (List<Map<String,Object>>)params.get(ApiConstants.RESULTS_DATA); }else { list.add(params); } List<String> uIds = new ArrayList<String>(); for(Map<String,Object> obj : list){ String id = (String)obj.get(ApiConstants.CREATOR); if(!uIds.contains(id))uIds.add(id); } Map<String,Object> uQuery = new HashMap<String,Object>(); uQuery.put(ApiConstants.LIMIT_KEYS, new String[]{UserBean.USER_NAME}); uQuery.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, uIds)); Map<String,Object> users = dao.listToOneMapAndIdAsKey(uQuery, DBBean.USER); for(Map<String,Object> obj : list){ String id = (String)obj.get(ApiConstants.CREATOR); Map<String,Object> user = (Map<String,Object>)users.get(id); obj.put("creatorName", user.get(UserBean.USER_NAME)); } } public ISalesContractService getScs() { return scs; } public void setScs(ISalesContractService scs) { this.scs = scs; } public ICommonDao getDao() { return dao; } public void setDao(ICommonDao dao) { this.dao = dao; } } diff --git a/service/src/main/java/com/pms/service/service/impl/ShipServiceImpl.java b/service/src/main/java/com/pms/service/service/impl/ShipServiceImpl.java index f42da812..3a2b3657 100644 --- a/service/src/main/java/com/pms/service/service/impl/ShipServiceImpl.java +++ b/service/src/main/java/com/pms/service/service/impl/ShipServiceImpl.java @@ -1,494 +1,494 @@ package com.pms.service.service.impl; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.pms.service.dbhelper.DBQuery; import com.pms.service.dbhelper.DBQueryOpertion; import com.pms.service.exception.ApiResponseException; import com.pms.service.mockbean.ApiConstants; import com.pms.service.mockbean.ArrivalNoticeBean; import com.pms.service.mockbean.DBBean; import com.pms.service.mockbean.GroupBean; import com.pms.service.mockbean.PurchaseCommonBean; import com.pms.service.mockbean.PurchaseContract; import com.pms.service.mockbean.SalesContractBean; import com.pms.service.mockbean.ShipBean; import com.pms.service.mockbean.ShipCountBean; import com.pms.service.mockbean.UserBean; import com.pms.service.service.AbstractService; import com.pms.service.service.IArrivalNoticeService; import com.pms.service.service.IPurchaseContractService; import com.pms.service.service.IPurchaseService; import com.pms.service.service.IShipService; import com.pms.service.util.ApiUtil; import com.pms.service.util.DateUtil; import com.pms.service.util.EmailUtil; public class ShipServiceImpl extends AbstractService implements IShipService { private IPurchaseContractService pService; private IArrivalNoticeService arrivalService; private IPurchaseService purchaseService; public IPurchaseContractService getpService() { return pService; } public IPurchaseService getPurchaseService() { return purchaseService; } public void setPurchaseService(IPurchaseService purchaseService) { this.purchaseService = purchaseService; } public void setpService(IPurchaseContractService pService) { this.pService = pService; } public IArrivalNoticeService getArrivalService() { return arrivalService; } public void setArrivalService(IArrivalNoticeService arrivalService) { this.arrivalService = arrivalService; } @Override public String geValidatorFileName() { return "ship"; } public Map<String, Object> get(Map<String, Object> params) { Map<String, Object> result = dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), DBBean.SHIP); List<Map<String, Object>> mergeEqListBasicInfo = scs.mergeEqListBasicInfo(result.get(SalesContractBean.SC_EQ_LIST)); List<Map<String, Object>> list = laodShipRestEqLit(mergeEqListBasicInfo, result.get(ShipBean.SHIP_SALES_CONTRACT_ID).toString(), true); result.put(SalesContractBean.SC_EQ_LIST, list); if (result.get(ShipBean.SHIP_DELIVERY_START_DATE) != null) { if(result.get(ShipBean.SHIP_DELIVERY_START_DATE) instanceof String){ }else{ result.put(ShipBean.SHIP_DELIVERY_START_DATE, DateUtil.getStringByDate((Date) result.get(ShipBean.SHIP_DELIVERY_START_DATE))); } } if (result.get(ShipBean.SHIP_DELIVERY_TIME) != null) { if(result.get(ShipBean.SHIP_DELIVERY_TIME) instanceof String){ }else{ result.put(ShipBean.SHIP_DELIVERY_TIME, DateUtil.getStringByDate((Date) result.get(ShipBean.SHIP_DELIVERY_TIME))); } } return result; } public Map<String, Object> list(Map<String, Object> params) { mergeMyTaskQuery(params, DBBean.SHIP); if (isDepotManager()) { params.put(ShipBean.SHIP_TYPE, new DBQuery(DBQueryOpertion.NOT_EQUALS, ArrivalNoticeBean.SHIP_TYPE_1_0)); } else if (isPurchase()) { params.put(ShipBean.SHIP_TYPE, ArrivalNoticeBean.SHIP_TYPE_1_0); } return dao.list(params, DBBean.SHIP); } public Map<String, Object> update(Map<String, Object> params) { return dao.updateById(params, DBBean.SHIP); } public void destroy(Map<String, Object> params) { List<String> ids = new ArrayList<String>(); ids.add(String.valueOf(params.get(ApiConstants.MONGO_ID))); dao.deleteByIds(ids, DBBean.SHIP); } public Map<String, Object> create(Map<String, Object> params) { if (ApiUtil.isEmpty(params.get(ShipBean.SHIP_STATUS))) { params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_DRAFT); } if (params.get(ShipBean.SHIP_DELIVERY_START_DATE) != null) { params.put(ShipBean.SHIP_DELIVERY_START_DATE, DateUtil.getDate((String) params.get(ShipBean.SHIP_DELIVERY_START_DATE))); } if (params.get(ShipBean.SHIP_DELIVERY_TIME) != null) { params.put(ShipBean.SHIP_DELIVERY_TIME, DateUtil.getDate((String) params.get(ShipBean.SHIP_DELIVERY_TIME))); } if (params.get(ApiConstants.MONGO_ID) != null) { return update(params); } else { // 发货申请编号 String code = "FHSQ-"; String[] limitKeys = { ShipBean.SHIP_CODE }; Map<String, Object> lastRecord = dao.getLastRecordByCreatedOn(DBBean.SHIP, null, limitKeys); String scCode = (String) params.get(ShipBean.SHIP_SALES_CONTRACT_CODE); String[] scCodeArr = scCode.split("-"); if (scCodeArr.length > 3) { if (scCodeArr[2].length() > 2) { code += scCodeArr[2].substring(2); } else { int i = Integer.parseInt(scCodeArr[2]); code += String.format("%02d", i); } if (scCodeArr[3].length() > 2) { code += scCodeArr[3].substring(2); } else { int i = Integer.parseInt(scCodeArr[3]); code += String.format("%02d", i); } code += "-"; } if (ApiUtil.isEmpty(lastRecord)) { code += "0001"; } else { String shipCode = (String) lastRecord.get(ShipBean.SHIP_CODE); String codeNum = shipCode.substring(shipCode.length()-4, shipCode.length()); int i = 0; try { i = Integer.parseInt(codeNum); } catch (Exception e) { // TODO: handle exception } i++; String str = String.format("%04d", i); code += str; } params.put(ShipBean.SHIP_CODE, code); return dao.add(params, DBBean.SHIP); } } public Map<String, Object> listCanShipEq(Map<String, Object> params) { params.put(ArrivalNoticeBean.NOTICE_STATUS, ArrivalNoticeBean.NOTICE_STATUS_NORMAL); dao.list(params, DBBean.ARRIVAL_NOTICE); return null; } public Map<String, Object> eqlist(Map<String, Object> params) { String saleId = (String) params.get(ShipBean.SHIP_SALES_CONTRACT_ID); // 已到货 的 设备清单,来自于调拨申请,入库和直发到货通知 Map<String, Object> map = arrivalService.listEqListByScIDForShip(saleId); List<Map<String, Object>> purchaseEqList = (List<Map<String, Object>>) map.get(SalesContractBean.SC_EQ_LIST); purchaseEqList = scs.mergeEqListBasicInfo(purchaseEqList); List<Map<String, Object>> shipMergedEqList = laodShipRestEqLit(purchaseEqList, saleId, false); Map<String, Object> res = new HashMap<String, Object>(); res.put(ApiConstants.RESULTS_DATA, shipMergedEqList); return res; } private List<Map<String, Object>> laodShipRestEqLit(List<Map<String, Object>> purchaseEqList, String saleId, boolean loadExists) { Map<String, Object> query = new HashMap<String, Object>(); query.put(SalesContractBean.SC_ID, saleId); query.put(ApiConstants.LIMIT_KEYS, ArrivalNoticeBean.EQ_LIST); Map<String, Integer> arrivedCountMap = countEqByKeyWithMultiKey(query, DBBean.ARRIVAL_NOTICE, ArrivalNoticeBean.EQCOST_ARRIVAL_AMOUNT, null, new String[] { ArrivalNoticeBean.SHIP_TYPE }); // 已发货的数量统计 Map<String, Object> parameters = new HashMap<String, Object>(); - parameters.put(ShipBean.SHIP_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { ShipBean.SHIP_STATUS_SUBMIT, ShipBean.SHIP_STATUS_FIRST_APPROVE, ShipBean.SHIP_STATUS_FIRST_APPROVE, ShipBean.SHIP_STATUS_CLOSE })); + parameters.put(ShipBean.SHIP_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { ShipBean.SHIP_STATUS_SUBMIT, ShipBean.SHIP_STATUS_FIRST_APPROVE, ShipBean.SHIP_STATUS_FINAL_APPROVE, ShipBean.SHIP_STATUS_CLOSE })); parameters.put(ShipBean.SHIP_SALES_CONTRACT_ID, saleId); Map<String, Integer> shipedCountMap = countEqByKeyWithMultiKey(parameters, DBBean.SHIP, ShipBean.EQCOST_SHIP_AMOUNT, null, new String[] { ArrivalNoticeBean.SHIP_TYPE }); List<Map<String, Object>> shipMergedEqList = new ArrayList<Map<String, Object>>(); Set<String> shipIds = new HashSet<String>(); for (Map<String, Object> eqMap : purchaseEqList) { String shipType = ""; if (eqMap.get(ArrivalNoticeBean.SHIP_TYPE) != null) { shipType = eqMap.get(ArrivalNoticeBean.SHIP_TYPE).toString(); } Object id = eqMap.get(ApiConstants.MONGO_ID).toString() + shipType; if (!shipIds.contains(id.toString())) { shipIds.add(id.toString()); if (shipedCountMap.get(id) != null) { eqMap.put(ShipBean.SHIP_LEFT_AMOUNT, arrivedCountMap.get(id) - shipedCountMap.get(id)); if (!loadExists) { eqMap.put(ShipBean.EQCOST_SHIP_AMOUNT, arrivedCountMap.get(id) - shipedCountMap.get(id)); } } else { eqMap.put(ShipBean.SHIP_LEFT_AMOUNT, arrivedCountMap.get(id)); if (!loadExists) { eqMap.put(ShipBean.EQCOST_SHIP_AMOUNT, arrivedCountMap.get(id)); } } shipMergedEqList.add(eqMap); } } if (!loadExists) { removeEmptyEqList(shipMergedEqList, ShipBean.SHIP_LEFT_AMOUNT); } return shipMergedEqList; } public Map<String, Object> submit(Map<String, Object> params) { params.put(ShipBean.SHIP_DATE, ApiUtil.formateDate(new Date(), "yyy-MM-dd")); params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_SUBMIT); return create(params); } public Map<String, Object> approve(Map<String, Object> params) { Map<String, Object> oldShip = dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), new String[] { SalesContractBean.SC_EQ_LIST, ShipBean.SHIP_STATUS }, DBBean.SHIP); if (ShipBean.SHIP_STATUS_SUBMIT.equalsIgnoreCase((String) oldShip.get(ShipBean.SHIP_STATUS))) { params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_FIRST_APPROVE); this.dao.updateById(params, DBBean.SHIP); } else { params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_FINAL_APPROVE); this.dao.updateById(params, DBBean.SHIP); List<Map<String, Object>> eqMapList = (List<Map<String, Object>>) oldShip.get(SalesContractBean.SC_EQ_LIST); Map<String, Object> shipMap = new HashMap<String, Object>(); Set<String> contractIds = new HashSet<String>(); for (Map<String, Object> eq : eqMapList) { if (eq.get(PurchaseContract.PURCHASE_CONTRACT_TYPE) != null && eq.get(PurchaseContract.PURCHASE_CONTRACT_TYPE).toString().equalsIgnoreCase(PurchaseCommonBean.CONTRACT_EXECUTE_BJ_MAKE)) { if (eq.get(PurchaseCommonBean.PURCHASE_CONTRACT_ID) != null) { contractIds.add(eq.get(PurchaseCommonBean.PURCHASE_CONTRACT_ID).toString()); shipMap.put(eq.get(PurchaseCommonBean.PURCHASE_CONTRACT_ID).toString(), eq.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE)); } } } for (String contractId : contractIds) { // 只统计此订单下的同样的设备清单 Map<String, Object> compareMap = new HashMap<String, Object>(); compareMap.put("purchaseContractId", contractId); Map<String, Object> query = new HashMap<String, Object>(); query.put(ShipBean.SHIP_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { ShipBean.SHIP_STATUS_FIRST_APPROVE, ShipBean.SHIP_STATUS_CLOSE })); query.put("eqcostList.purchaseContractId", contractId); Map<String, Integer> repCountMap = countEqByKey(query, DBBean.SHIP, ShipBean.EQCOST_SHIP_AMOUNT, null, compareMap); Map<String, Object> conQuery = new HashMap<String, Object>(); conQuery.put(ApiConstants.MONGO_ID, contractId); Map<String, Integer> contractCountMap = countEqByKey(conQuery, DBBean.PURCHASE_CONTRACT, "eqcostApplyAmount", null); boolean sendMail = true; for (String key : contractCountMap.keySet()) { if (repCountMap.get(key) == null) { sendMail = false; break; } else { if (repCountMap.get(key) < contractCountMap.get(key)) { sendMail = false; break; } } } if (sendMail) { Map<String, Object> userQuery = new HashMap<String, Object>(); userQuery.put(UserBean.GROUPS, new DBQuery(DBQueryOpertion.IN, this.dao.findOne(GroupBean.GROUP_NAME, GroupBean.PURCHASE_VALUE, DBBean.USER_GROUP).get(ApiConstants.MONGO_ID))); userQuery.put(ApiConstants.LIMIT_KEYS, UserBean.EMAIL); List<Object> emails = this.dao.listLimitKeyValues(userQuery, DBBean.USER); String subject = String.format("采购合同 - %s -已发货完毕", shipMap.get(contractId)); String content = String.format("采购合同 - %s -已发货完毕", shipMap.get(contractId)); EmailUtil.sendMail(subject, emails, content); } } } return new HashMap<String, Object>(); } public Map<String, Object> reject(Map<String, Object> params){ params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_REJECT); return this.dao.updateById(params, DBBean.SHIP); } public Map<String, Object> record(Map<String, Object> params) { List<Map<String, Object>> eqlist = (List<Map<String, Object>>) params.get(ShipBean.SHIP_EQ_LIST); boolean close = true; // for (Map<String, Object> eq : eqlist) { // // Object shipType = eq.get(ArrivalNoticeBean.SHIP_TYPE); // if (!ApiUtil.isEmpty(shipType) // && (shipType.toString().equalsIgnoreCase(ArrivalNoticeBean.SHIP_TYPE_1) || shipType.toString().equalsIgnoreCase(ArrivalNoticeBean.SHIP_TYPE_1_0))) { // // 直发才需要检查数量 // int arrivalAmount = ApiUtil.getInteger(eq.get(ShipBean.SHIP_EQ_ACTURE_AMOUNT), 0); // int amount = ApiUtil.getInteger(eq.get(ShipBean.EQCOST_SHIP_AMOUNT), 0); // if (amount != arrivalAmount) { // close = false; // break; // } // } // } if (close) { params.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_CLOSE); } return dao.updateById(params, DBBean.SHIP); } // 统计三类虚拟的采购合同在每月的发货合计 public Map<String, Object> doCount(Map<String, Object> params) { Map<String, Object> shipCount = this.dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), DBBean.SHIP_COUNT); if (shipCount != null && shipCount.get("status").toString().equalsIgnoreCase("已结算")) { return shipCount; } String date = (String) shipCount.get(ShipCountBean.SHIP_COUNT_DATE); String shipType = (String) shipCount.get(ArrivalNoticeBean.SHIP_TYPE); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Date countDate = null; try { countDate = sdf.parse(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(countDate); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, 20); Date startDate = cal.getTime(); cal = Calendar.getInstance(); cal.setTime(countDate); cal.set(Calendar.DAY_OF_MONTH, 19); Date endDate = cal.getTime(); Map<String, Object> shipQuery = new HashMap<String, Object>(); Object[] dateQuery = { startDate, endDate }; shipQuery.put(ShipBean.SHIP_DELIVERY_START_DATE, new DBQuery(DBQueryOpertion.BETWEEN_AND, dateQuery)); if(shipType.equalsIgnoreCase(PurchaseCommonBean.CONTRACT_EXECUTE_ALLOCATE_BJ_REPO_VALUE)){ // 调拨 shipQuery.put(SalesContractBean.SC_EQ_LIST + "." + ArrivalNoticeBean.SHIP_TYPE, shipType); }else{ // 三类虚拟采购合同 shipQuery.put(SalesContractBean.SC_EQ_LIST + "." + PurchaseContract.PURCHASE_CONTRACT_TYPE, shipType); } // 申请状态 List<String> statusList = new ArrayList<String>(); // statusList.add(ShipBean.SHIP_STATUS_APPROVE); statusList.add(ShipBean.SHIP_STATUS_CLOSE); shipQuery.put(ShipBean.SHIP_STATUS, new DBQuery(DBQueryOpertion.IN, statusList)); String[] limitKeys = { SalesContractBean.SC_EQ_LIST }; shipQuery.put(ApiConstants.LIMIT_KEYS, limitKeys); Map<String, Object> shipMap = dao.list(shipQuery, DBBean.SHIP); List<Map<String, Object>> shipList = (List<Map<String, Object>>) shipMap.get(ApiConstants.RESULTS_DATA); int totalAmount = 0; int totalMonty = 0; if (!ApiUtil.isEmpty(shipList)) { List<Map<String, Object>> allShipEqList = new ArrayList<Map<String, Object>>(); for (Map<String, Object> ship : shipList) { List<Map<String, Object>> shipEqList = (List<Map<String, Object>>) ship.get(SalesContractBean.SC_EQ_LIST); for (Map<String, Object> shipEq : shipEqList) { allShipEqList.add(shipEq); //FIXME: 先取真实发货数 totalAmount += ApiUtil.getInteger(shipEq.get(ShipBean.EQCOST_SHIP_AMOUNT), 0); //FIXME: 采购单价 totalMonty += ApiUtil.getInteger(shipEq.get(ShipBean.EQCOST_SHIP_AMOUNT), 0) * ApiUtil.getInteger(shipEq.get("eqcostBasePrice"), 0); } } shipCount.put(ShipCountBean.SHIP_TOTAL_AMOUNT, totalAmount); shipCount.put(ShipCountBean.SHIP_TOTAL_MONEY, totalMonty); shipCount.put(SalesContractBean.SC_EQ_LIST, allShipEqList); dao.updateById(shipCount, DBBean.SHIP_COUNT); } return shipCount; } // 发货统计 public Map<String, Object> listShipCount(Map<String, Object> params) { return dao.list(params, DBBean.SHIP_COUNT); } public Map<String, Object> listCountEq(Map<String, Object> params) { String[] limitKeys = { SalesContractBean.SC_EQ_LIST }; Map<String, Object> countMap = dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), limitKeys, DBBean.SHIP_COUNT); Map<String, Object> res = new HashMap<String, Object>(); res.put(ApiConstants.RESULTS_DATA, scs.mergeEqListBasicInfo(countMap.get(SalesContractBean.SC_EQ_LIST))); return res; } public Map<String, Object> getShipCount(Map<String, Object> params) { return doCount(params); } public Map<String, Object> submitShipCount(Map<String, Object> params) { Map<String, Object> shipCount = new HashMap<String, Object>(); shipCount = this.dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), DBBean.SHIP_COUNT); String date = (String) shipCount.get(ShipCountBean.SHIP_COUNT_DATE); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Date countDate = null; try { countDate = sdf.parse(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(countDate); cal.add(Calendar.MONTH, 1); Date startDate = cal.getTime(); if (startDate.getTime() > new Date().getTime()) { throw new ApiResponseException("", "", "结算不能在当月做"); } shipCount = new HashMap<String, Object>(); shipCount.put("status", "已结算"); shipCount.put(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID)); this.dao.updateById(shipCount, DBBean.SHIP_COUNT); Map<String, Object> nextShipCount = new HashMap<String, Object>(); nextShipCount.put(ArrivalNoticeBean.SHIP_TYPE, shipCount.get(ArrivalNoticeBean.SHIP_TYPE)); nextShipCount.put(ShipCountBean.SHIP_COUNT_DATE, sdf.format(startDate)); nextShipCount.put(ShipCountBean.SHIP_TOTAL_AMOUNT, 0); nextShipCount.put(ShipCountBean.SHIP_TOTAL_MONEY, 0); nextShipCount.put("status", "未结算"); this.dao.add(nextShipCount, DBBean.SHIP_COUNT); return null; } }
false
false
null
null
diff --git a/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDAO.java b/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDAO.java index 41836f7f..616b78c7 100644 --- a/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDAO.java +++ b/bitrepository-audit-trail-service/src/main/java/org/bitrepository/audittrails/store/AuditTrailServiceDAO.java @@ -1,143 +1,143 @@ /* * #%L * Bitrepository Audit Trail Service * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package org.bitrepository.audittrails.store; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.AUDITTRAIL_CONTRIBUTOR_GUID; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.AUDITTRAIL_SEQUENCE_NUMBER; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.AUDITTRAIL_TABLE; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.CONTRIBUTOR_GUID; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.CONTRIBUTOR_ID; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.CONTRIBUTOR_PRESERVATION_SEQ; import static org.bitrepository.audittrails.store.AuditDatabaseConstants.CONTRIBUTOR_TABLE; import java.sql.SQLException; import java.util.Date; import java.util.List; import org.bitrepository.bitrepositoryelements.AuditTrailEvent; import org.bitrepository.bitrepositoryelements.AuditTrailEvents; import org.bitrepository.bitrepositoryelements.FileAction; import org.bitrepository.common.ArgumentValidator; import org.bitrepository.common.database.DBConnector; import org.bitrepository.common.database.DBSpecifics; import org.bitrepository.common.database.DatabaseSpecificsFactory; import org.bitrepository.common.database.DatabaseUtils; import org.bitrepository.common.settings.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Audit trail storages backed by a database for preserving */ public class AuditTrailServiceDAO implements AuditTrailStore { /** The log.*/ private Logger log = LoggerFactory.getLogger(getClass()); /** The connection to the database.*/ private DBConnector dbConnector; /** * Constructor. * @param settings The settings. */ public AuditTrailServiceDAO(Settings settings) { ArgumentValidator.checkNotNull(settings, "settings"); DBSpecifics dbSpecifics = DatabaseSpecificsFactory.retrieveDBSpecifics( settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditServiceDatabaseSpecifics()); dbConnector = new DBConnector(dbSpecifics, settings.getReferenceSettings().getAuditTrailServiceSettings().getAuditTrailServiceDatabaseUrl()); dbConnector.getConnection(); } @Override public List<AuditTrailEvent> getAuditTrails(String fileId, String contributorId, Long minSeqNumber, Long maxSeqNumber, String actorName, FileAction operation, Date startDate, Date endDate) { ExtractModel model = new ExtractModel(); model.setFileId(fileId); model.setContributorId(contributorId); model.setMinSeqNumber(minSeqNumber); model.setMaxSeqNumber(maxSeqNumber); model.setActorName(actorName); model.setOperation(operation); model.setStartDate(startDate); model.setEndDate(endDate); AuditDatabaseExtractor extractor = new AuditDatabaseExtractor(model, dbConnector.getConnection()); return extractor.extractAuditEvents(); } @Override public void addAuditTrails(AuditTrailEvents newAuditTrails) { ArgumentValidator.checkNotNull(newAuditTrails, "AuditTrailEvents newAuditTrails"); AuditDatabaseIngestor ingestor = new AuditDatabaseIngestor(dbConnector.getConnection()); for(AuditTrailEvent event : newAuditTrails.getAuditTrailEvent()) { ingestor.ingestAuditEvents(event); } } @Override public int largestSequenceNumber(String contributorId) { ArgumentValidator.checkNotNullOrEmpty(contributorId, "String contributorId"); String sql = "SELECT " + AUDITTRAIL_SEQUENCE_NUMBER + " FROM " + AUDITTRAIL_TABLE + " WHERE " + AUDITTRAIL_CONTRIBUTOR_GUID + " = ( SELECT " + CONTRIBUTOR_GUID + " FROM " + CONTRIBUTOR_TABLE + " WHERE " + CONTRIBUTOR_ID + " = ? ) ORDER BY " + AUDITTRAIL_SEQUENCE_NUMBER + " DESC"; Long seq = DatabaseUtils.selectFirstLongValue(dbConnector.getConnection(), sql, contributorId); if(seq != null) { return seq.intValue(); } return 0; } @Override public long getPreservationSequenceNumber(String contributorId) { ArgumentValidator.checkNotNullOrEmpty(contributorId, "String contributorId"); String sql = "SELECT " + CONTRIBUTOR_PRESERVATION_SEQ + " FROM " + CONTRIBUTOR_TABLE + " WHERE " - + CONTRIBUTOR_ID + " = ? ) "; + + CONTRIBUTOR_ID + " = ? "; Long seq = DatabaseUtils.selectLongValue(dbConnector.getConnection(), sql, contributorId); if(seq != null) { return seq.intValue(); } return 0; } @Override public void setPreservationSequenceNumber(String contributorId, long seqNumber) { ArgumentValidator.checkNotNullOrEmpty(contributorId, "String contributorId"); ArgumentValidator.checkNotNegative(seqNumber, "int seqNumber"); String sqlUpdate = "UPDATE " + CONTRIBUTOR_TABLE + " SET " + CONTRIBUTOR_PRESERVATION_SEQ + " = ? WHERE " + CONTRIBUTOR_ID + " = ? "; DatabaseUtils.executeStatement(dbConnector.getConnection(), sqlUpdate, seqNumber, contributorId); } @Override public void close() { try { dbConnector.getConnection().close(); } catch (SQLException e) { log.warn("Cannot close the database properly.", e); } } }
true
false
null
null
diff --git a/src/edu/grinnell/sandb/Utility.java b/src/edu/grinnell/sandb/Utility.java index 56d7a9c..975e62d 100644 --- a/src/edu/grinnell/sandb/Utility.java +++ b/src/edu/grinnell/sandb/Utility.java @@ -1,88 +1,92 @@ package edu.grinnell.sandb; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import android.graphics.Bitmap; import android.util.Log; public class Utility { public static String captializeWords(String s) { String[] words = s.split(" "); StringBuilder sb = new StringBuilder(); for(int i = 0; i < words.length; i++) { sb.append(words[i].substring(0, 1).toUpperCase()) .append(words[i].substring(1).toLowerCase()); if (i != words.length - 1) sb.append(" "); } return sb.toString(); } /* public static void showToast(Context c, int message) { Toast t; switch(message) { case Result.NO_ROUTE: t = Toast.makeText(c, R.string.noRoute, Toast.LENGTH_SHORT); t.setGravity(Gravity.TOP, 0, 70); t.show(); return; case Result.HTTP_ERROR: t = Toast.makeText(c, R.string.httpError, Toast.LENGTH_SHORT); t.setGravity(Gravity.TOP, 0, 70); t.show(); return; case Result.NO_MEAL_DATA: t = Toast.makeText(c, R.string.noMealContent, Toast.LENGTH_LONG); t.setGravity(Gravity.TOP, 0, 70); t.show(); return; default: return; } } */ public static String dateString(GregorianCalendar c) { StringBuilder sb = new StringBuilder(); sb.append(c.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())); sb.append(" "); sb.append(c.get(Calendar.DAY_OF_MONTH)); sb.append(", "); sb.append(c.get(Calendar.YEAR)); sb.append(" | "); sb.append(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault())); return sb.toString(); } public static Bitmap resizeBitmap(Bitmap bm, int maxWidth, int maxHeight) { + + if (bm == null) + return null; + int w = bm.getWidth(); int h = bm.getHeight(); float s, sw, sh; if (w > h && w > 0) { s = ((float)maxWidth)/w; sw = maxWidth; sh = h*s + 0.5f; } else if (h > 0){ s = ((float)maxWidth)/w; sw = w*s + 0.5f; sh = maxHeight; } else { s = 1; sw = w; sh = h; } try { return Bitmap.createScaledBitmap(bm, (int) sw, (int) sh, true); } catch (IllegalArgumentException iae) { Log.d("generate thumb", "width: " + w + ", height: " + h + ", scale: " + s + ", sh" + sh); return null; } } } \ No newline at end of file diff --git a/src/edu/grinnell/sandb/data/Image.java b/src/edu/grinnell/sandb/data/Image.java index c4bc952..95151f6 100644 --- a/src/edu/grinnell/sandb/data/Image.java +++ b/src/edu/grinnell/sandb/data/Image.java @@ -1,65 +1,66 @@ package edu.grinnell.sandb.data; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; /* Class to store the article images and image titles in a db */ public class Image { protected int id; protected int articleId; protected String url; protected byte[] image; protected String imgTitle; protected Image(int ArticleID, String articleURL, byte[] articleImage, String articleImgTitle) { articleId = ArticleID; url = articleURL; image = articleImage; imgTitle = articleImgTitle; } protected Image(int ID, int ArticleID, String articleURL, byte[] articleImage, String articleImgTitle) { this(ArticleID, articleURL, articleImage, articleImgTitle); id = ID; } public Drawable toDrawable(Context c) { Bitmap bm = toBitmap(); Drawable d = new BitmapDrawable(c.getResources(), bm); d.setBounds(0, 0, 0 + d.getIntrinsicWidth(), 0 + d.getIntrinsicHeight()); return d; } public Bitmap toBitmap() { - return BitmapFactory.decodeByteArray(image, 0, image.length); + return (image != null) ? BitmapFactory.decodeByteArray(image, 0, image.length) + : null; } public int getId() { return id; } public int getArticleId() { return articleId; } public String getURL() { return url; } public byte[] getImg() { return image; } public String getImgTitle() { return imgTitle; } }
false
false
null
null
diff --git a/bundles/net.ageto.gyrex.persistence.carbonado/src/net/ageto/gyrex/persistence/carbonado/storage/internal/CarbonadoRepositoryImpl.java b/bundles/net.ageto.gyrex.persistence.carbonado/src/net/ageto/gyrex/persistence/carbonado/storage/internal/CarbonadoRepositoryImpl.java index 506c07d..977c67c 100644 --- a/bundles/net.ageto.gyrex.persistence.carbonado/src/net/ageto/gyrex/persistence/carbonado/storage/internal/CarbonadoRepositoryImpl.java +++ b/bundles/net.ageto.gyrex.persistence.carbonado/src/net/ageto/gyrex/persistence/carbonado/storage/internal/CarbonadoRepositoryImpl.java @@ -1,227 +1,227 @@ /******************************************************************************* * Copyright (c) 2010 AGETO 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: * Gunnar Wagenknecht - initial API and implementation *******************************************************************************/ package net.ageto.gyrex.persistence.carbonado.storage.internal; import java.util.Collection; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.sql.DataSource; import org.eclipse.gyrex.persistence.storage.content.RepositoryContentType; import org.eclipse.gyrex.persistence.storage.content.RepositoryContentTypeSupport; import org.eclipse.gyrex.persistence.storage.exceptions.ResourceFailureException; import org.eclipse.gyrex.persistence.storage.lookup.DefaultRepositoryLookupStrategy; import org.eclipse.gyrex.persistence.storage.lookup.RepositoryContentTypeAssignments; import org.eclipse.gyrex.persistence.storage.provider.RepositoryProvider; import org.eclipse.gyrex.persistence.storage.settings.IRepositoryPreferences; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.osgi.service.jdbc.DataSourceFactory; import org.apache.commons.lang.text.StrBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.ageto.gyrex.persistence.carbonado.internal.CarbonadoActivator; import net.ageto.gyrex.persistence.carbonado.internal.CarbonadoDebug; import net.ageto.gyrex.persistence.carbonado.storage.CarbonadoRepository; import net.ageto.gyrex.persistence.carbonado.storage.ICarbonadoRepositoryConstants; import net.ageto.gyrex.persistence.carbonado.storage.internal.jdbc.JdbcHelper; import net.ageto.gyrex.persistence.carbonado.storage.internal.jdbc.TracingDataSource; import net.ageto.gyrex.persistence.jdbc.pool.IPoolDataSourceFactoryConstants; import com.amazon.carbonado.Repository; import com.amazon.carbonado.repo.jdbc.JDBCRepositoryBuilder; public class CarbonadoRepositoryImpl extends CarbonadoRepository { private static final Logger LOG = LoggerFactory.getLogger(CarbonadoRepositoryImpl.class); private final CarbonadoRepositoryContentTypeSupport carbonadoRepositoryContentTypeSupport; private final AtomicReference<SchemaMigrationJob> schemaMigrationJobRef = new AtomicReference<SchemaMigrationJob>(); private volatile IStatus error; private final IRepositoryPreferences repositoryPreferences; public CarbonadoRepositoryImpl(final String repositoryId, final RepositoryProvider repositoryProvider, final IRepositoryPreferences repositoryPreferences) { super(repositoryId, repositoryProvider, new CarbonadoRepositoryMetrics(createMetricsId(repositoryProvider, repositoryId), repositoryId)); this.repositoryPreferences = repositoryPreferences; carbonadoRepositoryContentTypeSupport = new CarbonadoRepositoryContentTypeSupport(this); } private DataSource createDataSource() throws Exception { // check if we use a shared pool final String poolId = repositoryPreferences.get(JDBC_POOL_ID, null); if (null != poolId) { if (CarbonadoDebug.debug) { LOG.debug("Using connection pool {}...", poolId); } final DataSourceFactory dataSourceFactory = CarbonadoActivator.getInstance().getPoolDataSourceFactory(); final Properties dataSourceProperties = new Properties(); dataSourceProperties.put(IPoolDataSourceFactoryConstants.POOL_ID, poolId); dataSourceProperties.put(DataSourceFactory.JDBC_DATASOURCE_NAME, getRepositoryId()); dataSourceProperties.put(DataSourceFactory.JDBC_DESCRIPTION, String.format("DataSource for repository %s using database %s", getRepositoryId(), String.valueOf(repositoryPreferences.get(JDBC_DATABASE_NAME, null)))); dataSourceProperties.put(DataSourceFactory.JDBC_DATABASE_NAME, repositoryPreferences.get(JDBC_DATABASE_NAME, null)); return dataSourceFactory.createDataSource(dataSourceProperties); } // otherwise, fallback to old implementation return CarbonadoActivator.getInstance().getDataSourceSupport().createDataSource(getRepositoryId(), repositoryPreferences); } @Override protected Repository createRepository() throws Exception { // migrate old settings final String databaseName = repositoryPreferences.get("db_name", null); if (null != databaseName) { if (null == repositoryPreferences.get(JDBC_DATABASE_NAME, null)) { repositoryPreferences.put(JDBC_DATABASE_NAME, databaseName, false); } repositoryPreferences.remove("db_name"); repositoryPreferences.flush(); } // create the data source first final DataSource dataSource = createDataSource(); try { final JDBCRepositoryBuilder builder = new JDBCRepositoryBuilder(); builder.setDataSource(TracingDataSource.wrap(dataSource)); builder.setName(generateRepoName(getRepositoryId(), repositoryPreferences)); builder.setAutoVersioningEnabled(true, null); builder.setDataSourceLogging(CarbonadoDebug.dataSourceLogging); builder.setCatalog(repositoryPreferences.get(ICarbonadoRepositoryConstants.JDBC_DATABASE_NAME, null)); // MySQL database name return builder.build(); } catch (final Exception e) { // close data source on error (COLUMBUS-1177) JdbcHelper.closeQuietly(dataSource); throw e; } catch (final Error e) { // close data source on error (COLUMBUS-1177) JdbcHelper.closeQuietly(dataSource); throw e; } } private String generateRepoName(final String repositoryId, final IRepositoryPreferences preferences) { final StrBuilder name = new StrBuilder(); name.append(repositoryId); name.append(" (db "); name.append(preferences.get(ICarbonadoRepositoryConstants.JDBC_DATABASE_NAME, "<unknown>")); final String poolId = preferences.get(ICarbonadoRepositoryConstants.JDBC_POOL_ID, null); if (null != poolId) { name.append(", pool ").append(poolId); } else { name.append(", host "); name.append(preferences.get(CarbonadoRepository.HOSTNAME, "<unknown>")); name.append(", user "); name.append(preferences.get(CarbonadoRepository.USERNAME, "<unknown>")); } name.append(")"); return name.toString(); } @Override public RepositoryContentTypeSupport getContentTypeSupport() { return carbonadoRepositoryContentTypeSupport; } @Override protected Repository getOrCreateRepository() throws ResourceFailureException { - // overriden for package-visibility + // overridden for package-visibility return super.getOrCreateRepository(); } @Override protected IStatus getStatus() { // check for internal error final IStatus errorStatus = error; if (null != errorStatus) return errorStatus; // check for ongoing schema migration if (null != schemaMigrationJobRef.get()) return new Status(IStatus.CANCEL, CarbonadoActivator.SYMBOLIC_NAME, String.format("Schema verifivation in progress for repository '%s'.", getRepositoryId())); // ok return Status.OK_STATUS; } public void setError(final String message) { error = null != message ? new Status(IStatus.ERROR, CarbonadoActivator.SYMBOLIC_NAME, message) : null; } /** * Schedules a schema check with the repository. * * @param migrate * <code>true</code> if a schema migration should be performed * automatically, <code>false</code> otherwise * @param waitForFinish * <code>true</code> if the current thread should wait for the * schema verification to finish */ public IStatus verifySchema(final boolean migrate, final boolean waitForFinish) { // get all assigned content types final Collection<RepositoryContentType> contentTypes; try { final RepositoryContentTypeAssignments assignments = DefaultRepositoryLookupStrategy.getDefault().getContentTypeAssignments(getRepositoryId()); contentTypes = assignments.getContentTypes(true); - } catch (final IllegalStateException e) { + } catch (final Exception e) { // fail if case of unresolved content types throw new ResourceFailureException(e.getMessage()); } // quick check if (contentTypes.isEmpty()) // nothing to do return Status.OK_STATUS; final SchemaMigrationJob migrationJob = new SchemaMigrationJob(this, contentTypes, migrate); if (schemaMigrationJobRef.compareAndSet(null, migrationJob)) { final CountDownLatch waitSignal = new CountDownLatch(1); migrationJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { // reset reference when done schemaMigrationJobRef.compareAndSet(migrationJob, null); waitSignal.countDown(); } }); migrationJob.schedule(); if (!waitForFinish) return Job.ASYNC_FINISH; try { LOG.debug("Waiting for database '{}' to finish verifying schema.", getDescription()); if (!waitSignal.await(3, TimeUnit.MINUTES)) throw new ResourceFailureException(String.format("Timout waiting for database to verify schema. Please check database '%s'. ", getDescription())); return migrationJob.getSchemaStatus(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); return Status.CANCEL_STATUS; } } return Status.CANCEL_STATUS; } }
false
false
null
null
diff --git a/flex-checks/src/main/java/org/sonar/flex/checks/FieldNameCheck.java b/flex-checks/src/main/java/org/sonar/flex/checks/FieldNameCheck.java index 9fa04696..783dada5 100644 --- a/flex-checks/src/main/java/org/sonar/flex/checks/FieldNameCheck.java +++ b/flex-checks/src/main/java/org/sonar/flex/checks/FieldNameCheck.java @@ -1,92 +1,99 @@ /* * Sonar Flex Plugin * Copyright (C) 2010 SonarSource * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.flex.checks; import com.sonar.sslr.api.AstNode; import com.sonar.sslr.squid.checks.SquidCheck; import org.sonar.check.BelongsToProfile; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.check.RuleProperty; import org.sonar.flex.FlexGrammar; import org.sonar.flex.FlexKeyword; import org.sonar.sslr.parser.LexerlessGrammar; import java.util.List; import java.util.regex.Pattern; + @Rule( key = "S116", priority = Priority.MAJOR) @BelongsToProfile(title = CheckList.SONAR_WAY_PROFILE, priority = Priority.MAJOR) public class FieldNameCheck extends SquidCheck<LexerlessGrammar> { private static final String DEFAULT = "^[_a-z][a-zA-Z0-9]*$"; private Pattern pattern = null; @RuleProperty( key = "format", defaultValue = DEFAULT) String format = DEFAULT; @Override public void init() { subscribeTo(FlexGrammar.CLASS_DEF); } public void visitFile(AstNode astNode) { if (pattern == null) { pattern = Pattern.compile(format); } } @Override public void visitNode(AstNode astNode) { List<AstNode> classDirectives = astNode .getFirstChild(FlexGrammar.BLOCK) .getFirstChild(FlexGrammar.DIRECTIVES) .getChildren(FlexGrammar.DIRECTIVE); for (AstNode directive : classDirectives) { - if (directive.getFirstChild(FlexGrammar.ANNOTABLE_DIRECTIVE) != null - && directive.getFirstChild(FlexGrammar.ANNOTABLE_DIRECTIVE).getFirstChild().is(FlexGrammar.VARIABLE_DECLARATION_STATEMENT)) { - + if (isVariableDefinition(directive)) { AstNode variableDef = directive .getFirstChild(FlexGrammar.ANNOTABLE_DIRECTIVE) .getFirstChild(FlexGrammar.VARIABLE_DECLARATION_STATEMENT) .getFirstChild(FlexGrammar.VARIABLE_DEF); - if (variableDef.getFirstChild(FlexGrammar.VARIABLE_DEF_KIND).getFirstChild().is(FlexKeyword.VAR)) { - for (AstNode variableBindingNode : variableDef.getFirstChild(FlexGrammar.VARIABLE_BINDING_LIST).getChildren(FlexGrammar.VARIABLE_BINDING)) { - AstNode identifierNode = variableBindingNode - .getFirstChild(FlexGrammar.TYPED_IDENTIFIER) - .getFirstChild(FlexGrammar.IDENTIFIER); + for (AstNode variableBindingNode : variableDef.getFirstChild(FlexGrammar.VARIABLE_BINDING_LIST).getChildren(FlexGrammar.VARIABLE_BINDING)) { + AstNode identifierNode = variableBindingNode + .getFirstChild(FlexGrammar.TYPED_IDENTIFIER) + .getFirstChild(FlexGrammar.IDENTIFIER); - if (!pattern.matcher(identifierNode.getTokenValue()).matches()) { - getContext().createLineViolation(this, "Rename this field name to match the regular expression {0}", identifierNode, format); - } + if (!pattern.matcher(identifierNode.getTokenValue()).matches()) { + getContext().createLineViolation(this, "Rename this field name to match the regular expression {0}", identifierNode, format); } } } } } + + private static boolean isVariableDefinition(AstNode directive) { + if (directive.getFirstChild(FlexGrammar.ANNOTABLE_DIRECTIVE) != null) { + AstNode annotableDir = directive.getFirstChild(FlexGrammar.ANNOTABLE_DIRECTIVE).getFirstChild(); + + return annotableDir.is(FlexGrammar.VARIABLE_DECLARATION_STATEMENT) + && annotableDir.getFirstChild(FlexGrammar.VARIABLE_DEF).getFirstChild(FlexGrammar.VARIABLE_DEF_KIND).getFirstChild().is(FlexKeyword.VAR); + } + return false; + } }
false
false
null
null
diff --git a/src/cz/krtinec/birthday/dto/BContact.java b/src/cz/krtinec/birthday/dto/BContact.java index 332eafe..2cebb71 100644 --- a/src/cz/krtinec/birthday/dto/BContact.java +++ b/src/cz/krtinec/birthday/dto/BContact.java @@ -1,86 +1,86 @@ package cz.krtinec.birthday.dto; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public final class BContact extends BContactParent implements Comparable<BContact>{ public static final DateFormat SHORT_FORMAT = new SimpleDateFormat("MMdd"); private static final Calendar TODAY = Calendar.getInstance(); static Calendar tempCalendar = new GregorianCalendar(); private Date bDay; private Integer age; private Integer daysToBirthday; private DateIntegrity integrity; private String bDaySort; private String pivot = SHORT_FORMAT.format(TODAY.getTime()); private boolean nextYear; public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); - age = nextYear ? age : age + 1; + age = nextYear ? age + 1: age; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } } public Date getbDay() { return bDay; } public Integer getAge() { return age; } public int getDaysToBirthday() { return daysToBirthday; } @Override public String toString() { return displayName + ":" + bDay.toGMTString(); } @Override public int compareTo(BContact another) { if (this.nextYear && !another.nextYear) { return 1; } else if (!this.nextYear && another.nextYear) { return -1; } int bCompare = this.bDaySort.compareTo(another.bDaySort); if (bCompare == 0) { return this.displayName.compareTo(another.displayName); } else { return bCompare; } } }
true
true
public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); age = nextYear ? age : age + 1; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } }
public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); age = nextYear ? age + 1: age; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } }
diff --git a/microemulator/src/javax/microedition/lcdui/TextField.java b/microemulator/src/javax/microedition/lcdui/TextField.java index 608f7f9a..63e301cb 100644 --- a/microemulator/src/javax/microedition/lcdui/TextField.java +++ b/microemulator/src/javax/microedition/lcdui/TextField.java @@ -1,354 +1,354 @@ /* * MicroEmulator * Copyright (C) 2001 Bartek Teodorczyk <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (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 * * Contributor(s): * 3GLab */ package javax.microedition.lcdui; import com.barteo.emulator.device.Device; public class TextField extends Item { public static final int ANY = 0; public static final int EMAILADDR = 1; public static final int NUMERIC = 2; public static final int PHONENUMBER = 3; public static final int URL = 4; public static final int PASSWORD = 0x10000; public static final int CONSTRAINT_MASK = 0xffff; StringComponent stringComponent; String field; int caret; boolean caretVisible; int maxSize; int constraints; TextBox tb = null; static final Command doneCommand = new Command("Done", Command.OK, 0); static final Command cancelCommand = new Command("Cancel", Command.CANCEL, 0); CommandListener textBoxListener = new CommandListener() { public void commandAction(Command cmd, Displayable d) { if (cmd == doneCommand) { setString(tb.getString()); getOwner().currentDisplay.setCurrent(owner); } else if (cmd == cancelCommand) { getOwner().currentDisplay.setCurrent(owner); } } }; public TextField(String label, String text, int maxSize, int constraints) { super(label); if (maxSize <= 0) { throw new IllegalArgumentException(); } setConstraints(constraints); this.maxSize = maxSize; stringComponent = new StringComponent(); if (text != null) { setString(text); } else { setString(""); } stringComponent.setWidth(Device.screenPaintable.width - 8); caret = 0; caretVisible = false; } public String getString() { return field; } public void setString(String text) { validate(text); if (text == null) { field = ""; stringComponent.setText(""); } else { if (text.length() > maxSize) { throw new IllegalArgumentException(); } field = text; if ((constraints & PASSWORD) == 0) { stringComponent.setText(text); } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < text.length(); i++) { sb.append('*'); } stringComponent.setText(sb.toString()); } } repaint(); } public int getChars(char[] data) { - if (data.length > field.length()) { + if (data.length < field.length()) { throw new ArrayIndexOutOfBoundsException(); } getString().getChars(0, field.length(), data, 0); return field.length(); } public void setChars(char[] data, int offset, int length) { if (data == null) { setString(""); } else { if (length > maxSize) { throw new IllegalArgumentException(); } String newtext = new String(data, offset, length); validate(newtext); setString(newtext); } repaint(); } public void insert(String src, int position) { validate(src); if (field.length() + src.length() > maxSize) { throw new IllegalArgumentException(); } String newtext = ""; if (position > 0) { newtext = getString().substring(0, position); } newtext += src; if (position < field.length()) { newtext += getString().substring(position + 1); } setString(newtext); repaint(); } public void insert(char[] data, int offset, int length, int position) { if (offset + length > data.length) { throw new ArrayIndexOutOfBoundsException(); } insert(new String(data, offset, length), position); } public void delete(int offset, int length) { if (offset + length > field.length()) { throw new StringIndexOutOfBoundsException(); } String newtext = ""; if (offset > 0) { newtext = getString().substring(0, offset); } if (offset + length < field.length()) { newtext += getString().substring(offset + length); } setString(newtext); repaint(); } public int getMaxSize() { return maxSize; } public int setMaxSize(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException(); } if (field.length() > maxSize) { setString(getString().substring(0, maxSize)); } this.maxSize = maxSize; return maxSize; } public int size() { return field.length(); } public int getCaretPosition() { return caret; } public void setConstraints(int constraints) { - if ((constraints & TextField.CONSTRAINT_MASK) < 0 || - (constraints & TextField.CONSTRAINT_MASK) > 4) { - throw new IllegalArgumentException(); + if ((constraints & TextField.CONSTRAINT_MASK) < ANY || + (constraints & TextField.CONSTRAINT_MASK) > URL) { + throw new IllegalArgumentException("constraints is an illegal value"); } this.constraints = constraints; } public int getConstraints() { return constraints; } public void setLabel(String label) { super.setLabel(label); } boolean isFocusable() { return true; } int getHeight() { return super.getHeight() + stringComponent.getHeight() + 8; } int paint(Graphics g) { super.paintContent(g); g.translate(0, super.getHeight()); if (isFocus()) { g.drawRect(1, 1, Device.screenPaintable.width - 3, stringComponent.getHeight() + 4); } g.translate(3, 3); paintContent(g); g.translate(-3, -3); g.translate(0, -super.getHeight()); return getHeight(); } void paintContent(Graphics g) { stringComponent.paint(g); if (caretVisible) { int x_pos = stringComponent.getCharPositionX(caret); int y_pos = stringComponent.getCharPositionY(caret); g.drawLine(x_pos, y_pos, x_pos, y_pos + Font.getDefaultFont().getHeight()); } } void setCaretPosition(int position) { caret = position; } void setCaretVisible(boolean state) { caretVisible = state; } boolean select() { if (tb == null) { tb = new TextBox(getLabel(), getString(), maxSize, constraints); tb.addCommand(doneCommand); tb.addCommand(cancelCommand); tb.setCommandListener(textBoxListener); } else { tb.setString(getString()); } getOwner().currentDisplay.setCurrent(tb); return true; } int traverse(int gameKeyCode, int top, int bottom, boolean action) { Font f = Font.getDefaultFont(); - if (gameKeyCode == 1) { + if (gameKeyCode == Canvas.UP) { if (top > 0) { return -top; } else { return Item.OUTOFITEM; } } - if (gameKeyCode == 6) { + if (gameKeyCode == Canvas.DOWN) { if (getHeight() > bottom) { return getHeight() - bottom; } else { return Item.OUTOFITEM; } } return 0; } void validate(String text) { // text is illegal for the specified constraints so IllegalArgumentException if ((constraints & CONSTRAINT_MASK) == ANY) { return; } /* if ((constraints & CONSTRAINT_MASK) == NUMERIC) { try { int tmp = Integer.parseInt(text); } catch (NumberFormatException e) { throw new IllegalArgumentException( "TextField limited to numeric values: text = " + text); } } */ /* @todo add more constraints checking */ } }
false
false
null
null
diff --git a/polly/src/polly/core/http/HttpManagerProvider.java b/polly/src/polly/core/http/HttpManagerProvider.java index 4dc15b42..4d238444 100644 --- a/polly/src/polly/core/http/HttpManagerProvider.java +++ b/polly/src/polly/core/http/HttpManagerProvider.java @@ -1,151 +1,159 @@ package polly.core.http; import java.io.File; import java.io.IOException; import org.apache.log4j.Logger; import de.skuzzle.polly.sdk.Configuration; import de.skuzzle.polly.sdk.ConfigurationProvider; import de.skuzzle.polly.sdk.MyPolly; import de.skuzzle.polly.sdk.constraints.AttributeConstraint; import de.skuzzle.polly.sdk.exceptions.DatabaseException; import polly.configuration.ConfigurationProviderImpl; +import polly.core.ModuleStates; import polly.core.ShutdownManagerImpl; import polly.core.http.actions.IRCPageHttpAction; import polly.core.http.actions.LoginHttpAction; import polly.core.http.actions.LogoutHttpAction; import polly.core.http.actions.RoleHttpAction; import polly.core.http.actions.RootHttpAction; import polly.core.http.actions.SessionPageHttpAction; import polly.core.http.actions.UserInfoPageHttpAction; import polly.core.http.actions.UserPageHttpAction; import polly.core.http.actions.ShutdownHttpAction; import polly.core.mypolly.MyPollyImpl; import polly.core.users.UserManagerImpl; import polly.moduleloader.AbstractProvider; import polly.moduleloader.ModuleLoader; import polly.moduleloader.SetupException; import polly.moduleloader.annotations.Module; import polly.moduleloader.annotations.Provide; import polly.moduleloader.annotations.Require; @Module( requires = { @Require(component = ConfigurationProviderImpl.class), - @Require(component = ShutdownManagerImpl.class) + @Require(component = ShutdownManagerImpl.class), + @Require(state = ModuleStates.PERSISTENCE_READY) }, provides = @Provide(component = HttpManagerImpl.class) ) public class HttpManagerProvider extends AbstractProvider { private final static Logger logger = Logger.getLogger(HttpManagerProvider.class .getName()); public final static String HTTP_CONFIG = "http.cfg"; public final static String HOME_PAGE = "HOME_PAGE"; private HttpManagerImpl httpManager; private Configuration serverCfg; public HttpManagerProvider(ModuleLoader loader) { - super("HTTP_SERVER_PROVIDER", loader, false); + super("HTTP_SERVER_PROVIDER", loader, true); } @Override public void setup() throws SetupException { ConfigurationProvider configProvider = this.requireNow( ConfigurationProviderImpl.class, true); try { this.serverCfg = configProvider.open(HTTP_CONFIG); } catch (IOException e) { throw new SetupException(e); } File templateRoot = new File( this.serverCfg.readString(Configuration.HTTP_TEMPLATE_ROOT)); int sessionTimeOut = this.serverCfg.readInt(Configuration.HTTP_SESSION_TIMEOUT); int port = this.serverCfg.readInt(Configuration.HTTP_PORT); String publicHost = this.serverCfg.readString(Configuration.HTTP_PUBLIC_HOST); String encoding = configProvider.getRootConfiguration().readString( Configuration.ENCODING); int cacheThreshold = serverCfg.readInt( Configuration.HTTP_SESSION_CACHE_THRESHOLD); this.httpManager = new HttpManagerImpl( templateRoot, publicHost, port, sessionTimeOut, encoding, cacheThreshold); this.provideComponent(this.httpManager); ShutdownManagerImpl shutdownManager = this.requireNow( ShutdownManagerImpl.class, true); shutdownManager.addDisposable(this.httpManager); } @Override public void run() throws Exception { // Add HOME_PAGE attribute AttributeConstraint constraint = new AttributeConstraint() { @Override public boolean accept(String value) { return httpManager.actionExists(value); } }; UserManagerImpl userManager = this.requireNow(UserManagerImpl.class, false); try { + logger.trace("Trying to add HOME_PAGE Attribute"); userManager.addAttribute(HOME_PAGE, "/", constraint); + logger.trace("Done"); } catch (DatabaseException e) { logger.warn("ignored exception", e); } MyPolly myPolly = this.requireNow(MyPollyImpl.class, false); // HACK: this avoids cyclic dependency this.httpManager.setMyPolly(myPolly); + logger.trace("Adding default http actions..."); this.httpManager.addHttpAction(new RootHttpAction(myPolly)); this.httpManager.addHttpAction(new LoginHttpAction(myPolly)); this.httpManager.addHttpAction(new LogoutHttpAction(myPolly)); this.httpManager.addHttpAction(new UserPageHttpAction(myPolly)); this.httpManager.addHttpAction(new UserInfoPageHttpAction(myPolly)); this.httpManager.addHttpAction(new IRCPageHttpAction(myPolly)); this.httpManager.addHttpAction(new RoleHttpAction(myPolly)); this.httpManager.addHttpAction(new SessionPageHttpAction(myPolly)); this.httpManager.addHttpAction(new ShutdownHttpAction(myPolly)); + logger.trace("Adding menu entries for default admin menu..."); this.httpManager.addMenuUrl("Admin", "Users"); this.httpManager.addMenuUrl("Admin", "IRC"); this.httpManager.addMenuUrl("Admin", "Logs"); this.httpManager.addMenuUrl("Admin", "Roles"); this.httpManager.addMenuUrl("Admin", "Sessions"); boolean start = this.serverCfg.readBoolean(Configuration.HTTP_START_SERVER); if (!start) { + logger.info("Webserver will not be started due to configuration settings"); return; } try { + logger.trace("Trying to start the http service..."); this.httpManager.startWebServer(); logger.info("Webserver started"); } catch (IOException e) { logger.error("Error while starting webserver: ", e); throw new SetupException(e); } } }
false
false
null
null
diff --git a/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java b/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java index 35b552dbe..fd09ffefb 100644 --- a/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java +++ b/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java @@ -1,446 +1,446 @@ package org.archive.wayback.resourceindex.cdxserver; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.util.URIUtil; import org.archive.cdxserver.CDXQuery; import org.archive.cdxserver.CDXServer; import org.archive.cdxserver.auth.AuthToken; import org.archive.cdxserver.writer.HttpCDXWriter; import org.archive.format.cdx.CDXLine; import org.archive.format.cdx.StandardCDXLineFactory; import org.archive.url.UrlSurtRangeComputer.MatchType; import org.archive.util.binsearch.impl.HTTPSeekableLineReader; import org.archive.util.binsearch.impl.HTTPSeekableLineReader.BadHttpStatusException; import org.archive.util.binsearch.impl.HTTPSeekableLineReaderFactory; import org.archive.util.binsearch.impl.http.ApacheHttp31SLRFactory; import org.archive.wayback.ResourceIndex; import org.archive.wayback.core.CaptureSearchResult; import org.archive.wayback.core.CaptureSearchResults; import org.archive.wayback.core.SearchResults; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.exception.AccessControlException; import org.archive.wayback.exception.AdministrativeAccessControlException; import org.archive.wayback.exception.BadQueryException; import org.archive.wayback.exception.ResourceIndexNotAvailableException; import org.archive.wayback.exception.ResourceNotInArchiveException; import org.archive.wayback.exception.RobotAccessControlException; import org.archive.wayback.exception.WaybackException; import org.archive.wayback.memento.MementoConstants; import org.archive.wayback.memento.MementoHandler; import org.archive.wayback.memento.MementoUtils; import org.archive.wayback.resourceindex.filters.SelfRedirectFilter; import org.archive.wayback.util.webapp.AbstractRequestHandler; import org.archive.wayback.webapp.PerfStats; import org.json.JSONException; import org.json.JSONObject; import org.springframework.web.bind.ServletRequestBindingException; public class EmbeddedCDXServerIndex extends AbstractRequestHandler implements MementoHandler, ResourceIndex { private static final Logger LOGGER = Logger.getLogger( EmbeddedCDXServerIndex.class.getName()); protected CDXServer cdxServer; protected int timestampDedupLength = 0; protected int limit = 0; private SelfRedirectFilter selfRedirFilter; protected String remoteCdxPath; private HTTPSeekableLineReaderFactory remoteCdxHttp = new ApacheHttp31SLRFactory(); private StandardCDXLineFactory cdxLineFactory = new StandardCDXLineFactory("cdx11"); private String remoteAuthCookie; enum PerfStat { IndexLoad; } // public void init() // { // initAuthCookie(); // } // // protected String initAuthCookie() // { // if (cdxServer == null) { // return; // } // // AuthChecker check = cdxServer.getAuthChecker(); // if (!(check instanceof PrivTokenAuthChecker)) { // return; // } // // List<String> list = ((PrivTokenAuthChecker)check).getAllCdxFieldsAccessTokens(); // // if (list == null || list.isEmpty()) { // return; // } // // return CDXServer.CDX_AUTH_TOKEN + ": " + list.get(0); // } @Override public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { try { PerfStats.timeStart(PerfStat.IndexLoad); return doQuery(wbRequest); } finally { PerfStats.timeEnd(PerfStat.IndexLoad); } } public SearchResults doQuery(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { //AuthToken waybackAuthToken = new AuthToken(wbRequest.get(CDXServer.CDX_AUTH_TOKEN)); AuthToken waybackAuthToken = new AuthToken(); waybackAuthToken.setAllCdxFieldsAllow(); CDXToSearchResultWriter resultWriter = null; if (wbRequest.isReplayRequest() || wbRequest.isCaptureQueryRequest()) { resultWriter = this.getCaptureSearchWriter(wbRequest); } else if (wbRequest.isUrlQueryRequest()) { resultWriter = this.getUrlSearchWriter(wbRequest); } else { throw new BadQueryException("Unknown Query Type"); } try { if (remoteCdxPath != null) { this.remoteCdxServerQuery(resultWriter.getQuery(), waybackAuthToken, resultWriter); } else { cdxServer.getCdx(resultWriter.getQuery(), waybackAuthToken, resultWriter); } } catch (IOException e) { throw new ResourceIndexNotAvailableException(e.toString()); } catch (RuntimeException rte) { Throwable cause = rte.getCause(); if (cause instanceof AccessControlException) { throw (AccessControlException)cause; } if (cause instanceof IOException) { throw new ResourceIndexNotAvailableException(cause.toString()); } throw new ResourceIndexNotAvailableException(rte.getMessage()); } if (resultWriter.getErrorMsg() != null) { throw new BadQueryException(resultWriter.getErrorMsg()); } SearchResults searchResults = resultWriter.getSearchResults(); if (searchResults.getReturnedCount() == 0) { throw new ResourceNotInArchiveException(wbRequest.getRequestUrl() + " was not found"); } return searchResults; } protected CDXQuery createQuery(WaybackRequest wbRequest) { CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setLimit(limit); //query.setSort(CDXQuery.SortType.reverse); String statusFilter = "!statuscode:(500|502|504)"; if (wbRequest.isReplayRequest()) { if (wbRequest.isBestLatestReplayRequest()) { statusFilter = "statuscode:[23].."; } if (wbRequest.isTimestampSearchKey()) { query.setClosest(wbRequest.getReplayTimestamp()); } } else { if (timestampDedupLength > 0) { //query.setCollapse(new String[]{"timestamp:" + timestampDedupLength}); query.setCollapseTime(timestampDedupLength); } } query.setFilter(new String[]{statusFilter}); return query; } protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); - if (!query.getClosest().isEmpty()) { - sb.append("&closest="); - sb.append(query.getClosest()); - } +// if (!query.getClosest().isEmpty()) { +// sb.append("&closest="); +// sb.append(query.getClosest().substring(0, 4)); +// } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } } protected CDXToSearchResultWriter getCaptureSearchWriter(WaybackRequest wbRequest) { final CDXQuery query = createQuery(wbRequest); boolean resolveRevisits = wbRequest.isReplayRequest(); // For now, not using seek single capture to allow for run time checking of additional records boolean seekSingleCapture = resolveRevisits && wbRequest.isTimestampSearchKey(); //boolean seekSingleCapture = resolveRevisits && (wbRequest.isTimestampSearchKey() || (wbRequest.isBestLatestReplayRequest() && !wbRequest.hasMementoAcceptDatetime())); CDXToCaptureSearchResultsWriter captureWriter = new CDXToCaptureSearchResultsWriter(query, resolveRevisits, seekSingleCapture); captureWriter.setTargetTimestamp(wbRequest.getReplayTimestamp()); captureWriter.setSelfRedirFilter(selfRedirFilter); return captureWriter; } protected CDXToSearchResultWriter getUrlSearchWriter(WaybackRequest wbRequest) { final CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setCollapse(new String[]{CDXLine.urlkey}); query.setMatchType(MatchType.prefix); query.setShowGroupCount(true); query.setShowUniqCount(true); query.setLastSkipTimestamp(true); query.setFl("urlkey,original,timestamp,endtimestamp,groupcount,uniqcount"); return new CDXToUrlSearchResultWriter(query); } @Override public boolean renderMementoTimemap(WaybackRequest wbRequest, HttpServletRequest request, HttpServletResponse response) throws WaybackException, IOException { try { PerfStats.timeStart(PerfStat.IndexLoad); String format = wbRequest.getMementoTimemapFormat(); if ((format != null) && format.equals(MementoConstants.FORMAT_LINK)) { SearchResults cResults = wbRequest.getAccessPoint().queryIndex(wbRequest); MementoUtils.printTimemapResponse((CaptureSearchResults)cResults, wbRequest, response); return true; } CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setOutput(wbRequest.getMementoTimemapFormat()); String from = wbRequest.get(MementoConstants.PAGE_STARTS); if (from != null) { query.setFrom(from); } try { query.fill(request); } catch (ServletRequestBindingException e1) { //Ignore } cdxServer.getCdx(request, response, query); } finally { PerfStats.timeEnd(PerfStat.IndexLoad); } return true; } @Override public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException { CDXQuery query = new CDXQuery(httpRequest); cdxServer.getCdx(httpRequest, httpResponse, query); return true; } @Override public void shutdown() throws IOException { // TODO Auto-generated method stub } public CDXServer getCdxServer() { return cdxServer; } public void setCdxServer(CDXServer cdxServer) { this.cdxServer = cdxServer; } public int getTimestampDedupLength() { return timestampDedupLength; } public void setTimestampDedupLength(int timestampDedupLength) { this.timestampDedupLength = timestampDedupLength; } public SelfRedirectFilter getSelfRedirFilter() { return selfRedirFilter; } public void setSelfRedirFilter(SelfRedirectFilter selfRedirFilter) { this.selfRedirFilter = selfRedirFilter; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } @Override public void addTimegateHeaders( HttpServletResponse response, CaptureSearchResults results, WaybackRequest wbRequest, boolean includeOriginal) { MementoUtils.addTimegateHeaders(response, results, wbRequest, includeOriginal); // Add custom JSON header CaptureSearchResult result = results.getClosest(); JSONObject obj = new JSONObject(); JSONObject closestSnapshot = new JSONObject(); try { obj.put("wb_url", MementoUtils.getMementoPrefix(wbRequest.getAccessPoint()) + wbRequest.getAccessPoint().getUriConverter().makeReplayURI(result.getCaptureTimestamp(), wbRequest.getRequestUrl())); obj.put("timestamp", result.getCaptureTimestamp()); obj.put("status", result.getHttpCode()); closestSnapshot.put("closest", obj); } catch (JSONException je) { } String json = closestSnapshot.toString(); json = json.replace("\\/", "/"); response.setHeader("X-Link-JSON", json); } public String getRemoteCdxPath() { return remoteCdxPath; } public void setRemoteCdxPath(String remoteCdxPath) { this.remoteCdxPath = remoteCdxPath; } public String getRemoteAuthCookie() { return remoteAuthCookie; } public void setRemoteAuthCookie(String remoteAuthCookie) { this.remoteAuthCookie = remoteAuthCookie; } public HTTPSeekableLineReaderFactory getRemoteCdxHttp() { return remoteCdxHttp; } public void setRemoteCdxHttp(HTTPSeekableLineReaderFactory remoteCdxHttp) { this.remoteCdxHttp = remoteCdxHttp; } }
true
true
protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); if (!query.getClosest().isEmpty()) { sb.append("&closest="); sb.append(query.getClosest()); } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } }
protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); // if (!query.getClosest().isEmpty()) { // sb.append("&closest="); // sb.append(query.getClosest().substring(0, 4)); // } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } }
diff --git a/api/src/main/java/org/xnio/ByteString.java b/api/src/main/java/org/xnio/ByteString.java index 031d21d3..c9fad3ce 100644 --- a/api/src/main/java/org/xnio/ByteString.java +++ b/api/src/main/java/org/xnio/ByteString.java @@ -1,1303 +1,1303 @@ /* * JBoss, Home of Professional Open Source * * Copyright 2009 Red Hat, Inc. and/or its affiliates. * * 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.xnio; import java.io.IOException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.UnsupportedEncodingException; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.ByteBuffer; import static java.lang.Integer.signum; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.arraycopy; import static org.xnio._private.Messages.msg; /** * An immutable string of bytes. Since instances of this class are guaranteed to be immutable, they are * safe to use as {@link Option} values and in an {@link OptionMap}. Some operations can treat this byte string * as an ASCII- or ISO-8858-1-encoded character string. */ public final class ByteString implements Comparable<ByteString>, Serializable, CharSequence { private static final long serialVersionUID = -5998895518404718196L; private final byte[] bytes; private final int offs; private final int len; private transient int hashCode; private transient int hashCodeIgnoreCase; private ByteString(final byte[] bytes, final int offs, final int len) { this.bytes = bytes; this.offs = offs; this.len = len; if (offs < 0) { throw msg.parameterOutOfRange("offs"); } if (len < 0) { throw msg.parameterOutOfRange("len"); } if (offs + len > bytes.length) { throw msg.parameterOutOfRange("offs"); } } private static int calcHashCode(final byte[] bytes, final int offs, final int len) { int hc = 31; final int end = offs + len; for (int i = offs; i < end; i++) { hc = (hc << 5) - hc + (bytes[i] & 0xff); } return hc == 0 ? Integer.MAX_VALUE - 1 : hc; } private static int calcHashCodeIgnoreCase(final byte[] bytes, final int offs, final int len) { int hc = 31; final int end = offs + len; for (int i = offs; i < end; i++) { hc = (hc << 5) - hc + (upperCase(bytes[i]) & 0xff); } return hc == 0 ? Integer.MAX_VALUE - 1 : hc; } private ByteString(final byte[] bytes) { this(bytes, 0, bytes.length); } /** * Create a byte string of the given literal bytes. The given array is copied. * * @param bytes the bytes * @return the byte string */ public static ByteString of(byte... bytes) { return new ByteString(bytes.clone()); } /** * Create a byte string from the given array segment. * * @param b the byte array * @param offs the offset into the array * @param len the number of bytes to copy * @return the new byte string */ public static ByteString copyOf(byte[] b, int offs, int len) { return new ByteString(Arrays.copyOfRange(b, offs, offs + len)); } /** * Get a byte string from the bytes of a character string. * * @param str the character string * @param charset the character set to use * @return the byte string * @throws UnsupportedEncodingException if the encoding is not supported */ public static ByteString getBytes(String str, String charset) throws UnsupportedEncodingException { return new ByteString(str.getBytes(charset)); } /** * Get a byte string from the bytes of a character string. * * @param str the character string * @param charset the character set to use * @return the byte string */ public static ByteString getBytes(String str, Charset charset) { return new ByteString(str.getBytes(charset)); } /** * Get a byte string from all remaining bytes of a ByteBuffer. * * @param buffer the buffer * @return the byte string */ public static ByteString getBytes(ByteBuffer buffer) { return new ByteString(Buffers.take(buffer)); } /** * Get a byte string from a ByteBuffer. * * @param buffer the buffer * @param length the number of bytes to get * @return the byte string */ public static ByteString getBytes(ByteBuffer buffer, int length) { return new ByteString(Buffers.take(buffer, length)); } /** * Get a copy of the bytes of this ByteString. * * @return the copy */ public byte[] getBytes() { return Arrays.copyOfRange(bytes, offs, len); } /** * Copy the bytes of this ByteString into the destination array. If the array is too short to hold * the bytes, then only enough bytes to fill the array will be copied. * * @param dest the destination array * * @deprecated Replaced by {@link #copyTo(byte[])}. */ public void getBytes(byte[] dest) { copyTo(dest); } /** * Copy the bytes of this ByteString into the destination array. If the array is too short to hold * the bytes, then only enough bytes to fill the array will be copied. * * @param dest the destination array * @param offs the offset into the destination array * * @deprecated Replaced by {@link #copyTo(byte[],int)}. */ public void getBytes(byte[] dest, int offs) { copyTo(dest, offs); } /** * Copy the bytes of this ByteString into the destination array. If the array is too short to hold * the bytes, then only enough bytes to fill the array will be copied. * * @param dest the destination array * @param offs the offset into the destination array * @param len the maximum number of bytes to copy * * @deprecated Replaced by {@link #copyTo(byte[],int,int)}. */ public void getBytes(byte[] dest, int offs, int len) { copyTo(dest, offs, len); } /** * Copy {@code len} bytes from this string at offset {@code srcOffs} to the given array at the given offset. * * @param srcOffs the source offset * @param dst the destination * @param offs the destination offset * @param len the number of bytes to copy */ public void copyTo(int srcOffs, byte[] dst, int offs, int len) { arraycopy(bytes, srcOffs + this.offs, dst, offs, min(this.len, len)); } /** * Copy {@code len} bytes from this string to the given array at the given offset. * * @param dst the destination * @param offs the destination offset * @param len the number of bytes */ public void copyTo(byte[] dst, int offs, int len) { copyTo(0, dst, offs, len); } /** * Copy all the bytes from this string to the given array at the given offset. * * @param dst the destination * @param offs the destination offset */ public void copyTo(byte[] dst, int offs) { - copyTo(dst, offs, length()); + copyTo(dst, offs, dst.length - offs); } /** * Copy all the bytes from this string to the given array at the given offset. * * @param dst the destination */ public void copyTo(byte[] dst) { - copyTo(dst, offs, length()); + copyTo(dst, 0, dst.length); } /** * Append the bytes of this string into the given buffer. * * @param dest the target buffer */ public void appendTo(ByteBuffer dest) { dest.put(bytes, offs, len); } /** * Append as many bytes as possible to a byte buffer. * * @param offs the start offset * @param buffer the buffer to append to * @return the number of bytes appended */ public int tryAppendTo(final int offs, final ByteBuffer buffer) { final byte[] b = bytes; final int len = min(buffer.remaining(), b.length - offs); buffer.put(b, offs + this.offs, len); return len; } /** * Append to an output stream. * * @param output the stream to write to * @throws IOException if an error occurs */ public void writeTo(OutputStream output) throws IOException { // todo - determine if the output stream is trusted output.write(bytes, offs, len); } /** * Compare this string to another in a case-sensitive manner. * * @param other the other string * @return -1, 0, or 1 */ @Override public int compareTo(final ByteString other) { if (other == this) return 0; final int length = this.len; final int otherLength = other.len; final int len1 = min(length, otherLength); final byte[] bytes = this.bytes; final byte[] otherBytes = other.bytes; final int offs = this.offs; final int otherOffs = other.offs; int res; for (int i = 0; i < len1; i++) { res = signum(bytes[i + offs] - otherBytes[i + otherOffs]); if (res != 0) return res; } // shorter strings sort higher return signum(length - otherLength); } /** * Compare this string to another in a case-insensitive manner. * * @param other the other string * @return -1, 0, or 1 */ public int compareToIgnoreCase(final ByteString other) { if (other == this) return 0; if (other == this) return 0; final int length = this.len; final int otherLength = other.len; final int len1 = min(length, otherLength); final byte[] bytes = this.bytes; final byte[] otherBytes = other.bytes; final int offs = this.offs; final int otherOffs = other.offs; int res; for (int i = 0; i < len1; i++) { res = signum(upperCase(bytes[i + offs]) - upperCase(otherBytes[i + otherOffs])); if (res != 0) return res; } // shorter strings sort higher return signum(length - otherLength); } private static int upperCase(byte b) { return b >= 'a' && b <= 'z' ? b & 0xDF : b; } /** * Convert this byte string to a standard string. * * @param charset the character set to use * @return the standard string * @throws UnsupportedEncodingException if the charset is unknown */ public String toString(String charset) throws UnsupportedEncodingException { if ("ISO-8859-1".equalsIgnoreCase(charset) || "Latin-1".equalsIgnoreCase(charset) || "ISO-Latin-1".equals(charset)) return toString(); return new String(bytes, offs, len, charset); } /** * Get the number of bytes in this byte string. * * @return the number of bytes */ public int length() { return len; } /** * Decode this byte string as a Latin-1 string. * * @return the Latin-1-decoded version of this string */ @SuppressWarnings("deprecation") public String toString() { return new String(bytes, 0, offs, len); } /** * Get the byte at an index. * * @return the byte at an index */ public byte byteAt(int idx) { if (idx < 0 || idx > len) { throw new ArrayIndexOutOfBoundsException(); } return bytes[idx + offs]; } /** * Get the substring of this string starting at the given offset. * * @param offs the offset * @return the substring */ public ByteString substring(int offs) { return substring(offs, len - offs); } /** * Get the substring of this string starting at the given offset. * * @param offs the offset * @param len the substring length * @return the substring */ public ByteString substring(int offs, int len) { if (this.len - offs < len) { throw new IndexOutOfBoundsException(); } return new ByteString(bytes, this.offs + offs, len); } /** * Get the hash code for this ByteString. * * @return the hash code */ public int hashCode() { int hashCode = this.hashCode; if (hashCode == 0) { this.hashCode = hashCode = calcHashCode(bytes, offs, len); } return hashCode; } public int hashCodeIgnoreCase() { int hashCode = this.hashCodeIgnoreCase; if (hashCode == 0) { this.hashCodeIgnoreCase = hashCode = calcHashCodeIgnoreCase(bytes, offs, len); } return hashCode; } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); } private static boolean equals(byte[] a, int aoff, byte[] b, int boff, int len) { for (int i = 0; i < len; i ++) { if (a[i + aoff] != b[i + boff]) return false; } return true; } private static boolean equalsIgnoreCase(byte[] a, int aoff, byte[] b, int boff, int len) { for (int i = 0; i < len; i ++) { if (upperCase(a[i + aoff]) != upperCase(b[i + boff])) return false; } return true; } /** * Determine if this ByteString equals another ByteString. * * @param obj the other object * @return {@code true} if they are equal */ public boolean equals(final Object obj) { return (obj instanceof ByteString) && equals((ByteString) obj); } /** * Determine if this ByteString equals another ByteString. * * @param other the other object * @return {@code true} if they are equal */ public boolean equals(final ByteString other) { final int len = this.len; - return this == other || other != null && len == other.len && hashCode == other.hashCode && equals(bytes, offs, other.bytes, other.offs, len); + return this == other || other != null && len == other.len && equals(bytes, offs, other.bytes, other.offs, len); } /** * Determine if this ByteString equals another ByteString, ignoring case (ASCII). * * @param other the other object * @return {@code true} if they are equal */ public boolean equalsIgnoreCase(final ByteString other) { final int len = this.len; - return this == other || other != null && len == other.len && hashCode == other.hashCode && equalsIgnoreCase(bytes, offs, other.bytes, other.offs, len); + return this == other || other != null && len == other.len && equalsIgnoreCase(bytes, offs, other.bytes, other.offs, len); } /** * Get the unsigned {@code int} value of this string. If the value is greater than would fit in 32 bits, only * the low 32 bits are returned. Parsing stops on the first non-digit character. * * @param start the index to start at (must be less than or equal to length) * @return the value */ public int toInt(final int start) { final int len = this.len; if (start >= len) { return 0; } final byte[] bytes = this.bytes; int v = 0; byte b; for (int i = start + offs; i < len; i ++) { b = bytes[i]; if (b < '0' || b > '9') { return v; } v = (v << 3) + (v << 1) + (b - '0'); } return v; } /** * Get the unsigned {@code int} value of this string. If the value is greater than would fit in 32 bits, only * the low 32 bits are returned. Parsing stops on the first non-digit character. * * @return the value */ public int toInt() { return toInt(0); } /** * Get the unsigned {@code long} value of this string. If the value is greater than would fit in 64 bits, only * the low 64 bits are returned. Parsing stops on the first non-digit character. * * @param start the index to start at (must be less than or equal to length) * @return the value */ public long toLong(final int start) { final int len = this.len; if (start >= len) { return 0; } final byte[] bytes = this.bytes; long v = 0; byte b; for (int i = start; i < len; i ++) { b = bytes[i]; if (b < '0' || b > '9') { return v; } v = (v << 3) + (v << 1) + (b - '0'); } return v; } /** * Get the unsigned {@code long} value of this string. If the value is greater than would fit in 64 bits, only * the low 64 bits are returned. Parsing stops on the first non-digit character. * * @return the value */ public long toLong() { return toLong(0); } private static int decimalCount(int val) { assert val >= 0; // afaik no faster way exists to do this if (val < 10) return 1; if (val < 100) return 2; if (val < 1000) return 3; if (val < 10000) return 4; if (val < 100000) return 5; if (val < 1000000) return 6; if (val < 10000000) return 7; if (val < 100000000) return 8; if (val < 1000000000) return 9; return 10; } private static int decimalCount(long val) { assert val >= 0; // afaik no faster way exists to do this if (val < 10L) return 1; if (val < 100L) return 2; if (val < 1000L) return 3; if (val < 10000L) return 4; if (val < 100000L) return 5; if (val < 1000000L) return 6; if (val < 10000000L) return 7; if (val < 100000000L) return 8; if (val < 1000000000L) return 9; if (val < 10000000000L) return 10; if (val < 100000000000L) return 11; if (val < 1000000000000L) return 12; if (val < 10000000000000L) return 13; if (val < 100000000000000L) return 14; if (val < 1000000000000000L) return 15; if (val < 10000000000000000L) return 16; if (val < 100000000000000000L) return 17; if (val < 1000000000000000000L) return 18; return 19; } private static final ByteString ZERO = new ByteString(new byte[] { '0' }); /** * Get a string version of the given value. * * @param val the value * @return the string */ public static ByteString fromLong(long val) { if (val == 0) return ZERO; // afaik no faster way exists to do this int i = decimalCount(abs(val)); final byte[] b; if (val < 0) { b = new byte[++i]; b[0] = '-'; } else { b = new byte[i]; } long quo; // modulus int mod; do { quo = val / 10; mod = (int) (val - ((quo << 3) + (quo << 1))); b[--i] = (byte) (mod + '0'); val = quo; } while (i > 0); return new ByteString(b); } /** * Get a string version of the given value. * * @param val the value * @return the string */ public static ByteString fromInt(int val) { if (val == 0) return ZERO; // afaik no faster way exists to do this int i = decimalCount(abs(val)); final byte[] b; if (val < 0) { b = new byte[++i]; b[0] = '-'; } else { b = new byte[i]; } int quo; // modulus int mod; do { quo = val / 10; mod = val - ((quo << 3) + (quo << 1)); b[--i] = (byte) (mod + '0'); val = quo; } while (i > 0); return new ByteString(b); } /** * Determine whether this {@code ByteString} is equal (case-sensitively) to the given {@code String}. * * @param str the string to check * @return {@code true} if the given string is equal (case-sensitively) to this instance, {@code false} otherwise */ public boolean equalToString(String str) { if (str == null) return false; final byte[] bytes = this.bytes; final int length = bytes.length; if (str.length() != length) { return false; } char ch; final int end = offs + len; for (int i = offs; i < end; i++) { ch = str.charAt(i); if (ch > 0xff || bytes[i] != (byte) str.charAt(i)) { return false; } } return true; } /** * Determine whether this {@code ByteString} is equal (case-insensitively) to the given {@code String}. * * @param str the string to check * @return {@code true} if the given string is equal (case-insensitively) to this instance, {@code false} otherwise */ public boolean equalToStringIgnoreCase(String str) { if (str == null) return false; final byte[] bytes = this.bytes; final int length = bytes.length; if (str.length() != length) { return false; } char ch; final int end = offs + len; for (int i = offs; i < end; i++) { ch = str.charAt(i); if (ch > 0xff || upperCase(bytes[i]) != upperCase((byte) ch)) { return false; } } return true; } /** * Get the index of the given character in this string. * * @param c the character * @return the index, or -1 if it was not found */ public int indexOf(final char c) { return indexOf(c, 0); } /** * Get the index of the given character in this string. * * @param c the character * @return the index, or -1 if it was not found */ public int indexOf(final char c, int start) { if (c > 255) { return -1; } final int len = this.len; if (start > len) { return -1; } start = max(0, start) + offs; final byte[] bytes = this.bytes; final byte bc = (byte) c; final int end = start + len; for (int i = start; i < end; i++) { if (bytes[i] == bc) { return i; } } return -1; } /** * Get the last index of the given character in this string. * * @param c the character * @return the index, or -1 if it was not found */ public int lastIndexOf(final char c) { return lastIndexOf(c, length() - 1); } /** * Get the last index of the given character in this string. * * @param c the character * @return the index, or -1 if it was not found */ public int lastIndexOf(final char c, int start) { if (c > 255) { return -1; } final byte[] bytes = this.bytes; final int offs = this.offs; start = min(start, len - 1) + offs; final byte bc = (byte) c; for (int i = start; i >= offs; --i) { if (bytes[i] == bc) { return i; } } return -1; } // Linear array searches private static int arrayIndexOf(byte[] a, int aOffs, byte[] b, int bOffs, int bLen) { final int aLen = a.length - aOffs; if (bLen > aLen || aLen < 0) { return -1; } aOffs = max(0, aOffs); if (bLen == 0) { return aOffs; } final byte startByte = b[bOffs]; final int limit = aLen - bLen; OUTER: for (int i = aOffs; i < limit; i ++) { if (a[i] == startByte) { for (int j = 1; j < bLen; j ++) { if (a[i + j] != b[j + bOffs]) { continue OUTER; } } return i; } } return -1; } private static int arrayIndexOf(byte[] a, int aOffs, String string) { final int aLen = a.length - aOffs; final int bLen = string.length(); if (bLen > aLen || aLen < 0) { return -1; } aOffs = max(0, aOffs); if (bLen == 0) { return aOffs; } final char startChar = string.charAt(0); if (startChar > 0xff) { return -1; } char ch; final int limit = aLen - bLen; OUTER: for (int i = aOffs; i < limit; i ++) { if (a[i] == startChar) { for (int j = 1; j < bLen; j ++) { ch = string.charAt(j); if (ch > 0xff) { return -1; } if (a[i + j] != ch) { continue OUTER; } } return i; } } return -1; } private static int arrayIndexOfIgnoreCase(byte[] a, int aOffs, byte[] b, int bOffs, int bLen) { final int aLen = a.length - aOffs; if (bLen > aLen || aLen < 0) { return -1; } aOffs = max(0, aOffs); if (bLen == 0) { return aOffs; } final int startChar = upperCase(b[bOffs]); final int limit = aLen - bLen; OUTER: for (int i = aOffs; i < limit; i ++) { if (upperCase(a[i]) == startChar) { for (int j = 1; j < bLen; j ++) { if (upperCase(a[i + j]) != upperCase(b[j + bOffs])) { continue OUTER; } } return i; } } return -1; } private static int arrayIndexOfIgnoreCase(byte[] a, int aOffs, String string) { final int aLen = a.length - aOffs; final int bLen = string.length(); if (bLen > aLen || aLen < 0) { return -1; } aOffs = max(0, aOffs); if (bLen == 0) { return aOffs; } final char startChar = string.charAt(0); if (startChar > 0xff) { return -1; } final int startCP = upperCase((byte) startChar); final int limit = aLen - bLen; char ch; OUTER: for (int i = aOffs; i < limit; i ++) { if (upperCase(a[i]) == startCP) { for (int j = 1; j < bLen; j ++) { ch = string.charAt(j); if (ch > 0xff) { return -1; } // technically speaking, 'ı' (0x131) maps to I and 'ſ' (0x17F) maps to S, but this is unlikely to come up in ISO-8859-1 if (upperCase(a[i + j]) != upperCase((byte) ch)) { continue OUTER; } } return i; } } return -1; } private static int arrayLastIndexOf(byte[] a, int aOffs, byte[] b, final int bOffs, final int bLen) { final int aLen = a.length - aOffs; if (bLen > aLen || aLen < 0 || aOffs < 0) { return -1; } // move to the last possible position it could be aOffs = min(aLen - bLen, aOffs); if (bLen == 0) { return aOffs; } final byte startByte = b[0]; OUTER: for (int i = aOffs - 1; i >= 0; i --) { if (a[i] == startByte) { for (int j = 1; j < bLen; j++) { if (a[i + j] != b[bOffs + j]) { continue OUTER; } return i; } } } return -1; } private static int arrayLastIndexOf(byte[] a, int aOffs, String string) { final int aLen = a.length - aOffs; final int bLen = string.length(); if (bLen > aLen || aLen < 0 || aOffs < 0) { return -1; } // move to the last possible position it could be aOffs = min(aLen - bLen, aOffs); if (bLen == 0) { return aOffs; } final char startChar = string.charAt(0); if (startChar > 0xff) { return -1; } final byte startByte = (byte) startChar; char ch; OUTER: for (int i = aOffs - 1; i >= 0; i --) { if (a[i] == startByte) { for (int j = 1; j < bLen; j++) { ch = string.charAt(j); if (ch > 0xff) { return -1; } if (a[i + j] != (byte) ch) { continue OUTER; } return i; } } } return -1; } private static int arrayLastIndexOfIgnoreCase(byte[] a, int aOffs, byte[] b, final int bOffs, final int bLen) { final int aLen = a.length - aOffs; if (bLen > aLen || aLen < 0 || aOffs < 0) { return -1; } // move to the last possible position it could be aOffs = min(aLen - bLen, aOffs); if (bLen == 0) { return aOffs; } final int startCP = upperCase(b[bOffs]); OUTER: for (int i = aOffs - 1; i >= 0; i --) { if (upperCase(a[i]) == startCP) { for (int j = 1; j < bLen; j++) { if (upperCase(a[i + j]) != upperCase(b[j + bOffs])) { continue OUTER; } return i; } } } return -1; } private static int arrayLastIndexOfIgnoreCase(byte[] a, int aOffs, String string) { final int aLen = a.length - aOffs; final int bLen = string.length(); if (bLen > aLen || aLen < 0 || aOffs < 0) { return -1; } // move to the last possible position it could be aOffs = min(aLen - bLen, aOffs); if (bLen == 0) { return aOffs; } final char startChar = string.charAt(0); if (startChar > 0xff) { return -1; } final int startCP = upperCase((byte) startChar); char ch; OUTER: for (int i = aOffs - 1; i >= 0; i --) { if (upperCase(a[i]) == startCP) { for (int j = 1; j < bLen; j++) { ch = string.charAt(j); if (ch > 0xff) { return -1; } // technically speaking, 'ı' (0x131) maps to I and 'ſ' (0x17F) maps to S, but this is unlikely to come up in ISO-8859-1 if (upperCase(a[i + j]) != upperCase((byte) ch)) { continue OUTER; } return i; } } } return -1; } /** * Determine whether this string contains another string (case-sensitive). * * @param other the string to test * @return {@code true} if this string contains {@code other}, {@code false} otherwise */ public boolean contains(final ByteString other) { if (other == this) return true; if (other == null) return false; final byte[] otherBytes = other.bytes; return arrayIndexOf(bytes, offs, otherBytes, other.offs, other.len) != -1; } /** * Determine whether this string contains another string (case-sensitive). * * @param other the string to test * @return {@code true} if this string contains {@code other}, {@code false} otherwise */ public boolean contains(final String other) { return other != null && toString().contains(other); } /** * Determine whether this string contains another string (case-insensitive). * * @param other the string to test * @return {@code true} if this string contains {@code other}, {@code false} otherwise */ public boolean containsIgnoreCase(final ByteString other) { return other == this || other != null && arrayIndexOfIgnoreCase(bytes, offs, other.bytes, other.offs, other.len) != -1; } /** * Determine whether this string contains another string (case-sensitive). * * @param other the string to test * @return {@code true} if this string contains {@code other}, {@code false} otherwise */ public boolean containsIgnoreCase(final String other) { return arrayIndexOfIgnoreCase(bytes, offs, other) != -1; } public int indexOf(final ByteString other) { return arrayIndexOf(bytes, offs, other.bytes, other.offs, other.len); } public int indexOf(final ByteString other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayIndexOf(bytes, offs + start, other.bytes, other.offs, other.len); } public int indexOf(final String other) { return arrayIndexOf(bytes, offs, other); } public int indexOf(final String other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayIndexOf(bytes, offs + start, other); } public int indexOfIgnoreCase(final ByteString other) { return arrayIndexOfIgnoreCase(bytes, offs, other.bytes, other.offs, other.len); } public int indexOfIgnoreCase(final ByteString other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayIndexOfIgnoreCase(bytes, offs + start, other.bytes, other.offs, other.len); } public int indexOfIgnoreCase(final String other) { return arrayIndexOfIgnoreCase(bytes, offs, other); } public int indexOfIgnoreCase(final String other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayIndexOfIgnoreCase(bytes, offs + start, other); } public int lastIndexOf(final ByteString other) { return arrayLastIndexOf(bytes, offs, other.bytes, other.offs, other.len); } public int lastIndexOf(final ByteString other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayLastIndexOf(bytes, offs + start, other.bytes, other.offs, other.len); } public int lastIndexOf(final String other) { return arrayLastIndexOf(bytes, offs, other); } public int lastIndexOf(final String other, int start) { return arrayLastIndexOf(bytes, offs + start, other); } public int lastIndexOfIgnoreCase(final ByteString other) { return arrayLastIndexOfIgnoreCase(bytes, offs, other.bytes, other.offs, other.len); } public int lastIndexOfIgnoreCase(final ByteString other, int start) { if (start > len) return -1; if (start < 0) start = 0; return arrayLastIndexOfIgnoreCase(bytes, offs + start, other.bytes, other.offs, other.len); } public int lastIndexOfIgnoreCase(final String other) { return arrayLastIndexOfIgnoreCase(bytes, offs, other); } public int lastIndexOfIgnoreCase(final String other, int start) { return arrayLastIndexOfIgnoreCase(bytes, offs + start, other); } public boolean regionMatches(boolean ignoreCase, int offset, byte[] other, int otherOffset, int len) { if (offset < 0 || otherOffset < 0 || offset + len > this.len || otherOffset + len > other.length) { return false; } if (ignoreCase) { return equalsIgnoreCase(bytes, offset + offs, other, otherOffset, len); } else { return equals(bytes, offset + offs, other, otherOffset, len); } } public boolean regionMatches(boolean ignoreCase, int offset, ByteString other, int otherOffset, int len) { if (offset < 0 || otherOffset < 0 || offset + len > this.len || otherOffset + len > other.len) { return false; } if (ignoreCase) { return equalsIgnoreCase(bytes, offset + offs, other.bytes, otherOffset, len); } else { return equals(bytes, offset + offs, other.bytes, otherOffset, len); } } public boolean regionMatches(boolean ignoreCase, int offset, String other, int otherOffset, int len) { if (offset < 0 || otherOffset < 0 || offset + len > this.len || otherOffset + len > other.length()) { return false; } if (ignoreCase) { return equalsIgnoreCase(bytes, offset + offs, other, otherOffset, len); } else { return equals(bytes, offset + offs, other, otherOffset, len); } } private static boolean equalsIgnoreCase(final byte[] a, int aOffs, String string, int stringOffset, int length) { char ch; for (int i = 0; i < length; i ++) { ch = string.charAt(i + stringOffset); if (ch > 0xff) { return false; } if (a[i + aOffs] != (byte) ch) { return false; } } return true; } private static boolean equals(final byte[] a, int aOffs, String string, int stringOffset, int length) { char ch; for (int i = 0; i < length; i ++) { ch = string.charAt(i + stringOffset); if (ch > 0xff) { return false; } if (upperCase(a[i + aOffs]) != upperCase((byte) ch)) { return false; } } return true; } public boolean startsWith(ByteString prefix) { return regionMatches(false, 0, prefix, 0, prefix.length()); } public boolean startsWith(String prefix) { return regionMatches(false, 0, prefix, 0, prefix.length()); } public boolean startsWith(char prefix) { return prefix <= 0xff && len > 0 && bytes[offs] == (byte) prefix; } public boolean startsWithIgnoreCase(ByteString prefix) { return regionMatches(true, 0, prefix, 0, prefix.length()); } public boolean startsWithIgnoreCase(String prefix) { return regionMatches(true, 0, prefix, 0, prefix.length()); } public boolean startsWithIgnoreCase(char prefix) { return prefix <= 0xff && len > 0 && upperCase(bytes[offs]) == upperCase((byte) prefix); } public boolean endsWith(ByteString suffix) { final int suffixLength = suffix.len; return regionMatches(false, len - suffixLength, suffix, 0, suffixLength); } public boolean endsWith(String suffix) { final int suffixLength = suffix.length(); return regionMatches(false, len - suffixLength, suffix, 0, suffixLength); } public boolean endsWith(char suffix) { final int len = this.len; return suffix <= 0xff && len > 0 && bytes[offs + len - 1] == (byte) suffix; } public boolean endsWithIgnoreCase(ByteString suffix) { final int suffixLength = suffix.length(); return regionMatches(true, len - suffixLength, suffix, 0, suffixLength); } public boolean endsWithIgnoreCase(String suffix) { final int suffixLength = suffix.length(); return regionMatches(true, len - suffixLength, suffix, 0, suffixLength); } public boolean endsWithIgnoreCase(char suffix) { final int len = this.len; return suffix <= 0xff && len > 0 && upperCase(bytes[offs + len - 1]) == upperCase((byte) suffix); } public ByteString concat(byte[] suffixBytes) { return concat(suffixBytes, 0, suffixBytes.length); } public ByteString concat(byte[] suffixBytes, int offs, int len) { if (len <= 0) { return this; } final int length = this.len; byte[] newBytes = Arrays.copyOfRange(bytes, this.offs, length + len); System.arraycopy(suffixBytes, offs, newBytes, length, len); return new ByteString(newBytes); } public ByteString concat(ByteString suffix) { return concat(suffix.bytes, suffix.offs, suffix.len); } public ByteString concat(ByteString suffix, int offs, int len) { return concat(suffix.bytes, offs + suffix.offs, min(len, suffix.len)); } public ByteString concat(String suffix) { return concat(suffix, 0, suffix.length()); } @SuppressWarnings("deprecation") private static void getStringBytes(final boolean trust, final byte[] dst, final int dstOffs, final String src, final int srcOffs, final int len) { if (trust) { src.getBytes(srcOffs, srcOffs + len, dst, dstOffs); } else { for (int i = srcOffs; i < len; i++) { char c = src.charAt(i); if (c > 0xff) { throw new IllegalArgumentException("Invalid string contents"); } dst[i + dstOffs] = (byte) c; } } } public ByteString concat(String suffix, int offs, int len) { if (len <= 0) { return this; } final byte[] bytes = this.bytes; final int length = this.len; byte[] newBytes = Arrays.copyOfRange(bytes, offs, offs + length + len); getStringBytes(false, newBytes, length, suffix, offs, len); return new ByteString(newBytes); } public static ByteString concat(String prefix, ByteString suffix) { final int prefixLength = prefix.length(); final byte[] suffixBytes = suffix.bytes; final int suffixLength = suffixBytes.length; final byte[] newBytes = new byte[prefixLength + suffixLength]; getStringBytes(false, newBytes, 0, prefix, 0, prefixLength); System.arraycopy(suffixBytes, suffix.offs, newBytes, prefixLength, suffixLength); return new ByteString(newBytes); } public static ByteString concat(String prefix, String suffix) { final int prefixLength = prefix.length(); final int suffixLength = suffix.length(); final byte[] newBytes = new byte[prefixLength + suffixLength]; getStringBytes(false, newBytes, 0, prefix, 0, prefixLength); getStringBytes(false, newBytes, prefixLength, suffix, 0, suffixLength); return new ByteString(newBytes); } public char charAt(final int index) { if (index < 0 || index > len) { throw new ArrayIndexOutOfBoundsException(); } return (char) (bytes[index + offs] & 0xff); } public ByteString subSequence(final int start, final int end) { return substring(start, end); } }
false
false
null
null
diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java index 55c4a138c3..01024f0b38 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/StringCompositeKey.java @@ -1,51 +1,60 @@ package org.hibernate.test.querycache; import java.io.Serializable; +import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class StringCompositeKey implements Serializable { private static final long serialVersionUID = 1L; - private String substation; + private String substation; private String deviceType; private String device; + + private String analog; + + // For some dialects, the sum of a primary key column lengths cannot + // be larger than 255 (DB2). Restrict them to a sufficiently + // small size. See HHH-8085. - public String getSubstation() { + @Column( length = 50 ) + public String getSubstation() { return substation; } public void setSubstation(String substation) { this.substation = substation; } + @Column( length = 50 ) public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } + @Column( length = 50 ) public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } + @Column( length = 50 ) public String getAnalog() { return analog; } public void setAnalog(String analog) { this.analog = analog; } - - private String analog; } \ No newline at end of file
false
false
null
null
diff --git a/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/TestAtlasDataDAO.java b/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/TestAtlasDataDAO.java index 2d56fdd55..e96159f83 100644 --- a/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/TestAtlasDataDAO.java +++ b/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/TestAtlasDataDAO.java @@ -1,94 +1,97 @@ package uk.ac.ebi.gxa.data; import com.google.common.base.Predicates; import junit.framework.TestCase; import uk.ac.ebi.microarray.atlas.model.Experiment; +import uk.ac.ebi.microarray.atlas.model.Assay; import uk.ac.ebi.microarray.atlas.model.ArrayDesign; import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.*; /** * This class tests functionality of AtlasDataDAO * * @author Robert Petryszak */ public class TestAtlasDataDAO extends TestCase { private AtlasDataDAO atlasDataDAO; private Long geneId; private Experiment experiment; private String ef; private String efv; private float minPValue; private String designElementAccessionForMinPValue; private Set<Long> geneIds; private ArrayDesign arrayDesign; private final static DecimalFormat pValFormat = new DecimalFormat("0.#######"); @Override protected void setUp() throws Exception { super.setUp(); geneId = 153070209l; // human brca1 arrayDesign = new ArrayDesign("A-AFFY-33"); ef = "cell_type"; efv = "germ cell"; minPValue = 0.9999986f; designElementAccessionForMinPValue = "204531_s_at"; experiment = new Experiment(411512559L, "E-MTAB-25"); - + final Assay assay = new Assay("AssayAccession"); + assay.setArrayDesign(arrayDesign); + experiment.setAssays(Collections.singletonList(assay)); atlasDataDAO = new AtlasDataDAO(); atlasDataDAO.setAtlasDataRepo(new File(getClass().getClassLoader().getResource("").getPath())); geneIds = new HashSet<Long>(); geneIds.add(geneId); } public void testGetFactorValues() throws IOException, AtlasDataException { final ExperimentWithData ewd = atlasDataDAO.createExperimentWithData(experiment); try { final String[] fvs = ewd.getFactorValues(arrayDesign, ef); assertNotNull(fvs); assertNotSame(fvs.length, 0); assertTrue(Arrays.asList(fvs).contains(efv)); } finally { ewd.closeAllDataSources(); } } - public void testGetExpressionAnalyticsByGeneID() throws IOException, AtlasDataException { + public void testGetExpressionAnalyticsByGeneID() throws AtlasDataException { final ExperimentWithData ewd = atlasDataDAO.createExperimentWithData(experiment); try { Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA = ewd.getExpressionAnalysesForGeneIds(geneIds, Predicates.<DataPredicates.Pair>alwaysTrue()); // check the returned data assertNotNull(geneIdsToEfToEfvToEA.get(geneId)); assertNotNull(geneIdsToEfToEfvToEA.get(geneId).get(ef)); ExpressionAnalysis ea = geneIdsToEfToEfvToEA.get(geneId).get(ef).get(efv); assertNotNull(ea); assertNotNull("Got null for design element ID", ea.getDesignElementAccession()); //assertNotNull("Got null for experiment ID", ea.getExperimentID()); assertNotNull("Got null for ef name", ea.getEfName()); assertNotNull("Got null for efv name", ea.getEfvName()); assertNotNull("Got null for ef id", ea.getEfId()); assertNotNull("Got null for efv id", ea.getEfvId()); assertNotNull("Got null for pvalue", ea.getPValAdjusted()); assertNotNull("Got null for tstat", ea.getTStatistic()); assertNotNull("Got null for arrayDesign accession", ea.getArrayDesignAccession()); assertNotNull("Got null for design element index", ea.getDesignElementIndex()); System.out.println("Got expression analysis for gene id: " + geneId + " \n" + ea.toString()); assertEquals(designElementAccessionForMinPValue, ea.getDesignElementAccession()); assertEquals(pValFormat.format(minPValue), pValFormat.format(ea.getPValAdjusted())); } finally { ewd.closeAllDataSources(); } } }
false
false
null
null
diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCalendar/TestRichCalendarAttributes.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCalendar/TestRichCalendarAttributes.java index b0a8ef06..1047ae83 100644 --- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCalendar/TestRichCalendarAttributes.java +++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCalendar/TestRichCalendarAttributes.java @@ -1,712 +1,712 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *******************************************************************************/ package org.richfaces.tests.metamer.ftest.richCalendar; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardNoRequest; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardXhr; import static org.jboss.test.selenium.locator.LocatorFactory.jq; import static org.jboss.test.selenium.utils.URLUtils.buildUrl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.jboss.test.selenium.dom.Event; import org.jboss.test.selenium.locator.Attribute; import org.jboss.test.selenium.locator.AttributeLocator; import org.jboss.test.selenium.waiting.EventFiredCondition; import org.richfaces.tests.metamer.ftest.annotations.IssueTracking; import org.testng.annotations.Test; /** * Test case for attributes of a calendar on page faces/components/richCalendar/simple.xhtml. * * @author <a href="mailto:[email protected]">Pavol Pitonak</a> * @version $Revision$ */ public class TestRichCalendarAttributes extends AbstractCalendarTest { @Override public URL getTestUrl() { return buildUrl(contextPath, "faces/components/richCalendar/simple.xhtml"); } @Test public void testBoundaryDatesModeNull() { selenium.click(input); String month = selenium.getText(monthLabel); guardNoRequest(selenium).click(cellWeekDay.format(6, 6)); String newMonth = selenium.getText(monthLabel); assertEquals(newMonth, month, "Month should not change."); // the most top-left column might be 1st day of month while (selenium.getText(cellWeekDay.format(1, 1)).equals("1")) { selenium.click(prevMonthButton); } month = selenium.getText(monthLabel); guardNoRequest(selenium).click(cellWeekDay.format(1, 1)); newMonth = selenium.getText(monthLabel); assertEquals(newMonth, month, "Month should not change."); } @Test public void testBoundaryDatesModeInactive() { selenium.click(pjq("input[name$=boundaryDatesModeInput][value=inactive]")); selenium.waitForPageToLoad(); testBoundaryDatesModeNull(); } @Test public void testBoundaryDatesModeScroll() { selenium.click(pjq("input[name$=boundaryDatesModeInput][value=scroll]")); selenium.waitForPageToLoad(); selenium.click(input); String thisMonth = selenium.getText(monthLabel); // November, 2010 -> November thisMonth = thisMonth.substring(0, thisMonth.indexOf(",")); guardNoRequest(selenium).click(cellWeekDay.format(6, 6)); String newMonth = selenium.getText(monthLabel); newMonth = newMonth.substring(0, newMonth.indexOf(",")); assertEquals(Month.valueOf(newMonth), Month.valueOf(thisMonth).next(), "Month did not change correctly."); assertNoDateSelected(); // the most top-left column might be 1st day of month while (selenium.getText(cellWeekDay.format(1, 0)).equals("1")) { selenium.click(prevMonthButton); } thisMonth = selenium.getText(monthLabel); // November, 2010 -> November thisMonth = thisMonth.substring(0, thisMonth.indexOf(",")); guardNoRequest(selenium).click(cellWeekDay.format(1, 1)); newMonth = selenium.getText(monthLabel); newMonth = newMonth.substring(0, newMonth.indexOf(",")); assertEquals(Month.valueOf(newMonth), Month.valueOf(thisMonth).previous(), "Month did not change correctly."); assertNoDateSelected(); } @Test public void testBoundaryDatesModeSelect() { selenium.click(pjq("input[name$=boundaryDatesModeInput][value=select]")); selenium.waitForPageToLoad(); selenium.click(input); String thisMonth = selenium.getText(monthLabel); String selectedDate = selenium.getText(cellWeekDay.format(6, 6)); // November, 2010 -> November thisMonth = thisMonth.substring(0, thisMonth.indexOf(",")); guardNoRequest(selenium).click(cellWeekDay.format(6, 6)); String newMonth = selenium.getText(monthLabel); newMonth = newMonth.substring(0, newMonth.indexOf(",")); assertEquals(Month.valueOf(newMonth), Month.valueOf(thisMonth).next(), "Month did not change correctly."); assertSelected(selectedDate); // the most top-left column might be 1st day of month while (selenium.getText(cellWeekDay.format(1, 0)).equals("1")) { selenium.click(prevMonthButton); } thisMonth = selenium.getText(monthLabel); selectedDate = selenium.getText(cellWeekDay.format(1, 1)); // November, 2010 -> November thisMonth = thisMonth.substring(0, thisMonth.indexOf(",")); guardNoRequest(selenium).click(cellWeekDay.format(1, 1)); newMonth = selenium.getText(monthLabel); newMonth = newMonth.substring(0, newMonth.indexOf(",")); assertEquals(Month.valueOf(newMonth), Month.valueOf(thisMonth).previous(), "Month did not change correctly."); assertSelected(selectedDate); } @Test public void testButtonClass() { testStyleClass(image, "buttonClass"); } @Test public void testButtonClassLabel() { selenium.type(pjq("input[type=text][id$=buttonLabelInput]"), "label"); selenium.waitForPageToLoad(); testStyleClass(button, "buttonClass"); } @Test public void testButtonClassIcon() { selenium.click(pjq("td:has(label:contains(heart)) > input[name$=buttonIconInput]")); selenium.waitForPageToLoad(); testStyleClass(image, "buttonClass"); } @Test public void testButtonIcon() { selenium.click(pjq("td:has(label:contains(star)) > input[name$=buttonIconInput]")); selenium.waitForPageToLoad(); AttributeLocator attr = image.getAttribute(Attribute.SRC); String src = selenium.getAttribute(attr); assertTrue(src.contains("star.png"), "Calendar's icon was not updated."); selenium.click(pjq("td:has(label:contains(null)) > input[name$=buttonIconInput]")); selenium.waitForPageToLoad(); src = selenium.getAttribute(attr); assertTrue(src.contains("calendarIcon.png"), "Calendar's icon was not updated."); } @Test public void testButtonIconDisabled() { selenium.click(pjq("input[name$=disabledInput][value=true]")); selenium.waitForPageToLoad(); selenium.click(pjq("td:has(label:contains(heart)) > input[name$=buttonIconDisabledInput]")); selenium.waitForPageToLoad(); AttributeLocator attr = image.getAttribute(Attribute.SRC); String src = selenium.getAttribute(attr); assertTrue(src.contains("heart.png"), "Calendar's icon was not updated."); selenium.click(pjq("td:has(label:contains(null)) > input[name$=buttonIconDisabledInput]")); selenium.waitForPageToLoad(); src = selenium.getAttribute(attr); assertTrue(src.contains("disabledCalendarIcon.png"), "Calendar's icon was not updated."); } @Test public void testButtonLabel() { selenium.type(pjq("input[type=text][id$=buttonLabelInput]"), "label"); selenium.waitForPageToLoad(); assertTrue(selenium.isDisplayed(button), "Button should be displayed."); assertEquals(selenium.getText(button), "label", "Label of the button."); if (selenium.isElementPresent(image)) { assertFalse(selenium.isDisplayed(image), "Image should not be displayed."); } selenium.click(pjq("td:has(label:contains(star)) > input[name$=buttonIconInput]")); selenium.waitForPageToLoad(); if (selenium.isElementPresent(image)) { assertFalse(selenium.isDisplayed(image), "Image should not be displayed."); } } @Test public void testDatePattern() { selenium.type(pjq("input[type=text][id$=datePatternInput]"), "hh:mm:ss a MMMM d, yyyy"); selenium.waitForPageToLoad(); selenium.click(input); selenium.click(cellDay.format(6)); String day = selenium.getText(cellDay.format(6)); String month = selenium.getText(monthLabel); String selectedDate = null; try { Date date = new SimpleDateFormat("d MMMM, yyyy hh:mm a").parse(day + " " + month + " 12:00 PM"); selectedDate = new SimpleDateFormat("hh:mm:ss a MMMM d, yyyy").format(date); } catch (ParseException ex) { fail(ex.getMessage()); } selenium.click(applyButton); assertFalse(selenium.isDisplayed(popup), "Popup should not be displayed."); String inputDate = selenium.getValue(input); assertEquals(inputDate, selectedDate, "Input doesn't contain selected date."); } @Test public void testDayClassFunction() { selenium.click(pjq("input[name$=dayClassFunctionInput][value=yellowTuesdays]")); selenium.waitForPageToLoad(); selenium.click(input); for (int i = 2; i < 42; i += 7) { if (!selenium.belongsClass(cellDay.format(i), "rf-ca-boundary-dates")) { assertTrue(selenium.belongsClass(cellDay.format(i), "yellowDay"), "Cell nr. " + i + " should be yellow."); } } selenium.click(pjq("input[name$=dayClassFunctionInput][value=]")); selenium.waitForPageToLoad(); selenium.click(input); for (int i = 0; i < 42; i++) { assertFalse(selenium.belongsClass(cellDay.format(i), "yellowDay"), "Cell nr. " + i + " should not be yellow."); } } @Test - @IssueTracking("https://issues.jboss.org/browse/RF-9837") + @IssueTracking("https://issues.jboss.org/browse/RF-9837 https://issues.jboss.org/browse/RF-10085") public void testDefaultTime() { selenium.type(pjq("input[type=text][id$=defaultTimeInput]"), "21:24"); selenium.waitForPageToLoad(); selenium.click(input); selenium.click(cellWeekDay.format(3, 3)); boolean displayed = selenium.isDisplayed(timeButton); assertTrue(displayed, "Time button should be visible."); String buttonText = selenium.getText(timeButton); assertEquals(buttonText, "21:24", "Default time"); } @Test public void testDisabled() { selenium.click(pjq("input[name$=disabledInput][value=true]")); selenium.waitForPageToLoad(); AttributeLocator disabledAttr = input.getAttribute(new Attribute("disabled")); assertTrue(selenium.isAttributePresent(disabledAttr), "Disabled attribute of input should be defined."); assertEquals(selenium.getAttribute(disabledAttr), "disabled", "Input should be disabled."); selenium.click(input); assertFalse(selenium.isDisplayed(popup), "Popup should not be displayed."); selenium.click(image); assertFalse(selenium.isDisplayed(popup), "Popup should not be displayed."); } @Test public void testEnableManualInput() { AttributeLocator readonlyAttr = input.getAttribute(new Attribute("readonly")); assertTrue(selenium.isAttributePresent(readonlyAttr), "Readonly attribute of input should be defined."); assertEquals(selenium.getAttribute(readonlyAttr), "readonly", "Input should be read-only."); selenium.click(pjq("input[name$=enableManualInputInput][value=true]")); selenium.waitForPageToLoad(); assertFalse(selenium.isAttributePresent(readonlyAttr), "Readonly attribute of input should not be defined."); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9646") public void testFirstWeekDay() { selenium.type(pjq("input[type=text][id$=firstWeekDayInput]"), "6"); selenium.waitForPageToLoad(); selenium.click(input); String[] labels = {"", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"}; for (int i = 0; i < 8; i++) { String label = selenium.getText(weekDayLabel.format(i)); assertEquals(label, labels[i], "Week day label " + i); } // wrong input - throws a server-side exception // selenium.type(pjq("input[type=text][id$=firstWeekDayInput]"), "9"); // selenium.waitForPageToLoad(); // // selenium.click(input); // // labels = new String[]{"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // // for (int i = 0; i < 8; i++) { // String label = selenium.getText(weekDayLabel.format(i)); // assertEquals(label, labels[i], "Week day label " + i); // } } @Test public void testInputClass() { testStyleClass(input, "inputClass"); } @Test public void testInputSize() { selenium.type(pjq("input[type=text][id$=inputSizeInput]"), "30"); selenium.waitForPageToLoad(); AttributeLocator sizeAttr = input.getAttribute(Attribute.SIZE); assertTrue(selenium.isAttributePresent(sizeAttr), "Size attribute of input should be defined."); assertEquals(selenium.getAttribute(sizeAttr), "30", "Input should be disabled."); } @Test public void testInputStyle() { testStyle(input, "inputStyle"); } @Test public void testLocale() { selenium.type(pjq("input[type=text][id$=localeInput]"), "ru"); selenium.waitForPageToLoad(); selenium.click(input); String[] labels = {"", "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"}; for (int i = 0; i < 8; i++) { String label = selenium.getText(weekDayLabel.format(i)); assertEquals(label, labels[i], "Week day label " + i); } selenium.click(cellDay.format(6)); String day = selenium.getText(cellDay.format(6)); String month = selenium.getText(monthLabel); String selectedDate = null; try { Date date = new SimpleDateFormat("d MMMM, yyyy hh:mm", new Locale("ru")).parse(day + " " + month + " 12:00"); selectedDate = new SimpleDateFormat("MMM d, yyyy hh:mm", new Locale("ru")).format(date); } catch (ParseException ex) { fail(ex.getMessage()); } selenium.click(applyButton); String inputDate = selenium.getValue(input); assertEquals(inputDate, selectedDate, "Input doesn't contain selected date."); } @Test public void testOninputblur() { testFireEvent(Event.BLUR, input, "inputblur"); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9602") public void testOninputchange() { selenium.click(pjq("input[name$=enableManualInputInput][value=true]")); selenium.waitForPageToLoad(); selenium.type(pjq("input[id$=oninputchangeInput]"), "metamerEvents += \"inputchange \""); selenium.waitForPageToLoad(TIMEOUT); selenium.type(input, "Dec 23, 2010 19:27"); waitGui.failWith("Attribute oninputchange does not work correctly").until( new EventFiredCondition(new Event("inputchange"))); } @Test public void testOninputclick() { testFireEvent(Event.CLICK, input, "inputclick"); } @Test public void testOninputdblclick() { testFireEvent(Event.DBLCLICK, input, "inputdblclick"); } @Test public void testOninputfocus() { testFireEvent(Event.FOCUS, input, "inputfocus"); } @Test public void testOninputkeydown() { testFireEvent(Event.KEYDOWN, input, "inputkeydown"); } @Test public void testOninputkeypress() { testFireEvent(Event.KEYPRESS, input, "inputkeypress"); } @Test public void testOninputkeyup() { testFireEvent(Event.KEYUP, input, "inputkeyup"); } @Test public void testOninputmousedown() { testFireEvent(Event.MOUSEDOWN, input, "inputmousedown"); } @Test public void testOninputmousemove() { testFireEvent(Event.MOUSEMOVE, input, "inputmousemove"); } @Test public void testOninputmouseout() { testFireEvent(Event.MOUSEOUT, input, "inputmouseout"); } @Test public void testOninputmouseover() { testFireEvent(Event.MOUSEOVER, input, "inputmouseover"); } @Test public void testOninputmouseup() { testFireEvent(Event.MOUSEUP, input, "inputmouseup"); } @Test public void testOninputselect() { testFireEvent(Event.SELECT, input, "inputselect"); } @Test public void testPopup() { selenium.click(pjq("input[name$=popupInput][value=false]")); selenium.waitForPageToLoad(); boolean displayed = selenium.isDisplayed(calendar); assertTrue(displayed, "Calendar is not present on the page."); if (selenium.isElementPresent(input)) { displayed = selenium.isDisplayed(input); assertFalse(displayed, "Calendar's input should not be visible."); } if (selenium.isElementPresent(image)) { displayed = selenium.isDisplayed(image); assertFalse(displayed, "Calendar's image should not be visible."); } displayed = selenium.isDisplayed(popup); assertTrue(displayed, "Popup should be visible."); displayed = selenium.isElementPresent(button); assertFalse(displayed, "Calendar's button should not be visible."); } @Test public void testRendered() { selenium.click(pjq("input[type=radio][name$=renderedInput][value=false]")); selenium.waitForPageToLoad(); assertFalse(selenium.isElementPresent(calendar), "Panel should not be rendered when rendered=false."); } @Test public void testShowApplyButton() { selenium.click(pjq("input[type=radio][name$=showApplyButtonInput][value=false]")); selenium.waitForPageToLoad(); selenium.click(input); if (selenium.isElementPresent(applyButton)) { assertFalse(selenium.isDisplayed(applyButton), "Apply button should not be displayed."); } guardXhr(selenium).click(cellDay.format(6)); String day = selenium.getText(cellDay.format(6)); String month = selenium.getText(monthLabel); String selectedDate = null; try { Date date = new SimpleDateFormat("d MMMM, yyyy hh:mm").parse(day + " " + month + " 12:00"); selectedDate = new SimpleDateFormat("MMM d, yyyy hh:mm").format(date); } catch (ParseException ex) { fail(ex.getMessage()); } assertFalse(selenium.isDisplayed(popup), "Popup should not be displayed."); String inputDate = selenium.getValue(input); assertEquals(inputDate, selectedDate, "Input doesn't contain selected date."); } @Test public void testShowFooter() { selenium.click(pjq("input[type=radio][name$=showFooterInput][value=false]")); selenium.waitForPageToLoad(); selenium.click(input); boolean displayed = true; if (selenium.isElementPresent(todayButton)) { displayed = selenium.isDisplayed(todayButton); assertFalse(displayed, "Today button should not be visible."); } if (selenium.isElementPresent(applyButton)) { displayed = selenium.isDisplayed(applyButton); assertFalse(displayed, "Apply button should not be visible."); } displayed = selenium.isElementPresent(cleanButton); assertFalse(displayed, "Clean button should not be visible."); displayed = selenium.isElementPresent(timeButton); assertFalse(displayed, "Time button should not be visible."); selenium.click(cellWeekDay.format(3, 3)); if (selenium.isElementPresent(cleanButton)) { displayed = selenium.isDisplayed(cleanButton); assertFalse(displayed, "Clean button should not be visible."); } if (selenium.isElementPresent(timeButton)) { displayed = selenium.isDisplayed(timeButton); assertFalse(displayed, "Time button should not be visible."); } } @Test public void testShowHeader() { selenium.click(pjq("input[type=radio][name$=showHeaderInput][value=false]")); selenium.waitForPageToLoad(); selenium.click(input); boolean displayed = true; if (selenium.isElementPresent(prevYearButton)) { displayed = selenium.isDisplayed(prevYearButton); assertFalse(displayed, "Previous year button should not be visible."); } if (selenium.isElementPresent(prevMonthButton)) { displayed = selenium.isDisplayed(prevMonthButton); assertFalse(displayed, "Previous month button should not be visible."); } if (selenium.isElementPresent(nextMonthButton)) { displayed = selenium.isDisplayed(nextMonthButton); assertFalse(displayed, "Next month button should not be visible."); } if (selenium.isElementPresent(nextYearButton)) { displayed = selenium.isDisplayed(nextYearButton); assertFalse(displayed, "Next year button should not be visible."); } if (selenium.isElementPresent(closeButton)) { displayed = selenium.isDisplayed(closeButton); assertFalse(displayed, "Close button should not be visible."); } if (selenium.isElementPresent(monthLabel)) { displayed = selenium.isDisplayed(monthLabel); assertFalse(displayed, "Month label should not be visible."); } } @Test public void testShowInput() { selenium.click(pjq("input[type=radio][name$=showInputInput][value=false]")); selenium.waitForPageToLoad(); if (selenium.isElementPresent(input)) { boolean displayed = selenium.isDisplayed(input); assertFalse(displayed, "Input should not be visible."); } } @Test public void testShowWeekDaysBar() { selenium.click(pjq("input[type=radio][name$=showWeekDaysBarInput][value=false]")); selenium.waitForPageToLoad(); for (int i = 0; i < 8; i++) { if (selenium.isElementPresent(weekDayLabel.format(i))) { boolean displayed = selenium.isDisplayed(weekDayLabel.format(i)); assertFalse(displayed, "Bar with week days should not be visible."); } } } @Test public void testShowWeeksBar() { selenium.click(pjq("input[type=radio][name$=showWeeksBarInput][value=false]")); selenium.waitForPageToLoad(); for (int i = 0; i < 6; i++) { if (selenium.isElementPresent(week.format(i))) { boolean displayed = selenium.isDisplayed(week.format(i)); assertFalse(displayed, "Bar with week numbers should not be visible."); } } } @Test public void testValueChangeListener() { String time1Value = selenium.getText(time); selenium.click(input); selenium.click(cellDay.format(6)); guardXhr(selenium).click(applyButton); waitGui.failWith("Page was not updated").waitForChange(time1Value, retrieveText.locator(time)); String selectedDate1 = selenium.getValue(input); String selectedDate2 = selenium.getText(output); String listenerOutput = selenium.getText(jq("ul.phases-list li:eq(3)")); assertEquals(selectedDate1, selectedDate2, "Output and calendar's input should be the same."); assertEquals(listenerOutput, "* value changed: null -> " + selectedDate1); } /** * Checks that no date in the open month is selected. */ private void assertNoDateSelected() { for (int i = 0; i < 42; i++) { assertFalse(selenium.belongsClass(cellDay.format(i), "rf-ca-sel"), "Cell nr. " + i + " should not be selected."); } } /** * Checks that no date in the open month is selected except of one passed as argument. * @param exceptOfDate date that should be selected (e.g. "13") */ private void assertSelected(String exceptOfDate) { int lowerBoundary = 0; int upperBoundary = 42; if (Integer.parseInt(exceptOfDate) < 15) { upperBoundary = 21; } else { lowerBoundary = 21; } // check 3 lines of cells that contain selected date for (int i = lowerBoundary; i < upperBoundary; i++) { if (exceptOfDate.equals(selenium.getText(cellDay.format(i)))) { assertTrue(selenium.belongsClass(cellDay.format(i), "rf-ca-sel"), "Cell nr. " + i + " should not be selected."); } else { assertFalse(selenium.belongsClass(cellDay.format(i), "rf-ca-sel"), "Cell nr. " + i + " should not be selected."); } } lowerBoundary = lowerBoundary == 0 ? 21 : 0; upperBoundary = upperBoundary == 21 ? 42 : 21; // check other 3 lines of cells for (int i = lowerBoundary; i < upperBoundary; i++) { assertFalse(selenium.belongsClass(cellDay.format(i), "rf-ca-sel"), "Cell nr. " + i + " should not be selected."); } } } diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richInplaceInput/TestRichInplaceInput.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richInplaceInput/TestRichInplaceInput.java index 66bf2fc4..654a1e06 100644 --- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richInplaceInput/TestRichInplaceInput.java +++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richInplaceInput/TestRichInplaceInput.java @@ -1,370 +1,371 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *******************************************************************************/ package org.richfaces.tests.metamer.ftest.richInplaceInput; import static org.jboss.test.selenium.locator.LocatorFactory.jq; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardNoRequest; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardXhr; import static org.jboss.test.selenium.utils.URLUtils.buildUrl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.net.URL; import javax.faces.event.PhaseId; import org.jboss.test.selenium.css.CssProperty; import org.jboss.test.selenium.dom.Event; import org.jboss.test.selenium.locator.Attribute; import org.jboss.test.selenium.locator.JQueryLocator; import org.jboss.test.selenium.waiting.EventFiredCondition; import org.richfaces.tests.metamer.ftest.AbstractMetamerTest; import org.richfaces.tests.metamer.ftest.annotations.IssueTracking; import org.testng.annotations.Test; /** * Test case for page faces/components/richInplaceInput/simple.xhtml. * * @author <a href="mailto:[email protected]">Pavol Pitonak</a> * @version $Revision$ */ public class TestRichInplaceInput extends AbstractMetamerTest { private JQueryLocator inplaceInput = pjq("span[id$=inplaceInput]"); private JQueryLocator label = pjq("span.rf-ii-lbl"); private JQueryLocator input = pjq("input[id$=inplaceInputInput]"); private JQueryLocator edit = pjq("span.rf-ii-edit"); private JQueryLocator okButton = pjq("input.rf-ii-btn[id$=Okbtn]"); private JQueryLocator cancelButton = pjq("input.rf-ii-btn[id$=Cancelbtn]"); private JQueryLocator output = pjq("span[id$=output]"); @Override public URL getTestUrl() { return buildUrl(contextPath, "faces/components/richInplaceInput/simple.xhtml"); } @Test public void testInit() { assertTrue(selenium.isElementPresent(inplaceInput), "Inplace input is not on the page."); assertTrue(selenium.isElementPresent(label), "Default label should be present on the page."); assertEquals(selenium.getText(label), "RichFaces 4", "Default label"); assertTrue(selenium.isElementPresent(inplaceInput), "Input should be present on the page."); assertFalse(selenium.isElementPresent(okButton), "OK button should not be present on the page."); assertFalse(selenium.isElementPresent(cancelButton), "Cancel button should not be present on the page."); assertEquals(selenium.getValue(input), "RichFaces 4", "Value of inplace input."); } @Test public void testClick() { guardNoRequest(selenium).click(inplaceInput); assertFalse(selenium.belongsClass(edit, "rf-ii-none"), "Edit should not contain class rf-is-none when popup is open."); assertTrue(selenium.isDisplayed(input), "Input should be displayed."); selenium.type(input, "new value"); selenium.fireEvent(input, Event.BLUR); assertTrue(selenium.belongsClass(inplaceInput, "rf-ii-c-s"), "New class should be added to inplace input."); assertTrue(selenium.belongsClass(edit, "rf-ii-none"), "Edit should contain class rf-is-none when popup is closed."); assertEquals(selenium.getText(label), "new value", "Label should contain selected value."); assertEquals(selenium.getText(output), "new value", "Output did not change."); String listenerText = selenium.getText(jq("div#phasesPanel li:eq(3)")); assertEquals(listenerText, "* value changed: RichFaces 4 -> new value", "Value change listener was not invoked."); } @Test public void testDefaultLabel() { selenium.type(pjq("input[type=text][id$=valueInput]"), ""); selenium.waitForPageToLoad(); assertEquals(selenium.getText(label), "Click here to edit", "Default label should change"); selenium.type(pjq("input[type=text][id$=defaultLabelInput]"), ""); selenium.waitForPageToLoad(); assertEquals(selenium.getText(label), "", "Default label should change"); assertTrue(selenium.isElementPresent(inplaceInput), "Inplace select is not on the page."); assertTrue(selenium.isElementPresent(label), "Default label should be present on the page."); assertTrue(selenium.isElementPresent(input), "Input should be present on the page."); } @Test public void testEditClass() { testStyleClass(edit, "editClass"); } @Test public void testEditEvent() { selenium.type(pjq("input[type=text][id$=editEventInput]"), "mouseup"); selenium.waitForPageToLoad(); selenium.mouseDown(inplaceInput); assertTrue(selenium.belongsClass(edit, "rf-ii-none"), "Inplace input should not be in edit state."); selenium.mouseUp(inplaceInput); assertFalse(selenium.belongsClass(edit, "rf-ii-none"), "Inplace input should be in edit state."); } @Test public void testImmediate() { selenium.click(pjq("input[type=radio][name$=immediateInput][value=true]")); selenium.waitForPageToLoad(); String timeValue = selenium.getText(time); selenium.click(inplaceInput); selenium.type(input, "new value"); selenium.fireEvent(input, Event.BLUR); waitGui.failWith("Page was not updated").waitForChange(timeValue, retrieveText.locator(time)); assertPhases(PhaseId.RESTORE_VIEW, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS, PhaseId.UPDATE_MODEL_VALUES, PhaseId.INVOKE_APPLICATION, PhaseId.RENDER_RESPONSE); String listenerText = selenium.getText(jq("div#phasesPanel li:eq(2)")); assertEquals(listenerText, "* value changed: RichFaces 4 -> new value", "Value change listener was not invoked."); } @Test @IssueTracking("http://java.net/jira/browse/JAVASERVERFACES-1805") public void testInputWidth() { selenium.type(pjq("input[type=text][id$=inputWidthInput]"), "300px"); selenium.waitForPageToLoad(); String width = selenium.getStyle(input, CssProperty.WIDTH); assertEquals(width, "300px", "Width of input did not change."); selenium.type(pjq("input[type=text][id$=inputWidthInput]"), ""); selenium.waitForPageToLoad(); // it cannot handle null because of a bug in Mojarra and Myfaces and // generates style="width: ; " instead of default value assertTrue(selenium.isAttributePresent(input.getAttribute(Attribute.STYLE)), "Input doesn't have attribute style."); width = selenium.getAttribute(input.getAttribute(Attribute.STYLE)); assertTrue(!width.contains("width: ;"), "Default width of input was not set (was " + width + ")."); } @Test public void testNoneClass() { selenium.type(pjq("input[type=text][id$=valueInput]"), ""); selenium.waitForPageToLoad(); testStyleClass(edit, "noneClass"); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9868") public void testOnblur() { selenium.type(pjq("input[id$=onblurInput]"), "metamerEvents += \"blur \""); selenium.waitForPageToLoad(TIMEOUT); selenium.click(inplaceInput); selenium.fireEvent(input, Event.BLUR); waitGui.failWith("Attribute onblur does not work correctly").until(new EventFiredCondition(Event.BLUR)); } @Test + @IssueTracking("https://issues.jboss.org/browse/RF-10044") public void testOnchange() { selenium.type(pjq("input[type=text][id$=onchangeInput]"), "metamerEvents += \"change \""); selenium.waitForPageToLoad(); String timeValue = selenium.getText(time); selenium.click(inplaceInput); selenium.type(input, "new value"); selenium.fireEvent(input, Event.BLUR); waitFor(5000); waitGui.failWith("Page was not updated").waitForChange(timeValue, retrieveText.locator(time)); waitGui.failWith("Attribute onchange does not work correctly").until( new EventFiredCondition(new Event("change"))); } @Test public void testOnclick() { testFireEvent(Event.CLICK, inplaceInput); } @Test public void testOndblclick() { testFireEvent(Event.DBLCLICK, inplaceInput); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9868") public void testOnfocus() { selenium.type(pjq("input[id$=onfocusInput]"), "metamerEvents += \"focus \""); selenium.waitForPageToLoad(TIMEOUT); selenium.click(inplaceInput); waitGui.failWith("Attribute onfocus does not work correctly").until(new EventFiredCondition(Event.FOCUS)); } @Test public void testOninputclick() { testFireEvent(Event.CLICK, input, "inputclick"); } @Test public void testOninputdblclick() { testFireEvent(Event.DBLCLICK, input, "inputdblclick"); } @Test public void testOninputkeydown() { testFireEvent(Event.KEYDOWN, input, "inputkeydown"); } @Test public void testOninputkeypress() { testFireEvent(Event.KEYPRESS, input, "inputkeypress"); } @Test public void testOninputkeyup() { testFireEvent(Event.KEYUP, input, "inputkeyup"); } @Test public void testOninputmousedown() { testFireEvent(Event.MOUSEDOWN, input, "inputmousedown"); } @Test public void testOninputmousemove() { testFireEvent(Event.MOUSEMOVE, input, "inputmousemove"); } @Test public void testOninputmouseout() { testFireEvent(Event.MOUSEOUT, input, "inputmouseout"); } @Test public void testOninputmouseover() { testFireEvent(Event.MOUSEOVER, input, "inputmouseover"); } @Test public void testOninputmouseup() { testFireEvent(Event.MOUSEUP, input, "inputmouseup"); } @Test public void testOninputselect() { testFireEvent(Event.SELECT, input, "inputselect"); } @Test public void testOnkeydown() { testFireEvent(Event.KEYDOWN, inplaceInput); } @Test public void testOnkeypress() { testFireEvent(Event.KEYPRESS, inplaceInput); } @Test public void testOnkeyup() { testFireEvent(Event.KEYUP, inplaceInput); } @Test public void testOnmousedown() { testFireEvent(Event.MOUSEDOWN, inplaceInput); } @Test public void testOnmousemove() { testFireEvent(Event.MOUSEMOVE, inplaceInput); } @Test public void testOnmouseout() { testFireEvent(Event.MOUSEOUT, inplaceInput); } @Test public void testOnmouseover() { testFireEvent(Event.MOUSEOVER, inplaceInput); } @Test public void testOnmouseup() { testFireEvent(Event.MOUSEUP, inplaceInput); } @Test public void testRendered() { selenium.click(pjq("input[type=radio][name$=renderedInput][value=false]")); selenium.waitForPageToLoad(); assertFalse(selenium.isElementPresent(inplaceInput), "Component should not be rendered when rendered=false."); } @Test public void testShowControls() { selenium.click(pjq("input[type=radio][name$=showControlsInput][value=true]")); selenium.waitForPageToLoad(); selenium.click(inplaceInput); assertTrue(selenium.isVisible(okButton), "OK button should be visible."); assertTrue(selenium.isVisible(cancelButton), "Cancel button should be visible."); } @Test public void testClickOkButton() { selenium.click(pjq("input[type=radio][name$=showControlsInput][value=true]")); selenium.waitForPageToLoad(); String timeValue = selenium.getText(time); selenium.click(inplaceInput); guardNoRequest(selenium).keyPress(input, "x"); guardXhr(selenium).mouseDown(okButton); waitGui.failWith("Page was not updated").waitForChange(timeValue, retrieveText.locator(time)); assertEquals(selenium.getText(label), "RichFaces 4x", "Label"); assertEquals(selenium.getValue(input), "RichFaces 4x", "Value of inplace input"); assertEquals(selenium.getText(output), "RichFaces 4x", "Output"); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9872") public void testClickCancelButton() { selenium.click(pjq("input[type=radio][name$=showControlsInput][value=true]")); selenium.waitForPageToLoad(); selenium.click(inplaceInput); guardNoRequest(selenium).keyPress(input, "x"); guardNoRequest(selenium).mouseDown(cancelButton); assertEquals(selenium.getText(label), "RichFaces 4", "Label"); assertEquals(selenium.getValue(input), "RichFaces 4", "Value of inplace input."); assertEquals(selenium.getText(output), "RichFaces 4", "Output did not change."); } @Test public void testValue() { selenium.type(pjq("input[type=text][id$=valueInput]"), "new value"); selenium.waitForPageToLoad(); assertEquals(selenium.getText(label), "new value", "Default label"); assertEquals(selenium.getValue(input), "new value", "Value of inplace input."); } } diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richSelect/TestRichSelect.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richSelect/TestRichSelect.java index 70a52ee4..4cab4f94 100644 --- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richSelect/TestRichSelect.java +++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richSelect/TestRichSelect.java @@ -1,481 +1,482 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *******************************************************************************/ package org.richfaces.tests.metamer.ftest.richSelect; import static org.jboss.test.selenium.locator.LocatorFactory.jq; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardNoRequest; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guardXhr; import static org.jboss.test.selenium.utils.URLUtils.buildUrl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.net.URL; import org.jboss.test.selenium.css.CssProperty; import org.jboss.test.selenium.dom.Event; import org.jboss.test.selenium.locator.Attribute; import org.jboss.test.selenium.locator.AttributeLocator; import org.jboss.test.selenium.locator.JQueryLocator; import org.jboss.test.selenium.waiting.EventFiredCondition; import org.richfaces.tests.metamer.ftest.AbstractMetamerTest; import org.richfaces.tests.metamer.ftest.annotations.IssueTracking; import org.testng.annotations.Test; /** * Test case for page faces/components/richSelect/simple.xhtml. * * @author <a href="mailto:[email protected]">Pavol Pitonak</a> * @version $Revision$ */ public class TestRichSelect extends AbstractMetamerTest { private JQueryLocator select = pjq("div[id$=select]"); private JQueryLocator input = pjq("input.rf-sel-inp[id$=selectInput]"); private AttributeLocator inputValue = input.getAttribute(Attribute.VALUE); private JQueryLocator popup = jq("div.rf-sel-lst-cord"); private JQueryLocator options = jq("div.rf-sel-opt:eq({0})"); // 00..49 private JQueryLocator button = pjq("div.rf-sel-btn"); private JQueryLocator output = pjq("span[id$=output]"); @Override public URL getTestUrl() { return buildUrl(contextPath, "faces/components/richSelect/simple.xhtml"); } @Test public void testInit() { assertTrue(selenium.isElementPresent(select), "Inplace select is not on the page."); assertTrue(selenium.isElementPresent(button), "Button should be present on the page."); assertEquals(selenium.getAttribute(inputValue), "Click here to edit", "Default label"); assertTrue(selenium.isElementPresent(input), "Input should be present on the page."); assertFalse(selenium.isVisible(popup), "Popup should not be displayed on the page."); } @Test public void testSelectWithMouse() { guardNoRequest(selenium).mouseDown(button); selenium.mouseUp(button); assertTrue(selenium.isVisible(popup), "Popup should be displayed."); for (int i = 0; i < 50; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); } String[] selectOptions = {"Alabama", "Hawaii", "Massachusetts", "New Mexico", "South Dakota"}; for (int i = 0; i < 50; i += 10) { assertEquals(selenium.getText(options.format(i)), selectOptions[i / 10], "Select option nr. " + i); } guardNoRequest(selenium).click(options.format(10)); guardXhr(selenium).fireEvent(input, Event.BLUR); assertTrue(selenium.belongsClass(options.format(10), "rf-sel-sel")); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("Hawaii")); } @Test public void testSelectWithKeyboard() { guardNoRequest(selenium).focus(input); guardNoRequest(selenium).keyDown(input, "\\40"); // arrow down assertTrue(selenium.isVisible(popup), "Popup should be displayed."); for (int i = 0; i < 50; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); } String[] selectOptions = {"Alabama", "Hawaii", "Massachusetts", "New Mexico", "South Dakota"}; for (int i = 0; i < 50; i += 10) { assertEquals(selenium.getText(options.format(i)), selectOptions[i / 10], "Select option nr. " + i); } for (int i = 0; i < 11; i++) { selenium.keyDown(input, "\\40"); // arrow down } guardNoRequest(selenium).keyDown(input, "\\13"); // enter guardXhr(selenium).fireEvent(input, Event.BLUR); assertTrue(selenium.belongsClass(options.format(10), "rf-sel-sel")); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("Hawaii")); } @Test public void testFiltering() { selenium.focus(input); guardNoRequest(selenium).keyPress(input, "a"); selenium.keyDown(input, "\\40"); // arrow down assertEquals(selenium.getCount(jq("div.rf-sel-opt")), 4, "Count of filtered options ('a')"); String[] selectOptions = {"Alabama", "Alaska", "Arizona", "Arkansas"}; for (int i = 0; i < 4; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); assertEquals(selenium.getText(options.format(i)), selectOptions[i], "Select option nr. " + i); } for (int i = 0; i < 3; i++) { selenium.keyDown(input, "\\40"); // arrow down } selenium.keyDown(input, "\\13"); // enter assertTrue(selenium.belongsClass(options.format(2), "rf-sel-sel")); selenium.type(input, "NoRtH"); selenium.keyDown(input, "\\40"); // arrow down assertEquals(selenium.getCount(jq("div.rf-sel-opt")), 2, "Count of filtered options ('NoRtH')"); selenium.keyDown(input, "\\40"); // arrow down selenium.keyDown(input, "\\13"); // enter guardXhr(selenium).fireEvent(input, Event.BLUR); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("North Carolina")); } @Test public void testDefaultLabel() { selenium.type(pjq("input[type=text][id$=defaultLabelInput]"), "new label"); selenium.waitForPageToLoad(); assertEquals(selenium.getAttribute(inputValue), "new label", "Default label should change"); selenium.type(pjq("input[type=text][id$=defaultLabelInput]"), ""); selenium.waitForPageToLoad(); assertTrue(selenium.isElementPresent(select), "Inplace select is not on the page."); assertTrue(selenium.isElementPresent(input), "Input should be present on the page."); assertFalse(selenium.isDisplayed(popup), "Popup should not be displayed on the page."); if (selenium.isAttributePresent(inputValue)) { assertEquals(selenium.getAttribute(inputValue), "", "Default value should be empty"); } } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9855") public void testEnableManualInput() { selenium.click(pjq("input[type=radio][name$=enableManualInputInput][value=false]")); selenium.waitForPageToLoad(); AttributeLocator readonlyAttr = input.getAttribute(new Attribute("readonly")); assertEquals(selenium.getAttribute(readonlyAttr), "readonly", "Input should be read-only"); selenium.mouseDown(button); assertTrue(selenium.isVisible(popup), "Popup should be displayed."); selenium.click(options.format(10)); selenium.fireEvent(input, Event.BLUR); + selenium.fireEvent(input, Event.BLUR); // blur has to be fired twice for Firefox - just Selenium hack assertTrue(selenium.belongsClass(options.format(10), "rf-sel-sel")); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("Hawaii")); } @Test public void testItemClass() { final String value = "metamer-ftest-class"; selenium.type(pjq("input[type=text][id$=itemClassInput]"), value); selenium.waitForPageToLoad(); for (int i = 0; i < 50; i++) { assertTrue(selenium.belongsClass(options.format(i), value), "Select option " + selenium.getText(options.format(i)) + " does not contain class " + value); } } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9735") public void testListClass() { testStyleClass(popup, "listClass"); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9737") public void testListHeight() { selenium.type(pjq("input[type=text][id$=listHeightInput]"), "300px"); selenium.waitForPageToLoad(); String height = selenium.getStyle(jq("div.rf-sel-lst-scrl"), CssProperty.HEIGHT); assertEquals(height, "300px", "Height of list did not change"); selenium.type(pjq("input[type=text][id$=listHeightInput]"), ""); selenium.waitForPageToLoad(); // it cannot handle null because of a bug in Mojarra and Myfaces and // generates style="height: ; " instead of default value height = selenium.getStyle(jq("span.rf-is-lst-scrl"), CssProperty.HEIGHT); assertEquals(height, "200px", "Height of list did not change"); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9737") public void testListWidth() { selenium.type(pjq("input[type=text][id$=listWidthInput]"), "300px"); selenium.waitForPageToLoad(); String width = selenium.getStyle(jq("span.rf-is-lst-pos"), CssProperty.WIDTH); assertEquals(width, "300px", "Width of list did not change"); selenium.type(pjq("input[type=text][id$=listWidthInput]"), ""); selenium.waitForPageToLoad(); // it cannot handle null because of a bug in Mojarra and Myfaces and // generates style="width: ; " instead of default value width = selenium.getStyle(jq("span.rf-is-lst-pos"), CssProperty.WIDTH); assertEquals(width, "200px", "Width of list did not change"); } @Test public void testOnblur() { testFireEvent(Event.BLUR, input); } @Test public void testOnchange() { selenium.type(pjq("input[type=text][id$=onchangeInput]"), "metamerEvents += \"change \""); selenium.waitForPageToLoad(); selenium.click(button); selenium.click(options.format(10)); selenium.fireEvent(input, Event.BLUR); waitGui.failWith("Attribute onchange does not work correctly").until( new EventFiredCondition(Event.CHANGE)); } @Test public void testOnclick() { testFireEvent(Event.CLICK, input); } @Test public void testOndblclick() { testFireEvent(Event.DBLCLICK, input); } @Test public void testOnfocus() { testFireEvent(Event.FOCUS, input); } @Test public void testOnkeydown() { testFireEvent(Event.KEYDOWN, input); } @Test public void testOnkeypress() { testFireEvent(Event.KEYPRESS, input); } @Test public void testOnkeyup() { testFireEvent(Event.KEYUP, input); } @Test public void testOnlistclick() { testFireEvent(Event.CLICK, popup, "listclick"); } @Test public void testOnlistdblclick() { testFireEvent(Event.DBLCLICK, popup, "listdblclick"); } @Test public void testOnlistkeydown() { testFireEvent(Event.KEYDOWN, popup, "listkeydown"); } @Test public void testOnlistkeypress() { testFireEvent(Event.KEYPRESS, popup, "listkeypress"); } @Test public void testOnlistkeyup() { testFireEvent(Event.KEYUP, popup, "listkeyup"); } @Test public void testOnlistmousedown() { testFireEvent(Event.MOUSEDOWN, popup, "listmousedown"); } @Test public void testOnlistmousemove() { testFireEvent(Event.MOUSEMOVE, popup, "listmousemove"); } @Test public void testOnlistmouseout() { testFireEvent(Event.MOUSEOUT, popup, "listmouseout"); } @Test public void testOnlistmouseover() { testFireEvent(Event.MOUSEOVER, popup, "listmouseover"); } @Test public void testOnlistmouseup() { testFireEvent(Event.MOUSEUP, popup, "listmouseup"); } @Test public void testOnmousedown() { testFireEvent(Event.MOUSEDOWN, input); } @Test public void testOnmousemove() { testFireEvent(Event.MOUSEMOVE, input); } @Test public void testOnmouseout() { testFireEvent(Event.MOUSEOUT, input); } @Test public void testOnmouseover() { testFireEvent(Event.MOUSEOVER, input); } @Test public void testOnmouseup() { testFireEvent(Event.MOUSEUP, input); } @Test public void testOnselectitem() { selenium.type(pjq("input[type=text][id$=onselectitemInput]"), "metamerEvents += \"selectitem \""); selenium.waitForPageToLoad(); selenium.click(button); selenium.click(options.format(10)); waitGui.failWith("Attribute onchange does not work correctly").until( new EventFiredCondition(new Event("selectitem"))); } @Test public void testRendered() { selenium.click(pjq("input[type=radio][name$=renderedInput][value=false]")); selenium.waitForPageToLoad(); assertFalse(selenium.isElementPresent(select), "Component should not be rendered when rendered=false."); } @Test public void testSelectFirst() { selenium.click(pjq("input[type=radio][name$=selectFirstInput][value=true]")); selenium.waitForPageToLoad(); selenium.focus(input); selenium.keyPress(input, "a"); selenium.keyDown(input, "\\40"); // arrow down waitFor(5000); assertEquals(selenium.getCount(jq("div.rf-sel-opt")), 4, "Count of filtered options ('a')"); String[] selectOptions = {"Alabama", "Alaska", "Arizona", "Arkansas"}; for (int i = 0; i < 4; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); assertEquals(selenium.getText(options.format(i)), selectOptions[i], "Select option nr. " + i); } assertTrue(selenium.belongsClass(options.format(0), "rf-sel-sel"), "First filtered option should be selected"); } @Test public void testSelectItemClass() { selenium.type(pjq("input[type=text][id$=selectItemClassInput]"), "metamer-ftest-class"); selenium.waitForPageToLoad(); selenium.focus(input); selenium.keyDown(input, "\\40"); // arrow down selenium.keyDown(input, "\\40"); // arrow down assertTrue(selenium.belongsClass(options.format(0), "metamer-ftest-class"), "Selected item does not contains defined class."); for (int i = 1; i < 50; i++) { assertFalse(selenium.belongsClass(options.format(i), "metamer-ftest-class"), "Not selected item " + i + " should not contain defined class."); } } @Test public void testShowButton() { selenium.click(pjq("input[type=radio][name$=showButtonInput][value=false]")); selenium.waitForPageToLoad(); selenium.click(select); if (selenium.isElementPresent(button)) { assertFalse(selenium.isVisible(button), "Button should not be visible."); } selenium.focus(input); selenium.keyDown(input, "\\40"); // arrow down assertTrue(selenium.isVisible(popup), "Popup should be displayed."); for (int i = 0; i < 50; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); } String[] selectOptions = {"Alabama", "Hawaii", "Massachusetts", "New Mexico", "South Dakota"}; for (int i = 0; i < 50; i += 10) { assertEquals(selenium.getText(options.format(i)), selectOptions[i / 10], "Select option nr. " + i); } for (int i = 0; i < 11; i++) { selenium.keyDown(input, "\\40"); // arrow down } selenium.keyDown(input, "\\13"); // enter guardXhr(selenium).fireEvent(input, Event.BLUR); assertTrue(selenium.belongsClass(options.format(10), "rf-sel-sel")); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("Hawaii")); } @Test @IssueTracking("https://issues.jboss.org/browse/RF-9663") public void testShowButtonClick() { selenium.click(pjq("input[type=radio][name$=showButtonInput][value=false]")); selenium.waitForPageToLoad(); selenium.click(select); if (selenium.isElementPresent(button)) { assertFalse(selenium.isVisible(button), "Button should not be visible."); } assertTrue(selenium.isVisible(popup), "Popup should be displayed."); for (int i = 0; i < 50; i++) { assertTrue(selenium.isDisplayed(options.format(i)), "Select option " + i + " should be displayed."); } String[] selectOptions = {"Alabama", "Hawaii", "Massachusetts", "New Mexico", "South Dakota"}; for (int i = 0; i < 50; i += 10) { assertEquals(selenium.getText(options.format(i)), selectOptions[i / 10], "Select option nr. " + i); } selenium.click(options.format(10)); guardXhr(selenium).fireEvent(input, Event.BLUR); assertTrue(selenium.belongsClass(options.format(10), "rf-sel-sel")); waitGui.failWith("Bean was not updated").until(textEquals.locator(output).text("Hawaii")); } }
false
false
null
null
diff --git a/database/Table.java b/database/Table.java index 8567630..7670fca 100644 --- a/database/Table.java +++ b/database/Table.java @@ -1,382 +1,390 @@ package database; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import main.Logger; import relationenalgebra.AndExpression; import relationenalgebra.EqualityExpression; import relationenalgebra.OrExpression; import relationenalgebra.PrimaryExpression; public class Table implements Serializable { private static class ValueLookup { private Map<String, Integer> indexMap; private Table[] tables; private int[] currentRowIndices; private boolean anonymous; ValueLookup(Table... tables) { indexMap = new HashMap<String, Integer>(); this.tables = tables; currentRowIndices = new int[tables.length]; anonymous = false; for (int i = 0; i < tables.length; i++) { indexMap.put(tables[i].getOfficialName(), Integer.valueOf(i)); if (tables[i].getOfficialName().equals("")) { anonymous = true; } } } void setCurrentRowIndex(Table table, int rowIndex) { currentRowIndices[indexMap.get(table.getOfficialName())] = rowIndex; } void setCurrentRowIndex(int tableIndex, int rowIndex) { currentRowIndices[tableIndex] = rowIndex; } String lookupValue(String name) { Integer tableIndex = Integer.valueOf(0); String columnName = name; if (!anonymous) { int i = name.indexOf("."); String tableName = name.substring(0, i); columnName = name.substring(i + 1, name.length()); tableIndex = indexMap.get(tableName); if (tableIndex == null) { throw new IllegalArgumentException("table '" + tableName + "' not found"); } } Table table = tables[tableIndex]; int rowIndex = currentRowIndices[tableIndex]; int columnIndex = table.getColumnIndex(columnName); if (columnIndex < 0) { throw new IllegalArgumentException("no column named '" + columnName + "' found in current table"); } return table.rows.get(rowIndex).get(columnIndex); } } static final long serialVersionUID = 1234; protected String name; protected String alias; protected boolean drop; protected List<String> columnNames; protected List<List<String>> rows; protected int cost; public Table(String name) { super(); this.name = name; this.setUp(); } public Table(String name, List<String> columns) { super(); this.name = name; this.columnNames = columns; this.setUp(); } private void setUp() { this.rows = newRowsList(); this.drop = false; } /** * Writes the actual instance to the filesystem. */ public void write() { FileSystemDatabase.getInstance().write(this); } /** * Returns one row from privat row repository. */ public List<String> getRow(int number) { return Collections.unmodifiableList(rows.get(number)); } public void addRow(List<String> names) { if (names.size() != columnNames.size()) { throw new IllegalArgumentException("bad row size"); } rows.add(new ArrayList<String>(names)); } public void deleteRow(int number) { rows.remove(number); } private int getColumnIndex(String name) { for (int i = 0; i < columnNames.size(); i++) { if (columnNames.get(i).equals(name)) { return i; } if (name.equals(getOfficialName() + "." + columnNames.get(i))) { return i; } } return -1; } private static List<List<String>> newRowsList() { return new LinkedList<List<String>>(); } public Table projectTo(List<String> param) { // compute indices for projection int[] projection = new int[param.size()]; for (int i = 0; i < projection.length; i++) { int index = getColumnIndex(param.get(i)); if (index < 0) { throw new IllegalArgumentException("no column with name '" + param.get(i) + "'"); } projection[i] = index; } //Logger.debug("projection: "+columnNames+" to "+param); // generate column names list List<String> newColumnNames = new ArrayList<String>(projection.length); for (int i = 0; i < projection.length; i++) { newColumnNames.add(columnNames.get(projection[i])); } // generate new rows list List<List<String>> newRows = newRowsList(); for (List<String> row : rows) { List<String> projectedRow = new ArrayList<String>(projection.length); for (int i = 0; i < projection.length; i++) { projectedRow.add(row.get(projection[i])); } newRows.add(projectedRow); } int newCost = this.cost + columnNames.size() * rows.size(); return createAlteredClone(newColumnNames, newRows, newCost); } private Table createAlteredClone(List<String> newColumnNames, List<List<String>> newRows, int newCost) { Table result = new Table(this.name); result.alias = this.alias; if (newColumnNames == null) { newColumnNames = new ArrayList<String>(this.columnNames); } result.columnNames = newColumnNames; result.drop = false; result.rows = newRows; result.cost = newCost; return result; } public Table select(AndExpression exp) { List<List<String>> newRows = newRowsList(); ValueLookup vl = new ValueLookup(this); //Logger.debug("selection: "+exp); //Logger.debug("name: "+getOfficialName()+", columns: "+columnNames); for (int i = 0; i < rows.size(); i++) { vl.setCurrentRowIndex(this, i); //Logger.debug("next row: "+rows.get(i)); if (evaluate(exp, vl)) { newRows.add(new ArrayList<String>(rows.get(i))); // Logger.debug("ADDED"); } //else Logger.debug("DISCARDED"); } int newCost = cost + newRows.size() * columnNames.size(); return createAlteredClone(null, newRows, newCost); } private boolean evaluate(AndExpression expr, ValueLookup vl) { /* if (expr.getExprs() == null) { return evaluate(expr.getExpr(), vl); } */ for (OrExpression or : expr.getExprs()) { if (!evaluate(or, vl)) { return false; } } return true; } private boolean evaluate(OrExpression expr, ValueLookup vl) { /* if (expr.getExprs() == null) { return evaluate(expr.getExpr(), vl); } */ for (EqualityExpression eq : expr.getExprs()) { if (evaluate(eq, vl)) { return true; } } return false; } private boolean evaluate(EqualityExpression expr, ValueLookup vl) { String valueA = retrieveValue(expr.getExpr1(), vl); String valueB = retrieveValue(expr.getExpr2(), vl); int cmp = valueA.compareTo(valueB); //Logger.debug("comparing "+valueA+" to "+valueB+": "+cmp); switch (expr.getOperator()) { case Equal: return cmp == 0; case Greater: return cmp > 0; case GreaterEqual: return cmp >= 0; case Lower: return cmp < 0; case LowerEqual: return cmp <= 0; case NotEqual: return cmp != 0; default: throw new RuntimeException("unknown operator: " + expr.getOperator()); } } private String getOfficialName() { if (alias != null) { return alias; } return name; } private String retrieveValue(PrimaryExpression expr, ValueLookup vl) { if (expr.isConstant()) { return expr.getValue(); } return vl.lookupValue(expr.getValue()); } private static List<String> toQualifiedColumnNames( List<String> columnNames, String tableName) { List<String> result = new ArrayList<String>(columnNames.size()); for (String name : columnNames) { if (tableName.length() == 0) { result.add(name); } else { result.add(tableName + "." + name); } } return result; } public Table join(Table table, AndExpression exp) { List<List<String>> newRows = newRowsList(); ValueLookup vl = new ValueLookup(this, table); int newRowSize = columnNames.size() + table.columnNames.size(); List<String> newColumnNames = new ArrayList<String>(newRowSize); newColumnNames.addAll(toQualifiedColumnNames(columnNames, getOfficialName())); newColumnNames.addAll(toQualifiedColumnNames(table.columnNames, table .getOfficialName())); + + //if (exp != null) + // System.out.println("new column names: "+newColumnNames); for (int i = 0; i < rows.size(); i++) { vl.setCurrentRowIndex(0, i); for (int j = 0; j < table.rows.size(); j++) { vl.setCurrentRowIndex(1, j); List<String> newRow = new ArrayList<String>(newRowSize); newRow.addAll(rows.get(i)); newRow.addAll(table.rows.get(j)); - //Logger.debug("next row "+i+", "+j+": "+newRow); + + //System.out.print("next row "+i+", "+j+": "+newRow); if (exp == null || evaluate(exp, vl)) { newRows.add(newRow); + //if (exp != null) System.out.println(" ACCEPTED"); + } else { + //if (exp != null) System.out.println(" REJECTED"); } } } Table result = new Table("", newColumnNames); result.rows = newRows; result.cost = this.cost + table.cost + newRows.size() * newColumnNames.size(); return result; } public Table cross(Table table) { return join(table, null); } public String toString() { String s = "table '" + this.name + "'\n\tcolumns: '"; for (String c : this.columnNames) { s += c + ", "; } s += "'\n\trows:\n"; if (this.rows != null) { for (List<String> row : this.rows) { s += "\t\t"; for (String value : row) { s += value + "\t"; } s += "\n"; } } s += "cost: " + cost + "\n"; return s; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public int getCost() { return cost; } public String[] getColumnnames() { return this.columnNames.toArray(new String[this.columnNames.size()]); } } diff --git a/main/Main.java b/main/Main.java index 2b100bc..d348400 100644 --- a/main/Main.java +++ b/main/Main.java @@ -1,250 +1,250 @@ package main; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import optimization.CascadeSelects; import optimization.DetectJoins; import optimization.IOptimization; import optimization.MoveProjection; import optimization.MoveSelection; import parser.gene.ParseException; import parser.gene.SimpleSQLParser; import parser.syntaxtree.CompilationUnit; import parser.visitor.ObjectDepthFirst; import relationenalgebra.CrossProduct; import relationenalgebra.IOneChildNode; import relationenalgebra.ITreeNode; import relationenalgebra.ITwoChildNode; import relationenalgebra.Join; import relationenalgebra.Projection; import relationenalgebra.Relation; import relationenalgebra.Selection; import relationenalgebra.TableOperation; import database.FileSystemDatabase; import database.Table; public class Main { // Verzeichnis der Buchversandsdatenbank public static final String KUNDENDB = "db"; public static void main(String[] args) throws IOException, ClassNotFoundException { //Logger.debug = true; //Logger.debug("DEBUGGING IS ENABLED"); Logger.debug("load database"); FileSystemDatabase.getInstance().setDbDirectory(KUNDENDB); Main.createKundenDB(); Logger.debug("execute sql"); //Main.execute("select B.Titel from Buch_Autor as BA, Buch as B where BA.Autorenname=\"Christian Ullenboom\" and BA.B_ID=B.ID"); //Main.execute("select B.Titel from Buch_Autor as BA, Buch as B where BA.Autorenname=\"Henning Mankell\" and BA.B_ID=B.ID"); //Main.execute("select B.Titel from Buch as B, Kunde as K, Buch_Bestellung as BB, Kunde_Bestellung as KB where K.Name=\"KName1\" and K.ID=KB.K_ID and KB.B_ID=BB.Be_ID and BB.Bu_ID=B.ID"); //Main.readFile("sql.txt"); Main.blockTwoOptimizationDemo(); //Main.printKundenDB(); //FileSystemDatabase.getInstance().persistDb(); } public static void blockTwoOptimizationDemo() { String[] queries = new String[]{ "select B.Titel \n" + "from \n" + " Buch as B, \n" + " Kunde as K, \n" + " Buch_Bestellung as BB,\n" + " Kunde_Bestellung as KB \n" + "where \n" + " K.Name=\"KName1\" and \n" + " K.ID=KB.K_ID and \n" + " KB.B_ID=BB.Be_ID and \n" + " BB.Bu_ID=B.ID", "select B.ID, K.Name \n" + "from\n" + " Bestellung as B, \n" + " Kunde as K, \n" + " Kunde_Bestellung as KB \n" + "where \n" + " KB.K_ID=K.ID and \n" + " KB.B_ID=B.ID and \n" + " B.ID=\"Bestellung5\"", "select Name \n" + "from \n" + " Kunde, \n" + " Kunde_Bestellung \n" + "where \n" + " ID=K_ID and \n" + " Name=\"KName1\"", }; IOptimization cascadeSelects = new CascadeSelects(); IOptimization detectJoins = new DetectJoins(); IOptimization moveSelection = new MoveSelection(); IOptimization moveProjection = new MoveProjection(); String[] titles = new String[]{ "Result with no optimizations: ", "Result with cascaded and moved selections: ", "Result with cascaded and moved selections and detected joins: ", "Result with cascaded and moved selections, detected joins and moved projections: ", }; IOptimization[][] optimizationLists = new IOptimization[][]{ new IOptimization[0], new IOptimization[]{ cascadeSelects, moveSelection }, new IOptimization[]{ cascadeSelects, moveSelection, detectJoins }, new IOptimization[]{ cascadeSelects, moveSelection, detectJoins, moveProjection }, }; for (String query : queries) { System.out.println("Next query: "); System.out.println(query); System.out.println(); for (int i = 0; i < titles.length; i++) { System.out.println(titles[i]); Table result = executeOptimized(query, optimizationLists[i]); if (result == null) { System.out.println("(no result, optimization failed)"); } else { System.out.println(result.toString()); } System.out.println(); } } } private static Table executeOptimized(String query, IOptimization[] optimizations) { ITreeNode plan = sqlToRelationenAlgebra(query); if (plan == null) { System.err.println("failed to parse query"); return null; } System.out.println("parsed plan: "); System.out.println(plan.toString()); for (IOptimization optimization : optimizations) { try { plan = optimization.optimize(plan); } catch (Exception e) { System.err.println("failed to optimize query using "+optimization); System.err.println(e.getMessage()); e.printStackTrace(); return null; } } System.out.println("optimized plan:"); System.out.println(plan); try { return executeQuery(plan); } catch (Exception e) { System.err.println("failed to execute query"); System.err.println(e.getMessage()); e.printStackTrace(); return null; } } public static void printKundenDB() throws IOException, ClassNotFoundException { FileSystemDatabase.getInstance().printDb(); } public static void createKundenDB() { Logger.debug("create kunden db"); Main.readFile("kundendb.txt"); } public static void execute(String simpleSQL) { ITreeNode plan = Main.sqlToRelationenAlgebra(simpleSQL); Main.executePlan(plan); } public static ITreeNode sqlToRelationenAlgebra(String simpleSQL) { SimpleSQLParser parser = new SimpleSQLParser( new StringReader(simpleSQL)); parser.setDebugALL(Logger.debug); Logger.debug("parsing: "+simpleSQL); CompilationUnit cu = null; try { cu = parser.CompilationUnit(); ObjectDepthFirst v = new ObjectDepthFirst(); cu.accept(v, null); } catch (ParseException e) { System.err.println(e.getMessage()); return null; } return (ITreeNode) cu.accept(new AlgebraVisitor(), null); } private static void executePlan(ITreeNode plan) { if (plan instanceof TableOperation) ((TableOperation) plan).execute(); else { Logger.debug("QUERY: "+plan); Table result = executeQuery(plan); Logger.debug("QUERY RESULT: "); Logger.debug(result.toString()); } } private static Table executeQuery(ITreeNode query) { if (query instanceof ITwoChildNode) { Table child1Result = executeQuery(((ITwoChildNode)query).getChild()); Table child2Result = executeQuery(((ITwoChildNode)query).getSecondChild()); - if (query instanceof CrossProduct) - return child1Result.cross(child2Result); if (query instanceof Join) return child1Result.join(child2Result, ((Join)query).getExpr()); + if (query instanceof CrossProduct) + return child1Result.cross(child2Result); } else if (query instanceof IOneChildNode) { Table childResult = executeQuery(((IOneChildNode)query).getChild()); if (query instanceof Projection) return childResult.projectTo(((Projection)query).getColumnnames()); if (query instanceof Selection) return childResult.select(((Selection)query).getExpr()); } else if (query instanceof Relation) { Relation r = (Relation)query; Table t = FileSystemDatabase.getInstance().getTable(r.getName()); t.setAlias(r.getAlias()); return t; } throw new IllegalArgumentException("unknown node type: "+query); } private static void readFile(String filename) { File f = new File(filename); if (!f.isFile()) return; try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console if (!strLine.equals("\n") && !strLine.equals("")) Main.execute(strLine); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any throw new RuntimeException(e); } } }
false
false
null
null
diff --git a/netbout/netbout-inf/src/main/java/com/netbout/inf/index/EbsDirectory.java b/netbout/netbout-inf/src/main/java/com/netbout/inf/index/EbsDirectory.java index e886782ee..9b83f3f1b 100644 --- a/netbout/netbout-inf/src/main/java/com/netbout/inf/index/EbsDirectory.java +++ b/netbout/netbout-inf/src/main/java/com/netbout/inf/index/EbsDirectory.java @@ -1,317 +1,318 @@ /** * Copyright (c) 2009-2012, Netbout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.inf.index; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.ymock.util.Logger; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.CharEncoding; /** * Directory for EBS volume. * * <p>The class is immutable and thread-safe. * * @author Yegor Bugayenko ([email protected]) * @author Krzysztof Krason ([email protected]) * @version $Id$ */ @SuppressWarnings("PMD.TooManyMethods") final class EbsDirectory implements Closeable { /** * Mounting directory. */ private final transient File directory; /** * Our host. */ private final transient String host; /** * Public ctor. * @param path Directory */ public EbsDirectory(final File path) { this(path, "localhost"); } /** * Public ctor. * @param path Directory * @param hst The host where we're working */ public EbsDirectory(final File path, final String hst) { this.directory = path; this.host = hst; } /** * {@inheritDoc} */ @Override public void close() throws IOException { // @checkstyle MultipleStringLiterals (1 line) this.exec("sudo", "-S", "umount", this.directory); } /** * Some stats to show. * @return The text */ public String statistics() { final StringBuilder text = new StringBuilder(); text.append(String.format("directory: %s\n", this.directory)); text.append(String.format("host: %s\n", this.host)); try { // @checkstyle MultipleStringLiterals (1 line) text.append(this.exec("mount")); } catch (IOException ex) { text.append(String.format("%[exception]s", ex)); } return text.toString(); } /** * The path. * @return File */ public File path() { if (!this.directory.exists()) { if (this.directory.mkdirs()) { Logger.info( this, "#path(): directory '%s' created", this.directory ); } else { Logger.info( this, "#path(): directory '%s' already exists", this.directory ); } } return this.directory; } /** * The directory is mounted already? * @return Yes or no? * @throws IOException If some IO problem inside */ public boolean mounted() throws IOException { // @checkstyle MultipleStringLiterals (1 line) final String output = this.exec("mount"); final boolean mounted = output.contains(this.path().getPath()); if (mounted) { Logger.info( this, "#mounted(): '%s' is already mounted", this.path() ); } else { Logger.info( this, "#mounted(): '%s' is not mounted yet", this.path() ); } return mounted; } /** * Mount this device to our directory. * @param device Name of device to mount * @throws IOException If some IO problem inside + * @see <a href="http://serverfault.com/questions/376455">why chown</a> */ public void mount(final String device) throws IOException { FileUtils.deleteQuietly(this.directory); final String output = this.exec( "sudo", "-S", "mount", "-t", "ext3", device, this.path(), "&&", "chown", "tomcat7.tomcat7", this.path() ); Logger.info( this, "#mount(%s): mounted as %s:\n%s", device, this.path(), output ); } /** * Execute unix command and return it's output as a string. * @param args Arguments of shell command * @return The output as a string (trimmed) * @throws IOException If some IO problem inside */ private String exec(final Object... args) throws IOException { try { final Session session = this.session(); session.connect(); final ChannelExec exec = (ChannelExec) session.openChannel("exec"); final String command = this.command(args); exec.setCommand(command); exec.connect(); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); exec.setErrStream(stderr); exec.setOutputStream(stdout); exec.setInputStream(null); final int code = this.code(exec); if (code != 0) { throw new IOException( String.format( "Failed to execute \"%s\" (code=%d): %s", command, code, new String(stderr.toByteArray(), CharEncoding.UTF_8) ) ); } final String output = new String( stdout.toByteArray(), CharEncoding.UTF_8 ); exec.disconnect(); session.disconnect(); Logger.info( this, "#exec(..): \"%s\"\n %s", command, output.replace("\n", "\n ") ); return output; } catch (com.jcraft.jsch.JSchException ex) { throw new IOException(ex); } } /** * Wait until it's done and return its code. * @param exec The channel * @return The exit code * @throws IOException If some IO problem inside */ private int code(final ChannelExec exec) throws IOException { int retry = 0; while (!exec.isClosed()) { ++retry; try { TimeUnit.SECONDS.sleep(retry * 1L); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IOException(ex); } // @checkstyle MagicNumber (1 line) if (retry > 10) { break; } Logger.info(this, "#pause(..): waiting for SSH (retry=%d)", retry); } return exec.getExitStatus(); } /** * Create and return a session. * @return JSch session * @throws IOException If some IO problem inside */ private Session session() throws IOException { try { final JSch jsch = new JSch(); jsch.setConfig("StrictHostKeyChecking", "no"); jsch.setLogger( new com.jcraft.jsch.Logger() { @Override public boolean isEnabled(final int level) { return true; } @Override public void log(final int level, final String msg) { Logger.info(EbsDirectory.class, "%s", msg); } } ); jsch.addIdentity(this.key().getPath()); return jsch.getSession("ec2-user", this.host); } catch (com.jcraft.jsch.JSchException ex) { throw new IOException(ex); } } /** * Create command. * @param args Arguments of shell command * @return The command */ private String command(final Object... args) { final StringBuilder command = new StringBuilder(); for (Object arg : args) { command.append(" '") .append(arg.toString().replace("'", "\\'")) .append("' "); } return command.toString().trim(); } /** * Get file with secret key. * @return The file * @throws IOException If some IO problem inside */ private File key() throws IOException { final File file = File.createTempFile("netbout-ebs", ".pem"); final URL key = this.getClass().getResource("ebs.pem"); if (key == null) { throw new IOException("PEM not found"); } FileUtils.copyURLToFile(key, file); FileUtils.forceDeleteOnExit(file); return file; } } diff --git a/netbout/netbout-rest/src/main/java/com/netbout/servlets/LifecycleListener.java b/netbout/netbout-rest/src/main/java/com/netbout/servlets/LifecycleListener.java index ca9c4a661..6d24cd7d0 100644 --- a/netbout/netbout-rest/src/main/java/com/netbout/servlets/LifecycleListener.java +++ b/netbout/netbout-rest/src/main/java/com/netbout/servlets/LifecycleListener.java @@ -1,92 +1,96 @@ /** * Copyright (c) 2009-2012, Netbout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.servlets; import com.netbout.hub.DefaultHub; import com.netbout.hub.Hub; import com.netbout.notifiers.email.EmailFarm; import com.rexsl.core.Manifests; import com.ymock.util.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Application-wide listener that initializes the application on start * and shuts it down on stop. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ public final class LifecycleListener implements ServletContextListener { /** * The hub. */ private transient Hub hub; /** * {@inheritDoc} * * <p>This attributes is used later in * {@link com.netbout.rest.AbstractRs#setServletContext(ServletContext)}. */ @Override public void contextInitialized(final ServletContextEvent event) { final long start = System.nanoTime(); Manifests.append(event.getServletContext()); this.hub = new DefaultHub(); event.getServletContext() .setAttribute("com.netbout.rest.HUB", this.hub); EmailFarm.setHub(this.hub); Logger.info( this, "contextInitialized(): done in %[nano]s", System.nanoTime() - start ); } /** * {@inheritDoc} */ @Override public void contextDestroyed(final ServletContextEvent event) { final long start = System.nanoTime(); if (this.hub != null) { try { this.hub.close(); } catch (java.io.IOException ex) { - throw new IllegalStateException(ex); + Logger.error( + this, + "#contextDestroyed(): %[exception]s", + ex + ); } } Logger.info( this, - "contextDestroyed(): done in %[nano]s", + "#contextDestroyed(): done in %[nano]s", System.nanoTime() - start ); } }
false
false
null
null
diff --git a/src/com/android/videoeditor/VideoEditorActivity.java b/src/com/android/videoeditor/VideoEditorActivity.java index f728bcc..2fff2bb 100755 --- a/src/com/android/videoeditor/VideoEditorActivity.java +++ b/src/com/android/videoeditor/VideoEditorActivity.java @@ -1,2113 +1,2114 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.videoeditor; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Rect; import android.graphics.Bitmap.Config; import android.media.videoeditor.MediaItem; import android.media.videoeditor.MediaProperties; import android.media.videoeditor.VideoEditor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.PowerManager; import android.provider.MediaStore; import android.text.InputType; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.videoeditor.service.ApiService; import com.android.videoeditor.service.MovieMediaItem; import com.android.videoeditor.service.VideoEditorProject; import com.android.videoeditor.util.FileUtils; import com.android.videoeditor.util.MediaItemUtils; import com.android.videoeditor.util.StringUtils; import com.android.videoeditor.widgets.AudioTrackLinearLayout; import com.android.videoeditor.widgets.MediaLinearLayout; import com.android.videoeditor.widgets.MediaLinearLayoutListener; import com.android.videoeditor.widgets.OverlayLinearLayout; import com.android.videoeditor.widgets.PlayheadView; import com.android.videoeditor.widgets.PreviewSurfaceView; import com.android.videoeditor.widgets.ScrollViewListener; import com.android.videoeditor.widgets.TimelineHorizontalScrollView; import com.android.videoeditor.widgets.TimelineRelativeLayout; import com.android.videoeditor.widgets.ZoomControl; /** * Main activity of the video editor. It handles video editing of * a project. */ public class VideoEditorActivity extends VideoEditorBaseActivity implements SurfaceHolder.Callback { private static final String TAG = "VideoEditorActivity"; // State keys private static final String STATE_INSERT_AFTER_MEDIA_ITEM_ID = "insert_after_media_item_id"; private static final String STATE_PLAYING = "playing"; private static final String STATE_CAPTURE_URI = "capture_uri"; // Dialog ids private static final int DIALOG_DELETE_PROJECT_ID = 1; private static final int DIALOG_EDIT_PROJECT_NAME_ID = 2; private static final int DIALOG_CHOOSE_ASPECT_RATIO_ID = 3; private static final int DIALOG_EXPORT_OPTIONS_ID = 4; public static final int DIALOG_REMOVE_MEDIA_ITEM_ID = 10; public static final int DIALOG_REMOVE_TRANSITION_ID = 11; public static final int DIALOG_CHANGE_RENDERING_MODE_ID = 12; public static final int DIALOG_REMOVE_OVERLAY_ID = 13; public static final int DIALOG_REMOVE_EFFECT_ID = 14; public static final int DIALOG_REMOVE_AUDIO_TRACK_ID = 15; // Dialog parameters private static final String PARAM_ASPECT_RATIOS_LIST = "aspect_ratios"; private static final String PARAM_CURRENT_ASPECT_RATIO_INDEX = "current_aspect_ratio"; // Request codes private static final int REQUEST_CODE_IMPORT_VIDEO = 1; private static final int REQUEST_CODE_IMPORT_IMAGE = 2; private static final int REQUEST_CODE_IMPORT_MUSIC = 3; private static final int REQUEST_CODE_CAPTURE_VIDEO = 4; private static final int REQUEST_CODE_CAPTURE_IMAGE = 5; public static final int REQUEST_CODE_EDIT_TRANSITION = 10; public static final int REQUEST_CODE_PICK_TRANSITION = 11; public static final int REQUEST_CODE_PICK_OVERLAY = 12; public static final int REQUEST_CODE_KEN_BURNS = 13; // The maximum zoom level private static final int MAX_ZOOM_LEVEL = 120; private static final int ZOOM_STEP = 2; // Threshold in width dip for showing title in action bar. private static final int SHOW_TITLE_THRESHOLD_WIDTH_DIP = 1000; private final TimelineRelativeLayout.LayoutCallback mLayoutCallback = new TimelineRelativeLayout.LayoutCallback() { @Override public void onLayoutComplete() { // Scroll the timeline such that the specified position // is in the center of the screen. mTimelineScroller.appScrollTo(timeToDimension(mProject.getPlayheadPos()), false); } }; // Instance variables private PreviewSurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private ImageView mOverlayView; private PreviewThread mPreviewThread; private View mEditorProjectView; private View mEditorEmptyView; private TimelineHorizontalScrollView mTimelineScroller; private TimelineRelativeLayout mTimelineLayout; private OverlayLinearLayout mOverlayLayout; private AudioTrackLinearLayout mAudioTrackLayout; private MediaLinearLayout mMediaLayout; private PlayheadView mPlayheadView; private TextView mTimeView; private ImageButton mPreviewPlayButton; private ImageButton mPreviewRewindButton, mPreviewNextButton, mPreviewPrevButton; private int mActivityWidth; private String mInsertMediaItemAfterMediaItemId; private long mCurrentPlayheadPosMs; private ProgressDialog mExportProgressDialog; private ZoomControl mZoomControl; private PowerManager.WakeLock mCpuWakeLock; // Variables used in onActivityResult private Uri mAddMediaItemVideoUri; private Uri mAddMediaItemImageUri; private Uri mAddAudioTrackUri; private String mAddTransitionAfterMediaId; private int mAddTransitionType; private long mAddTransitionDurationMs; private String mEditTransitionAfterMediaId, mEditTransitionId; private int mEditTransitionType; private long mEditTransitionDurationMs; private String mAddOverlayMediaItemId; private Bundle mAddOverlayUserAttributes; private String mEditOverlayMediaItemId; private String mEditOverlayId; private Bundle mEditOverlayUserAttributes; private String mAddEffectMediaItemId; private int mAddEffectType; private Rect mAddKenBurnsStartRect; private Rect mAddKenBurnsEndRect; private boolean mRestartPreview; private Uri mCaptureMediaUri; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar actionBar = getActionBar(); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); // Only show title on large screens (width >= 1000 dip). int widthDip = (int) (displayMetrics.widthPixels / displayMetrics.scaledDensity); if (widthDip >= SHOW_TITLE_THRESHOLD_WIDTH_DIP) { actionBar.setDisplayOptions(actionBar.getDisplayOptions() | ActionBar.DISPLAY_SHOW_TITLE); actionBar.setTitle(R.string.full_app_name); } // Prepare the surface holder mSurfaceView = (PreviewSurfaceView) findViewById(R.id.video_view); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mOverlayView = (ImageView)findViewById(R.id.overlay_layer); mEditorProjectView = findViewById(R.id.editor_project_view); mEditorEmptyView = findViewById(R.id.empty_project_view); mTimelineScroller = (TimelineHorizontalScrollView)findViewById(R.id.timeline_scroller); mTimelineLayout = (TimelineRelativeLayout)findViewById(R.id.timeline); mMediaLayout = (MediaLinearLayout)findViewById(R.id.timeline_media); mOverlayLayout = (OverlayLinearLayout)findViewById(R.id.timeline_overlays); mAudioTrackLayout = (AudioTrackLinearLayout)findViewById(R.id.timeline_audio_tracks); mPlayheadView = (PlayheadView)findViewById(R.id.timeline_playhead); mPreviewPlayButton = (ImageButton)findViewById(R.id.editor_play); mPreviewRewindButton = (ImageButton)findViewById(R.id.editor_rewind); mPreviewNextButton = (ImageButton)findViewById(R.id.editor_next); mPreviewPrevButton = (ImageButton)findViewById(R.id.editor_prev); mTimeView = (TextView)findViewById(R.id.editor_time); actionBar.setDisplayHomeAsUpEnabled(true); mMediaLayout.setListener(new MediaLinearLayoutListener() { @Override public void onRequestScrollBy(int scrollBy, boolean smooth) { mTimelineScroller.appScrollBy(scrollBy, smooth); } @Override public void onRequestMovePlayhead(long scrollToTime, boolean smooth) { movePlayhead(scrollToTime); } @Override public void onAddMediaItem(String afterMediaItemId) { mInsertMediaItemAfterMediaItemId = afterMediaItemId; final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); intent.setType("video/*"); startActivityForResult(intent, REQUEST_CODE_IMPORT_VIDEO); } @Override public void onTrimMediaItemBegin(MovieMediaItem mediaItem) { onProjectEditStateChange(true); } @Override public void onTrimMediaItem(MovieMediaItem mediaItem, long timeMs) { updateTimelineDuration(); if (mProject != null && isPreviewPlaying()) { if (mediaItem.isVideoClip()) { if (timeMs >= 0) { mPreviewThread.renderMediaItemFrame(mediaItem, timeMs); } } else { mPreviewThread.previewFrame(mProject, mProject.getMediaItemBeginTime(mediaItem.getId()) + timeMs, mProject.getMediaItemCount() == 0); } } } @Override public void onTrimMediaItemEnd(MovieMediaItem mediaItem, long timeMs) { onProjectEditStateChange(false); // We need to repaint the timeline layout to clear the old // playhead position (the one drawn during trimming). mTimelineLayout.invalidate(); showPreviewFrame(); } }); mAudioTrackLayout.setListener(new AudioTrackLinearLayout.AudioTracksLayoutListener() { @Override public void onAddAudioTrack() { final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("audio/*"); startActivityForResult(intent, REQUEST_CODE_IMPORT_MUSIC); } }); mTimelineScroller.addScrollListener(new ScrollViewListener() { // Instance variables private int mActiveWidth; private long mDurationMs; private int mLastScrollX; @Override public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) { if (!appScroll && mProject != null) { mActiveWidth = mMediaLayout.getWidth() - mActivityWidth; mDurationMs = mProject.computeDuration(); } else { mActiveWidth = 0; } mLastScrollX = scrollX; } @Override public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) { // We check if the project is valid since the project may // close while scrolling if (!appScroll && mActiveWidth > 0 && mProject != null) { final int deltaScrollX = Math.abs(mLastScrollX - scrollX); if (deltaScrollX < 100) { mLastScrollX = scrollX; // When scrolling at high speed do not display the // preview frame final long timeMs = (scrollX * mDurationMs) / mActiveWidth; if (setPlayhead(timeMs < 0 ? 0 : timeMs)) { showPreviewFrame(); } } } } @Override public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) { // We check if the project is valid since the project may // close while scrolling if (!appScroll && mActiveWidth > 0 && mProject != null && scrollX != mLastScrollX) { final long timeMs = (scrollX * mDurationMs) / mActiveWidth; if (setPlayhead(timeMs < 0 ? 0 : timeMs)) { showPreviewFrame(); } } } }); mTimelineScroller.setScaleListener(new ScaleGestureDetector.SimpleOnScaleGestureListener() { // Guard against this many scale events in the opposite direction private static final int SCALE_TOLERANCE = 3; private int mLastScaleFactorSign; private float mLastScaleFactor; @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mLastScaleFactorSign = 0; return true; } @Override public boolean onScale(ScaleGestureDetector detector) { if (mProject == null) { return false; } final float scaleFactor = detector.getScaleFactor(); final float deltaScaleFactor = scaleFactor - mLastScaleFactor; if (deltaScaleFactor > 0.01f || deltaScaleFactor < -0.01f) { if (scaleFactor < 1.0f) { if (mLastScaleFactorSign <= 0) { zoomTimeline(mProject.getZoomLevel() - ZOOM_STEP, true); } if (mLastScaleFactorSign > -SCALE_TOLERANCE) { mLastScaleFactorSign--; } } else if (scaleFactor > 1.0f) { if (mLastScaleFactorSign >= 0) { zoomTimeline(mProject.getZoomLevel() + ZOOM_STEP, true); } if (mLastScaleFactorSign < SCALE_TOLERANCE) { mLastScaleFactorSign++; } } } mLastScaleFactor = scaleFactor; return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { } }); if (savedInstanceState != null) { mInsertMediaItemAfterMediaItemId = savedInstanceState.getString( STATE_INSERT_AFTER_MEDIA_ITEM_ID); mRestartPreview = savedInstanceState.getBoolean(STATE_PLAYING); mCaptureMediaUri = savedInstanceState.getParcelable(STATE_CAPTURE_URI); } else { mRestartPreview = false; } // Compute the activity width final Display display = getWindowManager().getDefaultDisplay(); mActivityWidth = display.getWidth(); mSurfaceView.setGestureListener(new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (isPreviewPlaying()) { return false; } mTimelineScroller.fling(-(int)velocityX); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (isPreviewPlaying()) { return false; } mTimelineScroller.scrollBy((int)distanceX, 0); return true; } })); mZoomControl = ((ZoomControl)findViewById(R.id.editor_zoom)); mZoomControl.setMax(MAX_ZOOM_LEVEL); mZoomControl.setOnZoomChangeListener(new ZoomControl.OnZoomChangeListener() { @Override public void onProgressChanged(int progress, boolean fromUser) { if (mProject != null) { zoomTimeline(progress, false); } } }); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mCpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Video Editor Activity CPU Wake Lock"); } @Override public void onPause() { super.onPause(); // Dismiss the export progress dialog. If the export will still be pending // when we return to this activity, we will display this dialog again. if (mExportProgressDialog != null) { mExportProgressDialog.dismiss(); mExportProgressDialog = null; } } @Override public void onResume() { super.onResume(); if (mProject != null) { mMediaLayout.onResume(); mAudioTrackLayout.onResume(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_INSERT_AFTER_MEDIA_ITEM_ID, mInsertMediaItemAfterMediaItemId); outState.putBoolean(STATE_PLAYING, isPreviewPlaying()); outState.putParcelable(STATE_CAPTURE_URI, mCaptureMediaUri); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { final boolean haveProject = (mProject != null); final boolean haveMediaItems = haveProject && mProject.getMediaItemCount() > 0; menu.findItem(R.id.menu_item_capture_video).setVisible(haveProject); menu.findItem(R.id.menu_item_capture_image).setVisible(haveProject); menu.findItem(R.id.menu_item_import_video).setVisible(haveProject); menu.findItem(R.id.menu_item_import_image).setVisible(haveProject); menu.findItem(R.id.menu_item_import_audio).setVisible(haveProject && mProject.getAudioTracks().size() == 0 && haveMediaItems); menu.findItem(R.id.menu_item_change_aspect_ratio).setVisible(haveProject && mProject.hasMultipleAspectRatios()); menu.findItem(R.id.menu_item_edit_project_name).setVisible(haveProject); // Check if there is an operation pending or preview is on. boolean enableMenu = haveProject; if (enableMenu && mPreviewThread != null) { // Preview is in progress enableMenu = mPreviewThread.isStopped(); if (enableMenu && mProjectPath != null) { enableMenu = !ApiService.isProjectBeingEdited(mProjectPath); } } menu.findItem(R.id.menu_item_export_movie).setVisible(enableMenu && haveMediaItems); menu.findItem(R.id.menu_item_delete_project).setVisible(enableMenu); menu.findItem(R.id.menu_item_play_exported_movie).setVisible(enableMenu && mProject.getExportedMovieUri() != null); menu.findItem(R.id.menu_item_share_movie).setVisible(enableMenu && mProject.getExportedMovieUri() != null); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { // Returns to project picker if user clicks on the app icon in the action bar. final Intent intent = new Intent(this, ProjectsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); return true; } case R.id.menu_item_capture_video: { mInsertMediaItemAfterMediaItemId = mProject.getLastMediaItemId(); // Create parameters for Intent with filename final ContentValues values = new ContentValues(); mCaptureMediaUri = getContentResolver().insert( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values); final Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mCaptureMediaUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, REQUEST_CODE_CAPTURE_VIDEO); return true; } case R.id.menu_item_capture_image: { mInsertMediaItemAfterMediaItemId = mProject.getLastMediaItemId(); // Create parameters for Intent with filename final ContentValues values = new ContentValues(); mCaptureMediaUri = getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mCaptureMediaUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE); return true; } case R.id.menu_item_import_video: { mInsertMediaItemAfterMediaItemId = mProject.getLastMediaItemId(); final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("video/*"); intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); startActivityForResult(intent, REQUEST_CODE_IMPORT_VIDEO); return true; } case R.id.menu_item_import_image: { mInsertMediaItemAfterMediaItemId = mProject.getLastMediaItemId(); final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); startActivityForResult(intent, REQUEST_CODE_IMPORT_IMAGE); return true; } case R.id.menu_item_import_audio: { final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("audio/*"); startActivityForResult(intent, REQUEST_CODE_IMPORT_MUSIC); return true; } case R.id.menu_item_change_aspect_ratio: { final ArrayList<Integer> aspectRatiosList = mProject.getUniqueAspectRatiosList(); final int size = aspectRatiosList.size(); if (size > 1) { final Bundle bundle = new Bundle(); bundle.putIntegerArrayList(PARAM_ASPECT_RATIOS_LIST, aspectRatiosList); // Get the current aspect ratio index final int currentAspectRatio = mProject.getAspectRatio(); int currentAspectRatioIndex = 0; for (int i = 0; i < size; i++) { final int aspectRatio = aspectRatiosList.get(i); if (aspectRatio == currentAspectRatio) { currentAspectRatioIndex = i; break; } } bundle.putInt(PARAM_CURRENT_ASPECT_RATIO_INDEX, currentAspectRatioIndex); showDialog(DIALOG_CHOOSE_ASPECT_RATIO_ID, bundle); } return true; } case R.id.menu_item_edit_project_name: { showDialog(DIALOG_EDIT_PROJECT_NAME_ID); return true; } case R.id.menu_item_delete_project: { // Confirm project delete showDialog(DIALOG_DELETE_PROJECT_ID); return true; } case R.id.menu_item_export_movie: { // Present the user with a dialog to choose export options showDialog(DIALOG_EXPORT_OPTIONS_ID); return true; } case R.id.menu_item_play_exported_movie: { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(mProject.getExportedMovieUri(), "video/*"); intent.putExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION, false); startActivity(intent); return true; } case R.id.menu_item_share_movie: { final Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, mProject.getExportedMovieUri()); intent.setType("video/*"); startActivity(intent); return true; } default: { return false; } } } @Override public Dialog onCreateDialog(int id, final Bundle bundle) { switch (id) { case DIALOG_CHOOSE_ASPECT_RATIO_ID: { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.editor_change_aspect_ratio)); final ArrayList<Integer> aspectRatios = bundle.getIntegerArrayList(PARAM_ASPECT_RATIOS_LIST); final int count = aspectRatios.size(); final CharSequence[] aspectRatioStrings = new CharSequence[count]; for (int i = 0; i < count; i++) { int aspectRatio = aspectRatios.get(i); switch (aspectRatio) { case MediaProperties.ASPECT_RATIO_11_9: { aspectRatioStrings[i] = getString(R.string.aspect_ratio_11_9); break; } case MediaProperties.ASPECT_RATIO_16_9: { aspectRatioStrings[i] = getString(R.string.aspect_ratio_16_9); break; } case MediaProperties.ASPECT_RATIO_3_2: { aspectRatioStrings[i] = getString(R.string.aspect_ratio_3_2); break; } case MediaProperties.ASPECT_RATIO_4_3: { aspectRatioStrings[i] = getString(R.string.aspect_ratio_4_3); break; } case MediaProperties.ASPECT_RATIO_5_3: { aspectRatioStrings[i] = getString(R.string.aspect_ratio_5_3); break; } default: { break; } } } builder.setSingleChoiceItems(aspectRatioStrings, bundle.getInt(PARAM_CURRENT_ASPECT_RATIO_INDEX), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int aspectRatio = aspectRatios.get(which); ApiService.setAspectRatio(VideoEditorActivity.this, mProjectPath, aspectRatio); removeDialog(DIALOG_CHOOSE_ASPECT_RATIO_ID); } }); builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_CHOOSE_ASPECT_RATIO_ID); } }); return builder.create(); } case DIALOG_DELETE_PROJECT_ID: { return AlertDialogs.createAlert(this, getString(R.string.editor_delete_project), 0, getString(R.string.editor_delete_project_question), getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ApiService.deleteProject(VideoEditorActivity.this, mProjectPath); mProjectPath = null; mProject = null; enterDisabledState(R.string.editor_no_project); removeDialog(DIALOG_DELETE_PROJECT_ID); finish(); } }, getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(DIALOG_DELETE_PROJECT_ID); } }, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_DELETE_PROJECT_ID); } }, true); } case DIALOG_DELETE_BAD_PROJECT_ID: { return AlertDialogs.createAlert(this, getString(R.string.editor_delete_project), 0, getString(R.string.editor_load_error), getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ApiService.deleteProject(VideoEditorActivity.this, bundle.getString(PARAM_PROJECT_PATH)); removeDialog(DIALOG_DELETE_BAD_PROJECT_ID); finish(); } }, getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(DIALOG_DELETE_BAD_PROJECT_ID); } }, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_DELETE_BAD_PROJECT_ID); } }, true); } case DIALOG_EDIT_PROJECT_NAME_ID: { if (mProject == null) { return null; } return AlertDialogs.createEditDialog(this, getString(R.string.editor_edit_project_name), mProject.getName(), getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final TextView tv = (TextView)((AlertDialog)dialog).findViewById(R.id.text_1); mProject.setProjectName(tv.getText().toString()); getActionBar().setTitle(tv.getText()); removeDialog(DIALOG_EDIT_PROJECT_NAME_ID); } }, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(DIALOG_EDIT_PROJECT_NAME_ID); } }, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_EDIT_PROJECT_NAME_ID); } }, InputType.TYPE_NULL, 32, null); } case DIALOG_EXPORT_OPTIONS_ID: { if (mProject == null) { return null; } return ExportOptionsDialog.create(this, new ExportOptionsDialog.ExportOptionsListener() { @Override public void onExportOptions(int movieHeight, int movieBitrate) { mPendingExportFilename = FileUtils.createMovieName( MediaProperties.FILE_MP4); ApiService.exportVideoEditor(VideoEditorActivity.this, mProjectPath, mPendingExportFilename, movieHeight, movieBitrate); removeDialog(DIALOG_EXPORT_OPTIONS_ID); showExportProgress(); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeDialog(DIALOG_EXPORT_OPTIONS_ID); } }, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_EXPORT_OPTIONS_ID); } }, mProject.getAspectRatio()); } case DIALOG_REMOVE_MEDIA_ITEM_ID: { return mMediaLayout.onCreateDialog(id, bundle); } case DIALOG_CHANGE_RENDERING_MODE_ID: { return mMediaLayout.onCreateDialog(id, bundle); } case DIALOG_REMOVE_TRANSITION_ID: { return mMediaLayout.onCreateDialog(id, bundle); } case DIALOG_REMOVE_OVERLAY_ID: { return mOverlayLayout.onCreateDialog(id, bundle); } case DIALOG_REMOVE_EFFECT_ID: { return mMediaLayout.onCreateDialog(id, bundle); } case DIALOG_REMOVE_AUDIO_TRACK_ID: { return mAudioTrackLayout.onCreateDialog(id, bundle); } default: { return null; } } } /** * Called when user clicks on the button in the control panel. * @param target one of the "play", "rewind", "next", * and "prev" buttons in the control panel */ public void onClickHandler(View target) { final long playheadPosMs = mProject.getPlayheadPos(); switch (target.getId()) { case R.id.editor_play: { if (mProject != null && mPreviewThread != null) { if (mPreviewThread.isPlaying()) { mPreviewThread.stopPreviewPlayback(); } else if (mProject.getMediaItemCount() > 0) { mPreviewThread.startPreviewPlayback(mProject, playheadPosMs); } } break; } case R.id.editor_rewind: { if (mProject != null && mPreviewThread != null) { if (mPreviewThread.isPlaying()) { mPreviewThread.stopPreviewPlayback(); movePlayhead(0); mPreviewThread.startPreviewPlayback(mProject, 0); } else { movePlayhead(0); showPreviewFrame(); } } break; } case R.id.editor_next: { if (mProject != null && mPreviewThread != null) { final boolean restartPreview; if (mPreviewThread.isPlaying()) { mPreviewThread.stopPreviewPlayback(); restartPreview = true; } else { restartPreview = false; } final MovieMediaItem mediaItem = mProject.getNextMediaItem(playheadPosMs); if (mediaItem != null) { movePlayhead(mProject.getMediaItemBeginTime(mediaItem.getId())); if (restartPreview) { mPreviewThread.startPreviewPlayback(mProject, mProject.getPlayheadPos()); } else { showPreviewFrame(); } } else { // Move to the end of the timeline movePlayhead(mProject.computeDuration()); showPreviewFrame(); } } break; } case R.id.editor_prev: { if (mProject != null && mPreviewThread != null) { final boolean restartPreview; if (mPreviewThread.isPlaying()) { mPreviewThread.stopPreviewPlayback(); restartPreview = true; } else { restartPreview = false; } final MovieMediaItem mediaItem = mProject.getPreviousMediaItem(playheadPosMs); if (mediaItem != null) { movePlayhead(mProject.getMediaItemBeginTime(mediaItem.getId())); } else { // Move to the beginning of the timeline movePlayhead(0); } if (restartPreview) { mPreviewThread.startPreviewPlayback(mProject, mProject.getPlayheadPos()); } else { showPreviewFrame(); } } break; } default: { break; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent extras) { super.onActivityResult(requestCode, resultCode, extras); if (resultCode == RESULT_CANCELED) { switch (requestCode) { case REQUEST_CODE_CAPTURE_VIDEO: case REQUEST_CODE_CAPTURE_IMAGE: { if (mCaptureMediaUri != null) { getContentResolver().delete(mCaptureMediaUri, null, null); mCaptureMediaUri = null; } break; } default: { break; } } return; } switch (requestCode) { case REQUEST_CODE_CAPTURE_VIDEO: { if (mProject != null) { ApiService.addMediaItemVideoUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mCaptureMediaUri, MediaItem.RENDERING_MODE_BLACK_BORDER, mProject.getTheme()); mInsertMediaItemAfterMediaItemId = null; } else { // Add this video after the project loads mAddMediaItemVideoUri = mCaptureMediaUri; } mCaptureMediaUri = null; break; } case REQUEST_CODE_CAPTURE_IMAGE: { if (mProject != null) { ApiService.addMediaItemImageUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mCaptureMediaUri, MediaItem.RENDERING_MODE_BLACK_BORDER, MediaItemUtils.getDefaultImageDuration(), mProject.getTheme()); mInsertMediaItemAfterMediaItemId = null; } else { // Add this image after the project loads mAddMediaItemImageUri = mCaptureMediaUri; } mCaptureMediaUri = null; break; } case REQUEST_CODE_IMPORT_VIDEO: { final Uri mediaUri = extras.getData(); if (mProject != null) { if ("media".equals(mediaUri.getAuthority())) { ApiService.addMediaItemVideoUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mediaUri, MediaItem.RENDERING_MODE_BLACK_BORDER, mProject.getTheme()); } else { // Notify the user that this item needs to be downloaded. Toast.makeText(this, getString(R.string.editor_video_load), Toast.LENGTH_LONG).show(); // When the download is complete insert it into the project. ApiService.loadMediaItem(this, mProjectPath, mediaUri, "video/*"); } mInsertMediaItemAfterMediaItemId = null; } else { // Add this video after the project loads mAddMediaItemVideoUri = mediaUri; } break; } case REQUEST_CODE_IMPORT_IMAGE: { final Uri mediaUri = extras.getData(); if (mProject != null) { if ("media".equals(mediaUri.getAuthority())) { ApiService.addMediaItemImageUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mediaUri, MediaItem.RENDERING_MODE_BLACK_BORDER, MediaItemUtils.getDefaultImageDuration(), mProject.getTheme()); } else { // Notify the user that this item needs to be downloaded. Toast.makeText(this, getString(R.string.editor_image_load), Toast.LENGTH_LONG).show(); // When the download is complete insert it into the project. ApiService.loadMediaItem(this, mProjectPath, mediaUri, "image/*"); } mInsertMediaItemAfterMediaItemId = null; } else { // Add this image after the project loads mAddMediaItemImageUri = mediaUri; } break; } case REQUEST_CODE_IMPORT_MUSIC: { final Uri data = extras.getData(); if (mProject != null) { ApiService.addAudioTrack(this, mProjectPath, ApiService.generateId(), data, true); } else { mAddAudioTrackUri = data; } break; } case REQUEST_CODE_EDIT_TRANSITION: { final int type = extras.getIntExtra(TransitionsActivity.PARAM_TRANSITION_TYPE, -1); final String afterMediaId = extras.getStringExtra( TransitionsActivity.PARAM_AFTER_MEDIA_ITEM_ID); final String transitionId = extras.getStringExtra( TransitionsActivity.PARAM_TRANSITION_ID); final long transitionDurationMs = extras.getLongExtra( TransitionsActivity.PARAM_TRANSITION_DURATION, 500); if (mProject != null) { mMediaLayout.editTransition(afterMediaId, transitionId, type, transitionDurationMs); } else { // Add this transition after you load the project mEditTransitionAfterMediaId = afterMediaId; mEditTransitionId = transitionId; mEditTransitionType = type; mEditTransitionDurationMs = transitionDurationMs; } break; } case REQUEST_CODE_PICK_TRANSITION: { final int type = extras.getIntExtra(TransitionsActivity.PARAM_TRANSITION_TYPE, -1); final String afterMediaId = extras.getStringExtra( TransitionsActivity.PARAM_AFTER_MEDIA_ITEM_ID); final long transitionDurationMs = extras.getLongExtra( TransitionsActivity.PARAM_TRANSITION_DURATION, 500); if (mProject != null) { mMediaLayout.addTransition(afterMediaId, type, transitionDurationMs); } else { // Add this transition after you load the project mAddTransitionAfterMediaId = afterMediaId; mAddTransitionType = type; mAddTransitionDurationMs = transitionDurationMs; } break; } case REQUEST_CODE_PICK_OVERLAY: { // If there is no overlay id, it means we are adding a new overlay. // Otherwise we generate a unique new id for the new overlay. final String mediaItemId = extras.getStringExtra(OverlayTitleEditor.PARAM_MEDIA_ITEM_ID); final String overlayId = extras.getStringExtra(OverlayTitleEditor.PARAM_OVERLAY_ID); final Bundle bundle = extras.getBundleExtra(OverlayTitleEditor.PARAM_OVERLAY_ATTRIBUTES); if (mProject != null) { final MovieMediaItem mediaItem = mProject.getMediaItem(mediaItemId); if (mediaItem != null) { if (overlayId == null) { ApiService.addOverlay(this, mProject.getPath(), mediaItemId, ApiService.generateId(), bundle, mediaItem.getAppBoundaryBeginTime(), OverlayLinearLayout.DEFAULT_TITLE_DURATION); } else { ApiService.setOverlayUserAttributes(this, mProject.getPath(), mediaItemId, overlayId, bundle); } mOverlayLayout.invalidateCAB(); } } else { // Add this overlay after you load the project. mAddOverlayMediaItemId = mediaItemId; mAddOverlayUserAttributes = bundle; mEditOverlayId = overlayId; } break; } case REQUEST_CODE_KEN_BURNS: { final String mediaItemId = extras.getStringExtra( KenBurnsActivity.PARAM_MEDIA_ITEM_ID); final Rect startRect = extras.getParcelableExtra( KenBurnsActivity.PARAM_START_RECT); final Rect endRect = extras.getParcelableExtra( KenBurnsActivity.PARAM_END_RECT); if (mProject != null) { mMediaLayout.addEffect(EffectType.EFFECT_KEN_BURNS, mediaItemId, startRect, endRect); mMediaLayout.invalidateActionBar(); } else { // Add this effect after you load the project. mAddEffectMediaItemId = mediaItemId; mAddEffectType = EffectType.EFFECT_KEN_BURNS; mAddKenBurnsStartRect = startRect; mAddKenBurnsEndRect = endRect; } break; } default: { break; } } } @Override public void surfaceCreated(SurfaceHolder holder) { logd("surfaceCreated"); mPreviewThread = new PreviewThread(mSurfaceHolder); restartPreview(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { logd("surfaceChanged: " + width + "x" + height); if (mPreviewThread != null) { mPreviewThread.onSurfaceChanged(width, height); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { logd("surfaceDestroyed"); // Stop the preview playback if pending and quit the preview thread if (mPreviewThread != null) { mPreviewThread.stopPreviewPlayback(); mPreviewThread.quit(); mPreviewThread = null; } } @Override protected void enterTransitionalState(int statusStringId) { mEditorProjectView.setVisibility(View.GONE); mEditorEmptyView.setVisibility(View.VISIBLE); ((TextView)findViewById(R.id.empty_project_text)).setText(statusStringId); findViewById(R.id.empty_project_progress).setVisibility(View.VISIBLE); } @Override protected void enterDisabledState(int statusStringId) { mEditorProjectView.setVisibility(View.GONE); mEditorEmptyView.setVisibility(View.VISIBLE); getActionBar().setTitle(R.string.full_app_name); ((TextView)findViewById(R.id.empty_project_text)).setText(statusStringId); findViewById(R.id.empty_project_progress).setVisibility(View.GONE); } @Override protected void enterReadyState() { mEditorProjectView.setVisibility(View.VISIBLE); mEditorEmptyView.setVisibility(View.GONE); } @Override protected boolean showPreviewFrame() { if (mPreviewThread == null) { // The surface is not ready yet. return false; } // Regenerate the preview frame if (mProject != null && !mPreviewThread.isPlaying() && mPendingExportFilename == null) { // Display the preview frame mPreviewThread.previewFrame(mProject, mProject.getPlayheadPos(), mProject.getMediaItemCount() == 0); } return true; } @Override protected void updateTimelineDuration() { if (mProject == null) { return; } final long durationMs = mProject.computeDuration(); // Resize the timeline according to the new timeline duration final int zoomWidth = mActivityWidth + timeToDimension(durationMs); final int childrenCount = mTimelineLayout.getChildCount(); for (int i = 0; i < childrenCount; i++) { final View child = mTimelineLayout.getChildAt(i); final ViewGroup.LayoutParams lp = child.getLayoutParams(); lp.width = zoomWidth; child.setLayoutParams(lp); } mTimelineLayout.requestLayout(mLayoutCallback); // Since the duration has changed make sure that the playhead // position is valid. if (mProject.getPlayheadPos() > durationMs) { movePlayhead(durationMs); } mAudioTrackLayout.updateTimelineDuration(); } /** * Convert the time to dimension * At zoom level 1: one activity width = 1200 seconds * At zoom level 2: one activity width = 600 seconds * ... * At zoom level 100: one activity width = 12 seconds * * At zoom level 1000: one activity width = 1.2 seconds * * @param durationMs The time * * @return The dimension */ private int timeToDimension(long durationMs) { return (int)((mProject.getZoomLevel() * mActivityWidth * durationMs) / 1200000); } /** * Zoom the timeline * * @param level The zoom level * @param updateControl true to set the control position to match the * zoom level */ private int zoomTimeline(int level, boolean updateControl) { if (level < 1 || level > MAX_ZOOM_LEVEL) { return mProject.getZoomLevel(); } mProject.setZoomLevel(level); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "zoomTimeline level: " + level + " -> " + timeToDimension(1000) + " pix/s"); } updateTimelineDuration(); if (updateControl) { mZoomControl.setProgress(level); } return level; } @Override protected void movePlayhead(long timeMs) { if (mProject == null) { return; } if (setPlayhead(timeMs)) { // Scroll the timeline such that the specified position // is in the center of the screen mTimelineScroller.appScrollTo(timeToDimension(timeMs), true); } } /** * Set the playhead at the specified time position * * @param timeMs The time position * * @return true if the playhead was set at the specified time position */ private boolean setPlayhead(long timeMs) { // Check if the position would change if (mCurrentPlayheadPosMs == timeMs) { return false; } // Check if the time is valid. Note that invalid values are common due // to overscrolling the timeline if (timeMs < 0) { return false; } else if (timeMs > mProject.computeDuration()) { return false; } mCurrentPlayheadPosMs = timeMs; mTimeView.setText(StringUtils.getTimestampAsString(this, timeMs)); mProject.setPlayheadPos(timeMs); return true; } @Override protected void setAspectRatio(final int aspectRatio) { final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)mSurfaceView.getLayoutParams(); switch (aspectRatio) { case MediaProperties.ASPECT_RATIO_5_3: { lp.width = (lp.height * 5) / 3; break; } case MediaProperties.ASPECT_RATIO_4_3: { lp.width = (lp.height * 4) / 3; break; } case MediaProperties.ASPECT_RATIO_3_2: { lp.width = (lp.height * 3) / 2; break; } case MediaProperties.ASPECT_RATIO_11_9: { lp.width = (lp.height * 11) / 9; break; } case MediaProperties.ASPECT_RATIO_16_9: { lp.width = (lp.height * 16) / 9; break; } default: { break; } } logd("setAspectRatio: " + aspectRatio + ", size: " + lp.width + "x" + lp.height); mSurfaceView.setLayoutParams(lp); mOverlayView.setLayoutParams(lp); } @Override protected MediaLinearLayout getMediaLayout() { return mMediaLayout; } @Override protected OverlayLinearLayout getOverlayLayout() { return mOverlayLayout; } @Override protected AudioTrackLinearLayout getAudioTrackLayout() { return mAudioTrackLayout; } @Override protected void onExportProgress(int progress) { if (mExportProgressDialog != null) { mExportProgressDialog.setProgress(progress); } } @Override protected void onExportComplete() { if (mExportProgressDialog != null) { mExportProgressDialog.dismiss(); mExportProgressDialog = null; } } @Override protected void onProjectEditStateChange(boolean projectEdited) { logd("onProjectEditStateChange: " + projectEdited); mPreviewPlayButton.setAlpha(projectEdited ? 100 : 255); mPreviewPlayButton.setEnabled(!projectEdited); mPreviewRewindButton.setEnabled(!projectEdited); mPreviewNextButton.setEnabled(!projectEdited); mPreviewPrevButton.setEnabled(!projectEdited); mMediaLayout.invalidateActionBar(); mOverlayLayout.invalidateCAB(); + invalidateOptionsMenu(); } @Override protected void initializeFromProject(boolean updateUI) { logd("Project was clean: " + mProject.isClean()); if (updateUI || !mProject.isClean()) { getActionBar().setTitle(mProject.getName()); // Clear the media related to the previous project and // add the media for the current project. mMediaLayout.setProject(mProject); mOverlayLayout.setProject(mProject); mAudioTrackLayout.setProject(mProject); mPlayheadView.setProject(mProject); // Add the media items to the media item layout mMediaLayout.addMediaItems(mProject.getMediaItems()); // Add the media items to the overlay layout mOverlayLayout.addMediaItems(mProject.getMediaItems()); // Add the audio tracks to the audio tracks layout mAudioTrackLayout.addAudioTracks(mProject.getAudioTracks()); setAspectRatio(mProject.getAspectRatio()); } updateTimelineDuration(); zoomTimeline(mProject.getZoomLevel(), true); // Set the playhead position. We need to wait for the layout to // complete before we can scroll to the playhead position. final Handler handler = new Handler(); handler.post(new Runnable() { private final long DELAY = 100; private final int ATTEMPTS = 20; private int mAttempts = ATTEMPTS; @Override public void run() { if (mAttempts == ATTEMPTS) { // Only scroll once movePlayhead(mProject.getPlayheadPos()); } // If the surface is not yet created (showPreviewFrame() // returns false) wait for a while (DELAY * ATTEMPTS). if (showPreviewFrame() == false && mAttempts >= 0) { mAttempts--; if (mAttempts >= 0) { handler.postDelayed(this, DELAY); } } } }); if (mAddMediaItemVideoUri != null) { ApiService.addMediaItemVideoUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mAddMediaItemVideoUri, MediaItem.RENDERING_MODE_BLACK_BORDER, mProject.getTheme()); mAddMediaItemVideoUri = null; mInsertMediaItemAfterMediaItemId = null; } if (mAddMediaItemImageUri != null) { ApiService.addMediaItemImageUri(this, mProjectPath, ApiService.generateId(), mInsertMediaItemAfterMediaItemId, mAddMediaItemImageUri, MediaItem.RENDERING_MODE_BLACK_BORDER, MediaItemUtils.getDefaultImageDuration(), mProject.getTheme()); mAddMediaItemImageUri = null; mInsertMediaItemAfterMediaItemId = null; } if (mAddAudioTrackUri != null) { ApiService.addAudioTrack(this, mProject.getPath(), ApiService.generateId(), mAddAudioTrackUri, true); mAddAudioTrackUri = null; } if (mAddTransitionAfterMediaId != null) { mMediaLayout.addTransition(mAddTransitionAfterMediaId, mAddTransitionType, mAddTransitionDurationMs); mAddTransitionAfterMediaId = null; } if (mEditTransitionId != null) { mMediaLayout.editTransition(mEditTransitionAfterMediaId, mEditTransitionId, mEditTransitionType, mEditTransitionDurationMs); mEditTransitionId = null; mEditTransitionAfterMediaId = null; } if (mAddOverlayMediaItemId != null) { ApiService.addOverlay(this, mProject.getPath(), mAddOverlayMediaItemId, ApiService.generateId(), mAddOverlayUserAttributes, 0, OverlayLinearLayout.DEFAULT_TITLE_DURATION); mAddOverlayMediaItemId = null; mAddOverlayUserAttributes = null; } if (mEditOverlayMediaItemId != null) { ApiService.setOverlayUserAttributes(this, mProject.getPath(), mEditOverlayMediaItemId, mEditOverlayId, mEditOverlayUserAttributes); mEditOverlayMediaItemId = null; mEditOverlayId = null; mEditOverlayUserAttributes = null; } if (mAddEffectMediaItemId != null) { mMediaLayout.addEffect(mAddEffectType, mAddEffectMediaItemId, mAddKenBurnsStartRect, mAddKenBurnsEndRect); mAddEffectMediaItemId = null; } enterReadyState(); if (mPendingExportFilename != null) { if (ApiService.isVideoEditorExportPending(mProjectPath, mPendingExportFilename)) { // The export is still pending // Display the export project dialog showExportProgress(); } else { // The export completed while the Activity was paused mPendingExportFilename = null; } } invalidateOptionsMenu(); restartPreview(); } /** * Restart preview */ private void restartPreview() { if (mRestartPreview == false) { return; } if (mProject == null) { return; } if (mPreviewThread != null) { mRestartPreview = false; mPreviewThread.startPreviewPlayback(mProject, mProject.getPlayheadPos()); } } /** * Shows progress dialog during export operation. */ private void showExportProgress() { // Keep the CPU on throughout the export operation. mExportProgressDialog = new ProgressDialog(this) { @Override public void onStart() { super.onStart(); mCpuWakeLock.acquire(); } @Override public void onStop() { super.onStop(); mCpuWakeLock.release(); } }; mExportProgressDialog.setTitle(getString(R.string.export_dialog_export)); mExportProgressDialog.setMessage(null); mExportProgressDialog.setIndeterminate(false); // Allow cancellation with BACK button. mExportProgressDialog.setCancelable(true); mExportProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancelExport(); } }); mExportProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mExportProgressDialog.setMax(100); mExportProgressDialog.setCanceledOnTouchOutside(false); mExportProgressDialog.setButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancelExport(); } } ); mExportProgressDialog.setCanceledOnTouchOutside(false); mExportProgressDialog.show(); mExportProgressDialog.setProgressNumberFormat(""); } private void cancelExport() { ApiService.cancelExportVideoEditor(VideoEditorActivity.this, mProjectPath, mPendingExportFilename); mPendingExportFilename = null; mExportProgressDialog = null; } private boolean isPreviewPlaying() { if (mPreviewThread == null) return false; return mPreviewThread.isPlaying(); } /** * The preview thread */ private class PreviewThread extends Thread { // Preview states private final int PREVIEW_STATE_STOPPED = 0; private final int PREVIEW_STATE_STARTING = 1; private final int PREVIEW_STATE_STARTED = 2; private final int PREVIEW_STATE_STOPPING = 3; private final int OVERLAY_DATA_COUNT = 16; private final Handler mMainHandler; private final Queue<Runnable> mQueue; private final SurfaceHolder mSurfaceHolder; private final Queue<VideoEditor.OverlayData> mOverlayDataQueue; private Handler mThreadHandler; private int mPreviewState; private Bitmap mOverlayBitmap; private final Runnable mProcessQueueRunnable = new Runnable() { @Override public void run() { // Process whatever accumulated in the queue Runnable runnable; while ((runnable = mQueue.poll()) != null) { runnable.run(); } } }; /** * Constructor * * @param surfaceHolder The surface holder */ public PreviewThread(SurfaceHolder surfaceHolder) { mMainHandler = new Handler(Looper.getMainLooper()); mQueue = new LinkedBlockingQueue<Runnable>(); mSurfaceHolder = surfaceHolder; mPreviewState = PREVIEW_STATE_STOPPED; mOverlayDataQueue = new LinkedBlockingQueue<VideoEditor.OverlayData>(); for (int i = 0; i < OVERLAY_DATA_COUNT; i++) { mOverlayDataQueue.add(new VideoEditor.OverlayData()); } start(); } /** * Preview the specified frame * * @param project The video editor project * @param timeMs The frame time * @param clear true to clear the output */ public void previewFrame(final VideoEditorProject project, final long timeMs, final boolean clear) { if (mPreviewState == PREVIEW_STATE_STARTING || mPreviewState == PREVIEW_STATE_STARTED) { stopPreviewPlayback(); } logd("Preview frame at: " + timeMs + " " + clear); // We only need to see the last frame mQueue.clear(); mQueue.add(new Runnable() { @Override public void run() { if (clear) { try { project.clearSurface(mSurfaceHolder); } catch (Exception ex) { Log.w(TAG, "Surface cannot be cleared"); } mMainHandler.post(new Runnable() { @Override public void run() { if (mOverlayBitmap != null) { mOverlayBitmap.eraseColor(Color.TRANSPARENT); mOverlayView.invalidate(); } } }); } else { final VideoEditor.OverlayData overlayData; try { overlayData = mOverlayDataQueue.remove(); } catch (NoSuchElementException ex) { Log.e(TAG, "Out of OverlayData elements"); return; } try { if (project.renderPreviewFrame(mSurfaceHolder, timeMs, overlayData) < 0) { logd("Cannot render preview frame at: " + timeMs + " of " + mProject.computeDuration()); mOverlayDataQueue.add(overlayData); } else { if (overlayData.needsRendering()) { mMainHandler.post(new Runnable() { /* * {@inheritDoc} */ @Override public void run() { if (mOverlayBitmap != null) { overlayData.renderOverlay(mOverlayBitmap); mOverlayView.invalidate(); } else { overlayData.release(); } mOverlayDataQueue.add(overlayData); } }); } else { mOverlayDataQueue.add(overlayData); } } } catch (Exception ex) { logd("renderPreviewFrame failed at timeMs: " + timeMs + "\n" + ex); mOverlayDataQueue.add(overlayData); } } } }); if (mThreadHandler != null) { mThreadHandler.post(mProcessQueueRunnable); } } /** * Display the frame at the specified time position * * @param mediaItem The media item * @param timeMs The frame time */ public void renderMediaItemFrame(final MovieMediaItem mediaItem, final long timeMs) { if (mPreviewState == PREVIEW_STATE_STARTING || mPreviewState == PREVIEW_STATE_STARTED) { stopPreviewPlayback(); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Render media item frame at: " + timeMs); } // We only need to see the last frame mQueue.clear(); mQueue.add(new Runnable() { @Override public void run() { try { if (mProject.renderMediaItemFrame(mSurfaceHolder, mediaItem.getId(), timeMs) < 0) { logd("Cannot render media item frame at: " + timeMs + " of " + mediaItem.getDuration()); } } catch (Exception ex) { logd("Cannot render preview frame at: " + timeMs + "\n" + ex); } } }); if (mThreadHandler != null) { mThreadHandler.post(mProcessQueueRunnable); } } /** * Start the preview playback * * @param project The video editor project * @param fromMs Start playing from the specified position */ private void startPreviewPlayback(final VideoEditorProject project, final long fromMs) { if (mPreviewState != PREVIEW_STATE_STOPPED) { logd("Preview did not start: " + mPreviewState); return; } previewStarted(project); logd("Start preview at: " + fromMs); // Clear any pending preview frames mQueue.clear(); mQueue.add(new Runnable() { @Override public void run() { try { project.startPreview(mSurfaceHolder, fromMs, -1, false, 3, new VideoEditor.PreviewProgressListener() { @Override public void onStart(VideoEditor videoEditor) { } @Override public void onProgress(VideoEditor videoEditor, final long timeMs, final VideoEditor.OverlayData overlayData) { mMainHandler.post(new Runnable() { @Override public void run() { if (overlayData != null && overlayData.needsRendering()) { if (mOverlayBitmap != null) { overlayData.renderOverlay(mOverlayBitmap); mOverlayView.invalidate(); } else { overlayData.release(); } } if (mPreviewState == PREVIEW_STATE_STARTED || mPreviewState == PREVIEW_STATE_STOPPING) { movePlayhead(timeMs); } } }); } @Override public void onStop(VideoEditor videoEditor) { mMainHandler.post(new Runnable() { @Override public void run() { if (mPreviewState == PREVIEW_STATE_STARTED || mPreviewState == PREVIEW_STATE_STOPPING) { previewStopped(false); } } }); } }); mMainHandler.post(new Runnable() { @Override public void run() { mPreviewState = PREVIEW_STATE_STARTED; } }); } catch (Exception ex) { // This exception may occur when trying to play frames // at the end of the timeline // (e.g. when fromMs == clip duration) logd("Cannot start preview at: " + fromMs + "\n" + ex); mMainHandler.post(new Runnable() { @Override public void run() { mPreviewState = PREVIEW_STATE_STARTED; previewStopped(true); } }); } } }); if (mThreadHandler != null) { mThreadHandler.post(mProcessQueueRunnable); } } /** * The preview started. * This method is always invoked from the UI thread. * * @param project The project */ private void previewStarted(VideoEditorProject project) { // Change the button image back to a play icon mPreviewPlayButton.setImageResource(R.drawable.btn_playback_pause_selector); mTimelineScroller.enableUserScrolling(false); mMediaLayout.setPlaybackInProgress(true); mOverlayLayout.setPlaybackInProgress(true); mAudioTrackLayout.setPlaybackInProgress(true); mPreviewState = PREVIEW_STATE_STARTING; // Keep the screen on during the preview. VideoEditorActivity.this.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } /** * Stops the preview. */ private void stopPreviewPlayback() { switch (mPreviewState) { case PREVIEW_STATE_STOPPED: { logd("stopPreviewPlayback: State was PREVIEW_STATE_STOPPED"); return; } case PREVIEW_STATE_STOPPING: { logd("stopPreviewPlayback: State was PREVIEW_STATE_STOPPING"); return; } case PREVIEW_STATE_STARTING: { logd("stopPreviewPlayback: State was PREVIEW_STATE_STARTING " + "now PREVIEW_STATE_STOPPING"); mPreviewState = PREVIEW_STATE_STOPPING; // We need to wait until the preview starts mMainHandler.postDelayed(new Runnable() { @Override public void run() { if (isFinishing() || isChangingConfigurations()) { // The activity is shutting down. Force stopping now. logd("stopPreviewPlayback: Activity is shutting down"); mPreviewState = PREVIEW_STATE_STARTED; previewStopped(true); } else if (mPreviewState == PREVIEW_STATE_STARTED) { logd("stopPreviewPlayback: Now PREVIEW_STATE_STARTED"); previewStopped(false); } else if (mPreviewState == PREVIEW_STATE_STOPPING) { // Keep waiting mMainHandler.postDelayed(this, 100); logd("stopPreviewPlayback: Waiting for PREVIEW_STATE_STARTED"); } else { logd("stopPreviewPlayback: PREVIEW_STATE_STOPPED while waiting"); } } }, 50); break; } case PREVIEW_STATE_STARTED: { logd("stopPreviewPlayback: State was PREVIEW_STATE_STARTED"); // We need to stop previewStopped(false); return; } default: { throw new IllegalArgumentException("stopPreviewPlayback state: " + mPreviewState); } } } /** * The surface size has changed * * @param width The new surface width * @param height The new surface height */ private void onSurfaceChanged(int width, int height) { if (mOverlayBitmap != null) { if (mOverlayBitmap.getWidth() == width && mOverlayBitmap.getHeight() == height) { // The size has not changed return; } mOverlayView.setImageBitmap(null); mOverlayBitmap.recycle(); mOverlayBitmap = null; } // Create the overlay bitmap logd("Overlay size: " + width + " x " + height); mOverlayBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); mOverlayView.setImageBitmap(mOverlayBitmap); } /** * Preview stopped. This method is always invoked from the UI thread. * * @param error true if the preview stopped due to an error */ private void previewStopped(boolean error) { if (mProject == null) { Log.w(TAG, "previewStopped: project was deleted."); return; } if (mPreviewState != PREVIEW_STATE_STARTED) { throw new IllegalStateException("previewStopped in state: " + mPreviewState); } // Change the button image back to a play icon mPreviewPlayButton.setImageResource(R.drawable.btn_playback_play_selector); if (error == false) { // Set the playhead position at the position where the playback stopped final long stopTimeMs = mProject.stopPreview(); movePlayhead(stopTimeMs); logd("PREVIEW_STATE_STOPPED: " + stopTimeMs); } else { logd("PREVIEW_STATE_STOPPED due to error"); } mPreviewState = PREVIEW_STATE_STOPPED; // The playback has stopped mTimelineScroller.enableUserScrolling(true); mMediaLayout.setPlaybackInProgress(false); mAudioTrackLayout.setPlaybackInProgress(false); mOverlayLayout.setPlaybackInProgress(false); // Do not keep the screen on if there is no preview in progress. VideoEditorActivity.this.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } /** * @return true if preview playback is in progress */ private boolean isPlaying() { return mPreviewState == PREVIEW_STATE_STARTING || mPreviewState == PREVIEW_STATE_STARTED; } /** * @return true if the preview is stopped */ private boolean isStopped() { return mPreviewState == PREVIEW_STATE_STOPPED; } @Override public void run() { setPriority(MAX_PRIORITY); Looper.prepare(); mThreadHandler = new Handler(); // Ensure that the queued items are processed mMainHandler.post(new Runnable() { @Override public void run() { // Start processing the queue of runnables mThreadHandler.post(mProcessQueueRunnable); } }); // Run the loop Looper.loop(); } /** * Quits the thread */ public void quit() { // Release the overlay bitmap if (mOverlayBitmap != null) { mOverlayView.setImageBitmap(null); mOverlayBitmap.recycle(); mOverlayBitmap = null; } if (mThreadHandler != null) { mThreadHandler.getLooper().quit(); try { // Wait for the thread to quit. An ANR waiting to happen. mThreadHandler.getLooper().getThread().join(); } catch (InterruptedException ex) { } } mQueue.clear(); } } private static void logd(String message) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, message); } } } diff --git a/src/com/android/videoeditor/VideoEditorBaseActivity.java b/src/com/android/videoeditor/VideoEditorBaseActivity.java index a5376c2..5e9b6b8 100755 --- a/src/com/android/videoeditor/VideoEditorBaseActivity.java +++ b/src/com/android/videoeditor/VideoEditorBaseActivity.java @@ -1,978 +1,974 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.videoeditor; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.videoeditor.AudioTrack; import android.media.videoeditor.MediaItem; import android.media.videoeditor.MediaVideoItem; import android.media.videoeditor.Transition; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.android.videoeditor.service.ApiService; import com.android.videoeditor.service.ApiServiceListener; import com.android.videoeditor.service.MovieAudioTrack; import com.android.videoeditor.service.MovieEffect; import com.android.videoeditor.service.MovieMediaItem; import com.android.videoeditor.service.MovieOverlay; import com.android.videoeditor.service.MovieTransition; import com.android.videoeditor.service.VideoEditorProject; import com.android.videoeditor.widgets.AudioTrackLinearLayout; import com.android.videoeditor.widgets.MediaLinearLayout; import com.android.videoeditor.widgets.OverlayLinearLayout; /** * This activity handles callbacks from the service and manages the project */ public abstract class VideoEditorBaseActivity extends Activity { // Logging private static final String TAG = "VideoEditorBase"; protected static final int DIALOG_DELETE_BAD_PROJECT_ID = 100; // State keys private static final String STATE_PROJECT_PATH = "path"; private static final String STATE_EXPORT_FILENAME = "export_filename"; // Dialog parameters protected static final String PARAM_PROJECT_PATH = "path"; // Instance variables private final ServiceListener mServiceListener = new ServiceListener(); protected String mProjectPath; protected VideoEditorProject mProject; protected String mPendingExportFilename; private boolean mProjectEditState; /** * The service listener */ private class ServiceListener extends ApiServiceListener { @Override public void onProjectEditState(String projectPath, boolean projectEdited) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProjectEditState != projectEdited) { mProjectEditState = projectEdited; onProjectEditStateChange(projectEdited); } } @Override public void onVideoEditorCreated(String projectPath, VideoEditorProject project, List<MediaItem> mediaItems, List<AudioTrack> audioTracks, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } // Check if an error occurred if (exception != null) { // Invalidate the project path mProjectPath = null; enterDisabledState(R.string.editor_no_project); // Display an error Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_create_error, Toast.LENGTH_LONG).show(); } else { enterReadyState(); mProject = project; initializeFromProject(true); } } @Override public void onVideoEditorLoaded(String projectPath, VideoEditorProject project, List<MediaItem> mediaItems, List<AudioTrack> audioTracks, Exception exception) { if (!projectPath.equals(mProjectPath)) { return; } // Check if an error occurred if (exception != null || project == null) { mProjectPath = null; enterDisabledState(R.string.editor_no_project); final Bundle bundle = new Bundle(); bundle.putString(VideoEditorActivity.PARAM_PROJECT_PATH, projectPath); showDialog(DIALOG_DELETE_BAD_PROJECT_ID, bundle); } else { // The project may be loaded already. This can happen when we // create a new project if (mProject == null) { mProject = project; initializeFromProject(true); } } } @Override public void onVideoEditorAspectRatioSet(String projectPath, int aspectRatio, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_aspect_ratio_error, Toast.LENGTH_LONG).show(); } else { // The aspect ratio has changed setAspectRatio(aspectRatio); } } @Override public void onVideoEditorThemeApplied(String projectPath, String theme, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_apply_theme_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().addMediaItems(mProject.getMediaItems()); getOverlayLayout().addMediaItems(mProject.getMediaItems()); getAudioTrackLayout().addAudioTracks(mProject.getAudioTracks()); updateTimelineDuration(); } } @Override public void onVideoEditorGeneratePreviewProgress(String projectPath, String className, String itemId, int action, int progress) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "onVideoEditorGeneratePreviewProgress: " + className + " " + progress); } if (className == null) { // Last callback (after all items are generated) if (action == ApiService.ACTION_UPDATE_FRAME) { showPreviewFrame(); } } else if (MediaItem.class.getCanonicalName().equals(className)) { getMediaLayout().onGeneratePreviewMediaItemProgress(itemId, action, progress); } else if (Transition.class.getCanonicalName().equals(className)) { getMediaLayout().onGeneratePreviewTransitionProgress(itemId, action, progress); } else if (AudioTrack.class.getCanonicalName().equals(className)) { getAudioTrackLayout().onGeneratePreviewProgress(itemId, action, progress); } else { Log.w(TAG, "Unsupported storyboard item type: " + className); } } @Override public void onVideoEditorExportProgress(String projectPath, String filename, int progress) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (!filename.equals(mPendingExportFilename)) { return; } // Update the export progress onExportProgress(progress); } @Override public void onVideoEditorExportComplete(String projectPath, String filename, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (!filename.equals(mPendingExportFilename)) { return; } onExportComplete(); mPendingExportFilename = null; if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_export_error, Toast.LENGTH_LONG).show(); } } @Override public void onVideoEditorSaved(String projectPath, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_saved_error, Toast.LENGTH_LONG).show(); } } @Override public void onVideoEditorReleased(String projectPath, Exception exception) { if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_release_error, Toast.LENGTH_LONG).show(); } } @Override public void onVideoEditorDeleted(String projectPath, Exception exception) { if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_delete_error, Toast.LENGTH_LONG).show(); } } @Override public void onMediaItemAdded(String projectPath, String mediaItemId, MovieMediaItem mediaItem, String afterMediaItemId, Class<?> mediaItemClass, Integer newAspectRatio, Exception exception) { - // Check if the VideoEditor is the one we are expecting - if (!projectPath.equals(mProjectPath)) { - return; - } - - if (mProject == null) { + // Check if the VideoEditor is the one we are expecting. + if (!projectPath.equals(mProjectPath) || mProject == null) { return; } if (exception != null) { if (mediaItemClass.getCanonicalName().equals( MediaVideoItem.class.getCanonicalName())) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_video_clip_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_image_error, Toast.LENGTH_LONG).show(); } } else { getMediaLayout().insertMediaItem(mediaItem, afterMediaItemId); getOverlayLayout().insertMediaItem(mediaItem, afterMediaItemId); if (newAspectRatio != null) { // The aspect ratio has changed setAspectRatio(newAspectRatio); } updateTimelineDuration(); } } @Override public void onMediaLoaded(String projectPath, Uri mediaIUri, String mimeType, String filename, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_media_load_error, Toast.LENGTH_LONG).show(); } else { // Update the status of the downloaded item in the user interface } } @Override public void onMediaItemMoved(String projectPath, String mediaItemId, String afterMediaItemId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_move_media_item_error, Toast.LENGTH_LONG).show(); } else { // Update the entire timeline getMediaLayout().addMediaItems(mProject.getMediaItems()); getOverlayLayout().addMediaItems(mProject.getMediaItems()); updateTimelineDuration(); } } @Override public void onMediaItemRemoved(String projectPath, String mediaItemId, MovieTransition transition, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_remove_media_item_error, Toast.LENGTH_LONG).show(); } else { // Remove the media item and bounding transitions getMediaLayout().removeMediaItem(mediaItemId, transition); getOverlayLayout().removeMediaItem(mediaItemId); updateTimelineDuration(); } } @Override public void onMediaItemRenderingModeSet(String projectPath, String mediaItemId, int renderingMode, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_rendering_mode_error, Toast.LENGTH_LONG).show(); } } @Override public void onMediaItemDurationSet(String projectPath, String mediaItemId, long durationMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_media_item_duration_error, Toast.LENGTH_LONG).show(); } else { final MovieMediaItem mediaItem = mProject.getMediaItem(mediaItemId); // Update the media item getMediaLayout().updateMediaItem(mediaItem); getOverlayLayout().updateMediaItem(mediaItem); updateTimelineDuration(); } } @Override public void onMediaItemBoundariesSet(String projectPath, String mediaItemId, long beginBoundaryMs, long endBoundaryMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_media_item_boundaries_error, Toast.LENGTH_LONG).show(); } else { final MovieMediaItem mediaItem = mProject.getMediaItem(mediaItemId); getMediaLayout().updateMediaItem(mediaItem); getOverlayLayout().updateMediaItem(mediaItem); // Place the cursor at the beginning of the trimmed media item //movePlayhead(mProject.getMediaItemBeginTime(mediaItemId)); updateTimelineDuration(); } } @Override public boolean onMediaItemThumbnail(String projectPath, String mediaItemId, Bitmap thumbnail, int index, int token, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return false; } if (mProject == null) { return false; } if (exception != null) { return false; } else { return getMediaLayout().setMediaItemThumbnail( mediaItemId, thumbnail, index, token); } } @Override public void onTransitionInserted(String projectPath, MovieTransition transition, String afterMediaId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_transition_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().addTransition(transition, afterMediaId); updateTimelineDuration(); } } @Override public void onTransitionRemoved(String projectPath, String transitionId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_remove_transition_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().removeTransition(transitionId); updateTimelineDuration(); } } @Override public void onTransitionDurationSet(String projectPath, String transitionId, long durationMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_transition_duration_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().updateTransition(transitionId); getOverlayLayout().refresh(); updateTimelineDuration(); } } @Override public boolean onTransitionThumbnails(String projectPath, String transitionId, Bitmap[] thumbnails, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return false; } if (mProject == null) { return false; } if (exception != null) { return false; } else { return getMediaLayout().setTransitionThumbnails(transitionId, thumbnails); } } @Override public void onOverlayAdded(String projectPath, MovieOverlay overlay, String mediaItemId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_overlay_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().invalidateActionBar(); getOverlayLayout().addOverlay(mediaItemId, overlay); } } @Override public void onOverlayRemoved(String projectPath, String overlayId, String mediaItemId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_remove_overlay_error, Toast.LENGTH_LONG).show(); } else { getOverlayLayout().removeOverlay(mediaItemId, overlayId); } } @Override public void onOverlayStartTimeSet(String projectPath, String overlayId, String mediaItemId, long startTimeMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_start_time_overlay_error, Toast.LENGTH_LONG).show(); } } @Override public void onOverlayDurationSet(String projectPath, String overlayId, String mediaItemId, long durationMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_duration_overlay_error, Toast.LENGTH_LONG).show(); } } @Override public void onOverlayUserAttributesSet(String projectPath, String overlayId, String mediaItemId, Bundle userAttributes, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_user_attributes_overlay_error, Toast.LENGTH_LONG).show(); } else { getOverlayLayout().updateOverlayAttributes(mediaItemId, overlayId, userAttributes); } } @Override public void onEffectAdded(String projectPath, MovieEffect effect, String mediaItemId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_effect_error, Toast.LENGTH_LONG).show(); } else { getMediaLayout().updateMediaItem(mProject.getMediaItem(mediaItemId)); } } @Override public void onEffectRemoved(String projectPath, String effectId, String mediaItemId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_remove_effect_error, Toast.LENGTH_LONG).show(); } else { // Remove the effect getMediaLayout().updateMediaItem(mProject.getMediaItem(mediaItemId)); } } @Override public void onAudioTrackAdded(String projectPath, MovieAudioTrack audioTrack, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_add_audio_track_error, Toast.LENGTH_LONG).show(); } else { getAudioTrackLayout().addAudioTrack(audioTrack); } } @Override public void onAudioTrackRemoved(String projectPath, String audioTrackId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_remove_audio_track_error, Toast.LENGTH_LONG).show(); } else { getAudioTrackLayout().removeAudioTrack(audioTrackId); } } @Override public void onAudioTrackBoundariesSet(String projectPath, String audioTrackId, long beginBoundaryMs, long endBoundaryMs, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception != null) { Toast.makeText(VideoEditorBaseActivity.this, R.string.editor_set_audio_track_boundaries_error, Toast.LENGTH_LONG).show(); } else { getAudioTrackLayout().updateAudioTrack(audioTrackId); } } @Override public void onAudioTrackExtractAudioWaveformProgress(String projectPath, String audioTrackId, int progress) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } getAudioTrackLayout().setWaveformExtractionProgress(audioTrackId, progress); } @Override public void onAudioTrackExtractAudioWaveformComplete(String projectPath, String audioTrackId, Exception exception) { // Check if the VideoEditor is the one we are expecting if (!projectPath.equals(mProjectPath)) { return; } if (mProject == null) { return; } if (exception == null) { getAudioTrackLayout().setWaveformExtractionComplete(audioTrackId); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.video_editor); if (savedInstanceState != null) { mProjectPath = savedInstanceState.getString(STATE_PROJECT_PATH); mPendingExportFilename = savedInstanceState.getString(STATE_EXPORT_FILENAME); } else { final Intent intent = getIntent(); mProjectPath = intent.getStringExtra(ProjectsActivity.PARAM_OPEN_PROJECT_PATH); if (Intent.ACTION_INSERT.equals(intent.getAction())) { ApiService.createVideoEditor(this, mProjectPath, intent.getStringExtra(ProjectsActivity.PARAM_CREATE_PROJECT_NAME), new String[0], new String[0], null); } } } @Override public void onResume() { super.onResume(); mProjectEditState = ApiService.isProjectBeingEdited(mProjectPath); onProjectEditStateChange(mProjectEditState); ApiService.registerListener(mServiceListener); // Check if we need to load the project if (mProjectPath != null) { if (mProject == null) { // We need to load the project ApiService.loadVideoEditor(this, mProjectPath); enterTransitionalState(R.string.editor_loading_project); } else { // The project is already loaded initializeFromProject(false); } } else { enterDisabledState(R.string.editor_no_project); } // Request the audio focus so that other apps can pause playback. final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } @Override public void onPause() { super.onPause(); ApiService.unregisterListener(mServiceListener); if (mProject != null) { // Mark the project as clean. If/when we resume the activity // we can check this flag in order to refresh the UI for changes // which may had occurred when the activity was paused. mProject.setClean(true); // Save the contents of the current project ApiService.saveVideoEditor(this, mProjectPath); } // Release the audio focus final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.abandonAudioFocus(null); } @Override public void onDestroy() { super.onDestroy(); // If we have an active project release the VideoEditor if (mProjectPath != null) { if (!isChangingConfigurations()) { ApiService.releaseVideoEditor(this, mProjectPath); } mProjectPath = null; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_PROJECT_PATH, mProjectPath); outState.putString(STATE_EXPORT_FILENAME, mPendingExportFilename); } /** * @return true if the project is edited */ protected boolean isProjectEdited() { return mProjectEditState; } /** * Enter the disabled state * * @param statusStringId The status string id */ protected abstract void enterDisabledState(int statusStringId); /** * Enter the transitional state * * @param statusStringId The status string id */ protected abstract void enterTransitionalState(int statusStringId); /** * Enter the ready state */ protected abstract void enterReadyState(); /** * Show the preview frame at the current playhead position * * @return true if the surface is created, false otherwise. */ protected abstract boolean showPreviewFrame(); /** * The duration of the timeline has changed */ protected abstract void updateTimelineDuration(); /** * Move the playhead to the specified position * * @param timeMs The time position */ protected abstract void movePlayhead(long timeMs); /** * Change the aspect ratio * * @param aspectRatio The new aspect ratio */ protected abstract void setAspectRatio(int aspectRatio); /** * Initialize the project when restored from storage. * * @param updateUI true to update the UI * * Note that this method may be called also after the project was loaded */ protected abstract void initializeFromProject(boolean updateUI); /** * @return The media layout */ protected abstract MediaLinearLayout getMediaLayout(); /** * @return The overlay layout */ protected abstract OverlayLinearLayout getOverlayLayout(); /** * @return The audio layout */ protected abstract AudioTrackLinearLayout getAudioTrackLayout(); /** * The export is progressing */ protected abstract void onExportProgress(int progress); /** * The export has completed */ protected abstract void onExportComplete(); /** * @param projectEdited true if the project is edited */ protected abstract void onProjectEditStateChange(boolean projectEdited); }
false
false
null
null
diff --git a/src/main/java/org/testatoo/core/Language.java b/src/main/java/org/testatoo/core/Language.java index c9b1fed..80ea8ff 100644 --- a/src/main/java/org/testatoo/core/Language.java +++ b/src/main/java/org/testatoo/core/Language.java @@ -1,354 +1,357 @@ /** * Copyright (C) 2008 Ovea <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testatoo.core; import org.hamcrest.Matcher; import org.testatoo.core.component.AbstractTextField; import org.testatoo.core.component.CheckBox; import org.testatoo.core.component.Component; import org.testatoo.core.component.Window; import org.testatoo.core.component.datagrid.Cell; import org.testatoo.core.component.datagrid.Column; import org.testatoo.core.component.datagrid.DataGrid; import org.testatoo.core.component.datagrid.Row; import org.testatoo.core.input.Keyboard; import org.testatoo.core.input.Mouse; import org.testatoo.core.nature.Checkable; import java.util.concurrent.TimeUnit; /** * This is the abstract base class corresponding to Testatoo Domain Specific Langage. * This DSL is based on test langage (like "assertThat") improved with articles, adverbs, etc... * It provides also action verbs (like "click on") to simulate actions on graphic objects * * @author [email protected] */ public abstract class Language { private static ThreadLocal<Object> it = new ThreadLocal<Object>(); @SuppressWarnings({"unchecked"}) public static <T> T it() { return (T) it.get(); } /** * To check an assertion on a graphic object * * @param <T> type of the graphic object * @param object the graphic object * @param matcher the matcher to calculate the assertion */ public static <T> void assertThat(T object, Matcher<T> matcher) { set(object); org.hamcrest.MatcherAssert.assertThat(object, matcher); } /** * Language placeholder to check an assertion * * @param assertion the assertion object */ - public static Boolean assertThat(Boolean assertion) { + public static boolean assertThat(boolean assertion) { + if (!assertion) { + throw new AssertionError("Expected true but is false"); + } return assertion; } /** * To avoid repeating the "assertThat" when calculating another assertion on the same object * * @param <T> type of the graphic object * @param matcher the matcher to calculate the assertion */ @SuppressWarnings({"unchecked"}) public static <T> void and(Matcher<T> matcher) { org.hamcrest.MatcherAssert.assertThat((T) Language.it.get(), matcher); } /** * To avoid repeating the "assertThat" when calculating another assertion on the same object * * @param object dummy object for language support (use it() in place) * @param matcher the matcher to calculate the assertion */ @SuppressWarnings({"unchecked"}) public static <T> void and(Object object, Matcher<T> matcher) { and(matcher); } /** * To allow more readable tests * * @param <T> type of the component * @param component testatoo component * @return a testatoo component */ public static <T> T on(T component) { return into(component); } /** * To allow more readable tests * * @param <T> type of the component * @param component testatoo component * @return a testatoo component */ public static <T> T into(T component) { EvaluatorHolder.get().focusOn((Component) component); return component; } /** * Reset the field and call the method type * * @param <T> type of the textField * @param value value to be entered * @param element the textField * @return the textField with value in it */ public static <T extends AbstractTextField> T enter(String value, T element) { EvaluatorHolder.get().reset(element); return type(value, element); } /** * To simulate the enter of a value in a textField * * @param <T> type of the textField * @param value value to be entered * @param element the textField * @return the textField with value in it */ public static <T extends AbstractTextField> T type(String value, T element) { EvaluatorHolder.get().focusOn(element); Keyboard.type(value); return element; } /** * To simulate a click on a component * * @param <T> type of the component * @param component testatoo component * @return the component after click */ public static <T extends Component> T clickOn(T component) { Mouse.clickOn(component); return component; } /** * To simulate a double-click on a component * * @param <T> type of the component * @param component testatoo component * @return the component after double-click */ public static <T extends Component> T doubleClickOn(T component) { Mouse.doubleClickOn(component); return component; } /** * To simulate a mouse movement over a component * * @param <T> type of the component * @param component testatoo component * @return the component after mouse-over */ public static <T extends Component> T dragMouseOver(T component) { Mouse.mouseOverOn(component); return component; } /** * To simulate a mouse movement out of a component * * @param <T> type of the component * @param component testatoo component * @return the component after mouse-out */ public static <T extends Component> T dragMouseOut(T component) { Mouse.mouseOutOf(component); return component; } /** * To simulate a check of the component * * @param <T> type of the component * @param component testatoo component * @return the checked component */ public static <T extends Checkable> T check(T component) { component.check(); return component; } /** * To simulate a uncheck of the component * * @param <T> type of the component * @param component testatoo component * @return the unchecked component */ public static <T extends CheckBox> T unCheck(T component) { component.unCheck(); return component; } /** * To simulate the closing of a window * * @param window the window to close */ public static void close(Window window) { window.close(); } /** * Return the first row of a selection of row * * @param rows list of rows * @return first row */ public static Row first(Selection<Row> rows) { return rows.first(); } /** * Return the last row of a selection of row * * @param rows list of rows * @return last row */ public static Row last(Selection<Row> rows) { return rows.last(); } /** * Return the first row of a dataGrid * * @param dataGrid a dataGrid * @return first row of the dataGrid */ public static Row firstRowOf(DataGrid dataGrid) { return dataGrid.rows().first(); } /** * Return the last row of a dataGrid * * @param dataGrid a dataGrid * @return last row of the dataGrid */ public static Row lastRowOf(DataGrid dataGrid) { return dataGrid.rows().last(); } /** * Waiting until an assertion is reached. The timeout is 1 second * * @param <T> type of the graphic object * @param object the graphic object * @param matcher the matcher to calculate the assertion */ public static <T> void waitUntil(T object, org.hamcrest.Matcher<T> matcher) { waitUntil(object, matcher, max(1, TimeUnit.SECONDS)); } /** * Waiting until an assertion is reached. * * @param <T> type of the graphic object * @param object the graphic object * @param matcher the matcher to calculate the assertion * @param duration maximum waiting time */ public static <T> void waitUntil(T object, org.hamcrest.Matcher<T> matcher, Duration duration) { waitUntil(object, matcher, duration, freq(500, TimeUnit.MILLISECONDS)); } /** * Waiting until an assertion is reached. * * @param <T> type of the graphic object * @param object the graphic object * @param matcher the matcher to calculate the assertion * @param duration maximum waiting time * @param frequency frequency of retries */ public static <T> void waitUntil(T object, org.hamcrest.Matcher<T> matcher, Duration duration, Duration frequency) { final long step = frequency.unit.toMillis(frequency.duration); Throwable ex = null; try { for (long timeout = duration.unit.toMillis(duration.duration); timeout > 0; timeout -= step, Thread.sleep(step)) { try { assertThat(object, matcher); return; } catch (Throwable e) { ex = e; } } } catch (InterruptedException iex) { throw new RuntimeException("Interrupted exception", iex); } throw new RuntimeException("Unable to reach the condition in " + duration.duration + " " + duration.unit, ex); } public static Duration max(long duration, TimeUnit unit) { return new Duration(duration, unit); } public static Duration freq(long duration, TimeUnit unit) { return new Duration(duration, unit); } /** * Placeholder for language * * @return empty Columns array */ public static Column[] columns() { return new Column[0]; } /** * Placeholder for language * * @return empty Rows array */ public static Row[] rows() { return new Row[0]; } /** * Placeholder for language * * @return empty Cells array */ public static Cell[] cells() { return new Cell[0]; } private static <T> T set(T it) { Language.it.set(it); return it; } } diff --git a/src/main/java/org/testatoo/core/matcher/Displays.java b/src/main/java/org/testatoo/core/matcher/Displays.java index 058763e..9707073 100644 --- a/src/main/java/org/testatoo/core/matcher/Displays.java +++ b/src/main/java/org/testatoo/core/matcher/Displays.java @@ -1,75 +1,70 @@ /** * Copyright (C) 2008 Ovea <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testatoo.core.matcher; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.testatoo.core.component.Component; import org.testatoo.core.nature.Container; import java.util.ArrayList; import java.util.List; /** * @author [email protected] */ public class Displays extends TypeSafeMatcher<Container> { private Component[] components; private List<Component> notExistComponents = new ArrayList<Component>(); private List<Component> notVisibleComponents = new ArrayList<Component>(); private Displays(Component... components) { this.components = components; } @Override protected boolean matchesSafely(Container container) { - for (Component component : components) { if (container.contains(component)) { if (!component.isVisible()) notVisibleComponents.add(component); } else notExistComponents.add(component); } - - if (notExistComponents.isEmpty() && notVisibleComponents.isEmpty()) - return true; - else - return false; + return notExistComponents.isEmpty() && notVisibleComponents.isEmpty(); } @Override public void describeTo(Description description) { if (!notExistComponents.isEmpty()) { description.appendText("contains all of "); description.appendValueList("{", ", ", "}", notExistComponents); } if (!notExistComponents.isEmpty() && !notVisibleComponents.isEmpty()) { description.appendText(" and "); } if (!notVisibleComponents.isEmpty()) { description.appendText("all of this must be visible "); description.appendValueList("{", ", ", "}", notVisibleComponents); } } public static Displays displays(Component... components) { return new Displays(components); } } diff --git a/src/test/java/org/testatoo/core/language/LanguageTest.java b/src/test/java/org/testatoo/core/language/LanguageTest.java index 2cabf7b..89d265a 100644 --- a/src/test/java/org/testatoo/core/language/LanguageTest.java +++ b/src/test/java/org/testatoo/core/language/LanguageTest.java @@ -1,292 +1,304 @@ /** * Copyright (C) 2008 Ovea <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testatoo.core.language; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testatoo.core.Evaluator; import org.testatoo.core.EvaluatorHolder; import org.testatoo.core.ListSelection; import org.testatoo.core.Selection; import org.testatoo.core.component.*; import org.testatoo.core.component.datagrid.DataGrid; import org.testatoo.core.component.datagrid.Row; import org.testatoo.core.input.*; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import static org.testatoo.core.ComponentType.*; import static org.testatoo.core.Language.*; import static org.testatoo.core.matcher.Matchers.*; /** * @author [email protected] */ public class LanguageTest { private Evaluator evaluator; private String id = "myId"; @Before public void setUp() { evaluator = mock(Evaluator.class); when(evaluator.name()).thenReturn(Evaluator.DEFAULT_NAME); // Needed for Mouse ;) EvaluatorHolder.register(evaluator); when(evaluator.existComponent(id)).thenReturn(true); when(evaluator.isVisible(any(Component.class))).thenReturn(true); when(evaluator.isEnabled(any(Component.class))).thenReturn(true); } @After public void clean() { EvaluatorHolder.unregister(Evaluator.DEFAULT_NAME); } @Test public void checkbox_usage_through_language() { when(evaluator.componentType(id)).thenReturn(CheckBox); CheckBox checkBox = new CheckBox(evaluator, id); when(evaluator.isChecked(checkBox)).thenReturn(false, true, false); when(evaluator.label(checkBox)).thenReturn("myLabel"); assertThat(checkBox, is(not(checked()))); check(checkBox); assertThat(checkBox, is(checked())); unCheck(checkBox); assertThat(checkBox, is(not(checked()))); assertThat(checkBox, has(label("myLabel"))); verify(evaluator, times(1)).check(checkBox); verify(evaluator, times(1)).unCheck(checkBox); verify(evaluator, times(3)).isChecked(checkBox); } @Test public void radio_usage_through_language() { when(evaluator.componentType(id)).thenReturn(Radio); Radio radio = new Radio(evaluator, id); when(evaluator.label(radio)).thenReturn("myLabel"); when(evaluator.isChecked(radio)).thenReturn(false, true); assertThat(radio, is(not(checked()))); check(radio); assertThat(radio, is(checked())); and(it(), has(label("myLabel"))); assertThat(radio, has(label("myLabel"))); verify(evaluator, times(1)).check(radio); verify(evaluator, times(2)).isChecked(radio); } @Test public void textfield_usage_through_language_part1() { when(evaluator.componentType(id)).thenReturn(TextField); TextField textField = new TextField(evaluator, id); when(evaluator.label(textField)).thenReturn("myLabel"); when(evaluator.value(textField)).thenReturn("myValue"); assertThat(textField, has(label("myLabel"))); assertThat(textField, has(value("myValue"))); clickOn(textField); Keyboard.type("SomeData"); verify(evaluator, times(1)).click(textField, Click.left); verify(evaluator, times(1)).type("SomeData"); } @Test public void textfield_usage_through_language_part2() { when(evaluator.componentType(id)).thenReturn(TextField); TextField textField = new TextField(evaluator, id); when(evaluator.maxLength(textField)).thenReturn(255); when(evaluator.label(textField)).thenReturn("myLabel"); when(evaluator.value(textField)).thenReturn("myValue"); assertThat(textField, is(enabled())); and(not(disabled())); and(it(), visible()); clickOn(textField); Mouse.clickOn(textField); type("data_1", into(textField)); verify(evaluator, times(2)).click(textField, Click.left); verify(evaluator, times(2)).focusOn(any(Component.class)); verify(evaluator, times(1)).type("data_1"); } @Test public void textfield_usage_through_language_part3() { when(evaluator.componentType(id)).thenReturn(TextField); TextField textField = new TextField(evaluator, id); when(evaluator.maxLength(textField)).thenReturn(255); when(evaluator.label(textField)).thenReturn("myLabel"); when(evaluator.value(textField)).thenReturn(""); enter("SomeData", on(textField)); verify(evaluator, atLeastOnce()).focusOn(textField); verify(evaluator, times(1)).reset(textField); verify(evaluator, times(1)).type("SomeData"); } @Test public void test_window_usage_through_language() { when(evaluator.componentType(id)).thenReturn(Window); Window window = new Window(evaluator, id); when(evaluator.isVisible(any(Component.class))).thenReturn(true); when(evaluator.isEnabled(any(Component.class))).thenReturn(true); when(evaluator.title(window)).thenReturn("windowTitle"); close(window); verify(evaluator, times(1)).close(window); } @Test public void test_mouse_usage_on_component() { Component component = new Component(evaluator, id); clickOn(component); doubleClickOn(component); dragMouseOut(component); dragMouseOver(component); verify(evaluator, times(1)).click(component, Click.left); verify(evaluator, times(1)).doubleClick(component); verify(evaluator, times(1)).mouseOut(component); verify(evaluator, times(1)).mouseOver(component); } @Test public void test_keyboard_usage() { when(evaluator.componentType(id)).thenReturn(TextField); TextField textField = new TextField(evaluator, id); when(evaluator.maxLength(textField)).thenReturn(255); when(evaluator.label(textField)).thenReturn("label"); when(evaluator.value(textField)).thenReturn("value"); type("Some Data", on(textField)); Keyboard.type("Other Data"); Keyboard.keyDown(KeyModifier.SHIFT); Keyboard.release(KeyModifier.CONTROL); Keyboard.press(Key.F6); Keyboard.release(); verify(evaluator, atLeastOnce()).focusOn(textField); verify(evaluator, times(1)).type("Some Data"); verify(evaluator, times(1)).type("Other Data"); verify(evaluator, times(1)).keyDown(KeyModifier.SHIFT); verify(evaluator, times(1)).release(KeyModifier.CONTROL); verify(evaluator, times(1)).press(Key.F6); verify(evaluator, times(1)).release(); } @Test public void test_dataGrid_usage() { when(evaluator.componentType(id)).thenReturn(DataGrid); final DataGrid dataGrid = new DataGrid(evaluator, id); when(evaluator.existComponent("1")).thenReturn(true); when(evaluator.componentType("1")).thenReturn(Row); when(evaluator.existComponent("2")).thenReturn(true); when(evaluator.componentType("2")).thenReturn(Row); when(evaluator.existComponent("3")).thenReturn(true); when(evaluator.componentType("3")).thenReturn(Row); when(evaluator.existComponent("4")).thenReturn(true); when(evaluator.componentType("4")).thenReturn(Row); when(evaluator.existComponent("5")).thenReturn(true); when(evaluator.componentType("5")).thenReturn(Row); when(evaluator.existComponent("6")).thenReturn(true); when(evaluator.componentType("6")).thenReturn(Row); when(evaluator.existComponent("7")).thenReturn(true); when(evaluator.componentType("7")).thenReturn(Row); Row row_1 = new Row(evaluator, "1"); Row row_2 = new Row(evaluator, "2"); Row row_3 = new Row(evaluator, "3"); Row row_4 = new Row(evaluator, "4"); Row row_5 = new Row(evaluator, "5"); Row row_6 = new Row(evaluator, "6"); Row row_7 = new Row(evaluator, "7"); Selection<Row> rows = ListSelection.of(row_1, row_2, row_3, row_4, row_5, row_6, row_7); when(evaluator.rows(dataGrid)).thenReturn(rows); when(evaluator.cells(any(Row.class))).thenReturn(ListSelection.empty()); assertThat(first(dataGrid.rows()).id(), is(dataGrid.row(1).id())); assertThat(last(dataGrid.rows()).id(), is(dataGrid.row(dataGrid.rows().size()).id())); } @Test public void test_wait_until_with_success() { evaluator = mock(Evaluator.class); when(evaluator.existComponent(id)).thenReturn(true); when(evaluator.isVisible(any(Component.class))).thenReturn(false, false, false, false, false, false, true); when(evaluator.isEnabled(any(Component.class))).thenReturn(true); Component component = new Component(evaluator, id); waitUntil(component, is(visible()), max(2, TimeUnit.SECONDS), freq(500, TimeUnit.MILLISECONDS)); verify(evaluator, times(7)).isVisible(any(Component.class)); } @Test public void test_wait_until_with_failure() { evaluator = mock(Evaluator.class); when(evaluator.existComponent(id)).thenReturn(true); when(evaluator.isVisible(any(Component.class))).thenReturn(false); when(evaluator.isEnabled(any(Component.class))).thenReturn(true); Component component = new Component(evaluator, id); try { waitUntil(component, is(visible())); fail(); } catch (Exception e) { assertThat(e.getMessage(), is("Unable to reach the condition in 1 SECONDS")); } } + + @Test + public void test_sugar_assertThat() { + assertThat(true); + + try { + assertThat(false); + fail(); + } catch (AssertionError e) { + assertThat(e.getMessage(), is("Expected true but is false")); + } + } }
false
false
null
null
diff --git a/src/main/java/com/bergerkiller/bukkit/tc/DirectionStatement.java b/src/main/java/com/bergerkiller/bukkit/tc/DirectionStatement.java index d0884f3..1058cfd 100644 --- a/src/main/java/com/bergerkiller/bukkit/tc/DirectionStatement.java +++ b/src/main/java/com/bergerkiller/bukkit/tc/DirectionStatement.java @@ -1,57 +1,57 @@ package com.bergerkiller.bukkit.tc; import java.util.Locale; import org.bukkit.block.BlockFace; import com.bergerkiller.bukkit.common.utils.LogicUtil; import com.bergerkiller.bukkit.tc.controller.MinecartGroup; import com.bergerkiller.bukkit.tc.controller.MinecartMember; import com.bergerkiller.bukkit.tc.events.SignActionEvent; import com.bergerkiller.bukkit.tc.statements.Statement; public class DirectionStatement { public Direction direction; public String text; public Integer number; public DirectionStatement(String text, BlockFace cartDirection) { this(text, BlockFace.SELF, Direction.NONE); } public DirectionStatement(String text, BlockFace cartDirection, Direction alternative) { int idx = text.indexOf(':'); if (idx == -1) { this.text = text; this.direction = alternative; } else { this.text = text.substring(idx + 1); // Parse Direction from String text final String dirText = text.substring(0, idx).toLowerCase(Locale.ENGLISH); if (LogicUtil.contains(dirText, "c", "continue")) { this.direction = Direction.fromFace(cartDirection); - } else if (LogicUtil.contains(dirText, "r", "reverse")) { + } else if (LogicUtil.contains(dirText, "i", "rev", "reverse", "inverse")) { this.direction = Direction.fromFace(cartDirection.getOppositeFace()); } else { this.direction = Direction.parse(dirText); } } try { this.number = Integer.parseInt(this.text); } catch (NumberFormatException ex) { this.number = null; } } public boolean has(SignActionEvent event, MinecartMember<?> member) { return Statement.has(member, this.text, event); } public boolean has(SignActionEvent event, MinecartGroup group) { return Statement.has(group, this.text, event); } public boolean hasNumber() { return this.number != null; } } diff --git a/src/main/java/com/bergerkiller/bukkit/tc/statements/StatementItems.java b/src/main/java/com/bergerkiller/bukkit/tc/statements/StatementItems.java index ead5077..f9a6a0d 100644 --- a/src/main/java/com/bergerkiller/bukkit/tc/statements/StatementItems.java +++ b/src/main/java/com/bergerkiller/bukkit/tc/statements/StatementItems.java @@ -1,98 +1,109 @@ package com.bergerkiller.bukkit.tc.statements; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import com.bergerkiller.bukkit.common.inventory.ItemParser; import com.bergerkiller.bukkit.common.utils.ItemUtil; import com.bergerkiller.bukkit.tc.Util; import com.bergerkiller.bukkit.tc.controller.MinecartGroup; import com.bergerkiller.bukkit.tc.controller.MinecartMember; import com.bergerkiller.bukkit.tc.controller.type.MinecartMemberChest; import com.bergerkiller.bukkit.tc.events.SignActionEvent; public class StatementItems extends Statement { @Override public boolean match(String text) { return text.startsWith("items"); } @Override public boolean handle(MinecartMember<?> member, String text, SignActionEvent event) { final Inventory inventory = getInventory(member); if (inventory == null) { return false; } int count = ItemUtil.getItemCount(getInventory(member), -1, -1); return Util.evaluate(count, text); } @Override public boolean handle(MinecartGroup group, String text, SignActionEvent event) { final Inventory inventory = getInventory(group); if (inventory == null) { return false; } int count = ItemUtil.getItemCount(inventory, -1, -1); return Util.evaluate(count, text); } @Override public boolean matchArray(String text) { return text.equals("i"); } public boolean handleInventory(Inventory inv, String[] items) { if (inv == null) { return false; } int opidx; int count; for (String itemname : items) { opidx = Util.getOperatorIndex(itemname); String itemnamefixed; if (opidx > 0) { itemnamefixed = itemname.substring(0, opidx - 1); } else { itemnamefixed = itemname; } for (ItemParser parser : Util.getParsers(itemnamefixed)) { count = ItemUtil.getItemCount(inv, parser.getTypeId(), parser.getData()); if (opidx == -1) { if (parser.hasAmount()) { if (count >= parser.getAmount()) { return true; } } else if (count > 0) { return true; } } else if (Util.evaluate(count, itemname)) { return true; } } + // Check for 'special' named items + count = 0; + for (ItemStack item : inv) { + if (ItemUtil.hasDisplayName(item) && ItemUtil.getDisplayName(item).equals(itemnamefixed)) { + count++; + } + } + if (count > 0 && Util.evaluate(count, itemname)) { + return true; + } } return false; } public Inventory getInventory(MinecartMember<?> member) { if (member instanceof MinecartMemberChest) { return ((MinecartMemberChest) member).getEntity().getInventory(); } else { return null; } } public Inventory getInventory(MinecartGroup group) { return group.getInventory(); } @Override public boolean handleArray(MinecartMember<?> member, String[] items, SignActionEvent event) { return handleInventory(getInventory(member), items); } @Override public boolean handleArray(MinecartGroup group, String[] items, SignActionEvent event) { return handleInventory(getInventory(group), items); } }
false
false
null
null
diff --git a/com.ibm.wala.core/src/com/ibm/wala/logic/Disjunction.java b/com.ibm.wala.core/src/com/ibm/wala/logic/Disjunction.java index 1a43ee547..e608cc8b5 100644 --- a/com.ibm.wala.core/src/com/ibm/wala/logic/Disjunction.java +++ b/com.ibm.wala.core/src/com/ibm/wala/logic/Disjunction.java @@ -1,146 +1,155 @@ /******************************************************************************* * Copyright (c) 2006 IBM 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.logic; import java.util.Collection; import java.util.Collections; import com.ibm.wala.logic.ILogicConstants.BinaryConnective; import com.ibm.wala.util.collections.HashSetFactory; /** * A disjunction of formulae * * @author sjfink */ public class Disjunction extends AbstractBinaryFormula implements IMaxTerm { // invariant: size >= 2 private final Collection<? extends IFormula> clauses; private Disjunction(Collection<? extends IFormula> clauses) { assert clauses.size() >= 2; this.clauses = clauses; } public Collection<? extends IConstant> getConstants() { Collection<IConstant> result = HashSetFactory.make(); for (IFormula f : clauses) { result.addAll(f.getConstants()); } return result; } public Collection<? extends ITerm> getTerms() { Collection<ITerm> result = HashSetFactory.make(); for (IFormula f : clauses) { result.addAll(f.getTerms()); } return result; } public Collection<Variable> getFreeVariables() { Collection<Variable> result = HashSetFactory.make(); for (IFormula f : clauses) { result.addAll(f.getFreeVariables()); } return result; } public String prettyPrint(ILogicDecorator d) { if (clauses.size() == 1) { return getF1().prettyPrint(d); } else { StringBuffer result = new StringBuffer(); result.append(" ( "); result.append(getF1().prettyPrint(d)); result.append(" ) "); result.append(d.prettyPrint(getConnective())); result.append(" ( "); result.append(getF2().prettyPrint(d)); result.append(" )"); return result.toString(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clauses == null) ? 0 : clauses.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Disjunction other = (Disjunction) obj; if (clauses == null) { if (other.clauses != null) return false; } else if (!clauses.equals(other.clauses)) return false; return true; } @Override public BinaryConnective getConnective() { return BinaryConnective.OR; } @Override public IFormula getF1() { return clauses.iterator().next(); } @Override public IFormula getF2() { Collection<? extends IFormula> c = HashSetFactory.make(clauses); c.remove(getF1()); - return make(c); + if (c.size() == 1) { + return c.iterator().next(); + } else { + return make(c); + } } public static Disjunction make(Collection<? extends IFormula> clauses) { + assert clauses.size() >= 2; Collection<IFormula> newClauses = HashSetFactory.make(); for (IFormula c : clauses) { - assert !(c instanceof Disjunction); - if (Simplifier.isTautology(c)) { - return make(BooleanConstantFormula.TRUE); - } else if (!Simplifier.isContradiction(c)) { - newClauses.add(c); + if (c instanceof Disjunction) { + Disjunction d = (Disjunction) c; + newClauses.addAll(d.clauses); + } else { + if (Simplifier.isTautology(c)) { + return make(BooleanConstantFormula.TRUE); + } else if (!Simplifier.isContradiction(c)) { + newClauses.add(c); + } } } if (newClauses.isEmpty()) { return make(BooleanConstantFormula.FALSE); } return new Disjunction(newClauses); } public Collection<? extends IFormula> getClauses() { return Collections.unmodifiableCollection(clauses); } public static Disjunction make(BooleanConstantFormula f) { Collection<? extends IFormula> c = Collections.singleton(f); return new Disjunction(c); } @Override public String toString() { return prettyPrint(DefaultDecorator.instance()); } }
false
false
null
null
diff --git a/src/com/zrd/zr/letuwb/EntranceActivity.java b/src/com/zrd/zr/letuwb/EntranceActivity.java index 081f2c9..db7347f 100755 --- a/src/com/zrd/zr/letuwb/EntranceActivity.java +++ b/src/com/zrd/zr/letuwb/EntranceActivity.java @@ -1,1339 +1,1339 @@ package com.zrd.zr.letuwb; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.google.ads.AdRequest; import com.google.ads.AdView; import com.mobclick.android.MobclickAgent; import com.zrd.zr.letuwb.R; import com.zrd.zr.protos.WeibousersProtos.Weibousers; import com.zrd.zr.protos.WeibousersProtos.Weibouser; public class EntranceActivity extends Activity implements OnTouchListener { final static String SERIAL_APP = "gbhytfvnjurdcmkiesx,lowaz.;p201108282317"; final static String TIMEZONE_SERVER = "Asia/Hong_Kong"; //final static String URL_SITE = "http://hot88.info/letmewb/"; final static String URL_SITE = "http://183.90.186.96/letmewb/"; //final static String URL_UPDATE = "http://az88.info/"; final static String URL_UPDATE = "http://183.90.186.96/"; //final static String URL_STATS = "http://az88.info/letmewb/"; final static String URL_STATS = "http://183.90.186.96/letmewb/"; final static String PATH_COLLECTION = "/letuwb/collection/"; final static String PATH_CACHE = "/letuwb/cache/"; final static Integer MAXSIZE_CACHE = 100;// in MB final static Integer MAXPERCENTAGE_CACHE = 5; // with % final static int REQUESTCODE_PICKFILE = 1001; final static int REQUESTCODE_BACKFROM = 1002; final static String CONFIG_ACCOUNTS = "Accounts"; final static String CONFIG_CLIENTKEY = "ClientKey"; final static String CONFIG_RANDOMKEY = "RandomKey"; final static String CONFIG_TOPICCHOICE = "TopicChoice"; final static String SYMBOL_FAILED = "~failed~"; final static String SYMBOL_SUCCESSFUL = "~successful~"; final static int PERIOD_VOTEAGAIN = 24;//in HOUR private static String mClientKey = ""; private static String mRandomKey = ""; private static Integer mTopicChoice = 0; GridView mGridPics; private static final Integer mLimit = 28;//how many pictures should be passed to PicbrowActivity, actually multiple of mPageLimit is recommended final Integer mPageLimit = 4;//how many pictures should be loaded into mGridPics. private static Integer mCurPage = 1; private Integer mPageBeforeBrow = 1; private static Integer mCurParagraph = 1; private static Integer mTotalPages = 0; private static Integer mTotalPics = 0; private static ArrayList<String> mCurTerms = new ArrayList<String>(); private static Integer mAccountId = 0; private static ArrayList<WeibouserInfo> mUsrs = new ArrayList<WeibouserInfo>(); ArrayList<WeibouserInfo> mPageUsrs = new ArrayList<WeibouserInfo>(); OnClickListener listenerBtnView = null; OnClickListener listenerBtnExit = null; Dialog mPrgDlg; private Dialog mDlgWaysToCheck; AlertDialog mQuitDialog; EditText mEditUsername; EditText mEditPassword; EditText mEditRepeat; TableRow mRowRepeat; CheckBox mCheckRemember; TextView mTextPageInfo; Button mBtnRandom; Button mBtnLatest; Button mBtnHottest; Button mBtnUnhottest; ImageButton mBtnExchange; private ArrayList<Button> mTopicBtns = null; SeekBar mSeekMain; Button mBtnPre; Button mBtnNext; TextView mTextSeekPos; LinearLayout mLinearMainBottom; WebView mWebCount; static DisplayMetrics mDisplayMetrics = new DisplayMetrics(); private static int mPrivilege = 1;//0 member, 1 guest NotificationManager mNotificationManager; GestureDetector mGestureDetector = null; private String mOutText;//!!actually not used!! static SharedPreferences mPreferences = null; /* Called when the activity is firstly created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); mPreferences = getPreferences(EntranceActivity.MODE_PRIVATE); /** * Try to trace exceptions */ //TraceDroid.init(this); //TraceDroidEmailSender.sendStackTraces("[email protected]", this); /** * Initialize the application */ mClientKey = mPreferences.getString(CONFIG_CLIENTKEY, ""); mRandomKey = mPreferences.getString(CONFIG_RANDOMKEY, ""); mTopicChoice = mPreferences.getInt(CONFIG_TOPICCHOICE, 0); AsyncInit init = new AsyncInit(); init.execute(); /** * Clean cache if needed */ AsyncCacheCleaner acc = new AsyncCacheCleaner(this); acc.execute( AsyncSaver.getSdcardDir() + EntranceActivity.PATH_CACHE, MAXSIZE_CACHE.toString(), //in MB MAXPERCENTAGE_CACHE.toString() //in percentage ); // Look up the AdView as a resource and load a request. AdView adView = (AdView)this.findViewById(R.id.adsMain); adView.loadAd(new AdRequest()); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.exchangelist_title); RegLoginActivity.addContext(EntranceActivity.this); mBtnExchange = (ImageButton) findViewById(R.id.btnExchange); mGridPics = (GridView) findViewById(R.id.gridViewPics); mTextPageInfo = (TextView) findViewById(R.id.tvPageInfo); mBtnRandom = (Button) findViewById(R.id.btnRandom); mBtnLatest = (Button) findViewById(R.id.btnLatest); mBtnHottest = (Button) findViewById(R.id.btnHottest); mBtnUnhottest = (Button) findViewById(R.id.btnUnhottest); mTopicBtns = new ArrayList<Button>(); mTopicBtns.add(mBtnLatest); mTopicBtns.add(mBtnHottest); mTopicBtns.add(mBtnRandom); mTopicBtns.add(mBtnUnhottest); mSeekMain = (SeekBar) findViewById(R.id.sbMain); mBtnPre = (Button) findViewById(R.id.btnPre); mBtnNext = (Button) findViewById(R.id.btnNext); mTextSeekPos = (TextView) findViewById(R.id.tvSeekPos); mLinearMainBottom = (LinearLayout) findViewById(R.id.linearLayoutMainBottom); mLinearMainBottom.setVisibility(LinearLayout.GONE); mWebCount = (WebView) findViewById(R.id.wvCount); getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mGestureDetector = new GestureDetector(this, new LetuseeGestureListener()); mGridPics.setOnTouchListener(this); mBtnExchange.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(EntranceActivity.this, ExchangeListActivity.class); startActivity(intent); } }); mTextSeekPos.setVisibility(TextView.GONE); mSeekMain.setMax(0); mSeekMain.setOnSeekBarChangeListener( new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub int p; if (progress == 0) p = 1; else p = progress; mTextSeekPos.setText("" + ((p - 1) * mPageLimit + 1) + "~" + (p * mPageLimit)); mTextSeekPos.setVisibility(TextView.VISIBLE); mTextPageInfo.setVisibility(TextView.GONE); AlphaAnimation anim = new AlphaAnimation(0.1f, 1.0f); mTextSeekPos.startAnimation(anim); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub mTextSeekPos.setVisibility(TextView.GONE); mTextPageInfo.setVisibility(TextView.VISIBLE); int progress = seekBar.getProgress(); if (progress == 0) progress = 1; int idxPic = mPageLimit * progress; Integer page; if (idxPic % mLimit == 0) { page = idxPic / mLimit; } else { page = (int) Math.ceil((double) idxPic / (double) mLimit); } int max = (int) Math.ceil((double) mLimit / (double) mPageLimit); Integer paragraph = progress % max == 0 ? max : (progress % max); mPrgDlg.show(); AsyncGridLoader agl = new AsyncGridLoader(EntranceActivity.this); int m = mCurTerms.size(); String[] args = new String[m + 4]; for (int i = 0; i < m; i++) { args[i] = mCurTerms.get(i); } args[m] = "limit"; args[m + 1] = mLimit.toString(); args[m + 2] = "page"; args[m + 3] = page.toString(); mCurPage = page; mCurParagraph = paragraph; agl.execute(args); /* Toast.makeText( LetuseeActivity.this, "" + ((progress - 1) * mPageLimit + 1) + "~" + (progress * mPageLimit), Toast.LENGTH_SHORT ).show(); */ } } ); mBtnPre.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub previous(); } }); mBtnNext.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub next(); } }); mBtnRandom.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub mBtnRandom.setSelected(true); mBtnLatest.setSelected(false); mBtnHottest.setSelected(false); mBtnUnhottest.setSelected(false); AsyncGridLoader asyncGridLoader = new AsyncGridLoader(EntranceActivity.this); mPrgDlg.show(); mCurTerms.clear(); mCurTerms.add("top"); mCurTerms.add("6"); mCurPage = 1; mCurParagraph = 1; asyncGridLoader.execute(mCurTerms.get(0), mCurTerms.get(1), "limit", mLimit.toString(), "page", mCurPage.toString(), "pb", "1"); } }); mBtnLatest.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub mBtnRandom.setSelected(false); mBtnLatest.setSelected(true); mBtnHottest.setSelected(false); mBtnUnhottest.setSelected(false); AsyncGridLoader asyncGridLoader = new AsyncGridLoader(EntranceActivity.this); mPrgDlg.show(); mCurTerms.clear(); mCurTerms.add("top"); mCurTerms.add("0"); mCurPage = 1; mCurParagraph = 1; asyncGridLoader.execute(mCurTerms.get(0), mCurTerms.get(1), "limit", mLimit.toString(), "page", mCurPage.toString(), "pb", "1"); } }); mBtnHottest.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub mBtnRandom.setSelected(false); mBtnLatest.setSelected(false); mBtnHottest.setSelected(true); mBtnUnhottest.setSelected(false); Toast.makeText( EntranceActivity.this, R.string.tips_hottesttheweek, Toast.LENGTH_LONG ).show(); AsyncGridLoader asyncGridLoader = new AsyncGridLoader(EntranceActivity.this); mPrgDlg.show(); mCurTerms.clear(); mCurTerms.add("top"); mCurTerms.add("4"); mCurPage = 1; mCurParagraph = 1; asyncGridLoader.execute(mCurTerms.get(0), mCurTerms.get(1), "limit", mLimit.toString(), "page", mCurPage.toString(), "pb", "1"); } }); mBtnUnhottest.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { // TODO Auto-generated method stub mBtnRandom.setSelected(false); mBtnLatest.setSelected(false); mBtnHottest.setSelected(false); mBtnUnhottest.setSelected(true); Toast.makeText( EntranceActivity.this, R.string.tips_unhottesttheweek, Toast.LENGTH_LONG ).show(); AsyncGridLoader asyncGridLoader = new AsyncGridLoader(EntranceActivity.this); mPrgDlg.show(); mCurTerms.clear(); mCurTerms.add("top"); mCurTerms.add("5"); mCurPage = 1; mCurParagraph = 1; asyncGridLoader.execute(mCurTerms.get(0), mCurTerms.get(1), "limit", mLimit.toString(), "page", mCurPage.toString(), "pb", "1"); } }); mPrgDlg = new Dialog(this, R.style.Dialog_Clean); mPrgDlg.setContentView(R.layout.custom_dialog_loading); WindowManager.LayoutParams lp = mPrgDlg.getWindow().getAttributes(); lp.alpha = 1.0f; mPrgDlg.getWindow().setAttributes(lp); mPrgDlg.setCancelable(true); mQuitDialog = new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).create(); mQuitDialog.setTitle(getString(R.string.quit_title)); mQuitDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.label_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub SharedPreferences.Editor edit = mPreferences.edit(); int i; for (i = 0; i < mTopicBtns.size(); i++) { if (mTopicBtns.get(i).isSelected()) break; } edit.putInt(CONFIG_TOPICCHOICE, i); edit.commit(); android.os.Process.killProcess(android.os.Process.myPid()); } } ); mQuitDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.label_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } } ); mDlgWaysToCheck = new Dialog(this, R.style.Dialog_Clean); mDlgWaysToCheck.setContentView(R.layout.custom_dialog_list); ListView lv = (ListView)mDlgWaysToCheck.findViewById(R.id.lvCustomList); ArrayList<String> list = new ArrayList<String>(); list.add(getString(R.string.label_bigger_pic)); list.add(getString(R.string.label_microblogs)); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, R.layout.item_custom_dialog_list, list ); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) { // TODO Auto-generated method stub WeibouserInfo wi; Intent intent = new Intent(); int idx = (Integer) mGridPics.getTag(); switch (position) { case 0: wi = (WeibouserInfo) mPageUsrs.get(idx); intent.setClass(EntranceActivity.this, PicbrowActivity.class); intent.putExtra("id", wi.id); mPageBeforeBrow = mCurPage; startActivityForResult(intent, REQUESTCODE_BACKFROM); break; case 1: wi = (WeibouserInfo) mPageUsrs.get(idx); intent.putExtra("uid", wi.uid); intent.setClass(EntranceActivity.this, WeiboShowActivity.class); startActivity(intent); break; } mDlgWaysToCheck.dismiss(); } }); mGridPics.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // TODO Auto-generated method stub mGridPics.setTag(position); mDlgWaysToCheck.show(); } }); if (mClientKey.equals("")) { mBtnHottest.performClick(); } else { if (mTopicChoice < mTopicBtns.size()) { mTopicBtns.get(mTopicChoice).performClick(); } else { mBtnLatest.performClick(); } } } /* * get index of current usr in mUsrs by id */ public static int getUsrIndexFromId(long id, List<WeibouserInfo> usrs) { if (usrs == null) return -1; if (usrs.size() == 0) return -1; int i; for (i = 0; i < usrs.size(); i++) { WeibouserInfo pi = (WeibouserInfo) usrs.get(i); if (id == pi.id) { break; } } if (i == usrs.size()) return -1; return i; } /* * get picfileInfo from mUsrs by id */ public static WeibouserInfo getPicFromId(long id, List<WeibouserInfo> pics) { int idx = getUsrIndexFromId(id, pics); if (idx < 0 || idx >= pics.size()) return null; return pics.get(idx); } public static String getClientKey() { return mClientKey; } public static String getRandomKey() { return mRandomKey; } public static void resetRandomKey(String key) { mRandomKey = key; if (mPreferences != null) { SharedPreferences.Editor edit = mPreferences.edit(); edit.putString(CONFIG_RANDOMKEY, mRandomKey); edit.commit(); } } public static ArrayList<String[]> getStoredAccounts() { ArrayList<String[]> list = new ArrayList<String[]>(); if (mPreferences == null) return list; String contents = mPreferences.getString(CONFIG_ACCOUNTS, ""); if (contents.equals("")) return list; String[] pairs = contents.split(","); if (pairs.length % 2 != 0) return list; for (int i = 0; i < pairs.length; i += 2) { list.add(new String[] {pairs[i], pairs[i + 1]}); } return list; } public static void saveAccount(String usr, String pwd) { ArrayList<String[]> list = getStoredAccounts(); int i; for (i = 0; i < list.size(); i++) { if (list.get(i)[0].equals(usr)) break; } if (i != list.size()) { list.remove(i); } list.add(new String[] {usr, pwd}); String content = ""; for (i = 0; i < list.size(); i++) { content += list.get(i)[0] + "," + list.get(i)[1]; if (i != list.size() - 1) content += ","; } SharedPreferences.Editor edit = mPreferences.edit(); edit.putString(CONFIG_ACCOUNTS, content); edit.commit(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { // TODO Auto-generated method stub runOnUiThread(new Runnable() { public void run() { final String TAG = "Letusee Stats"; String url = URL_STATS + "count.html"; mWebCount.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading (WebView view, String url) { Log.v(TAG, "loading " + url); return false; } }); WebSettings webSettings = mWebCount.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(false); mWebCount.loadUrl(url); Log.v(TAG, "send " + url); } }); super.onResume(); /* * for umeng.com */ MobclickAgent.onResume(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(Menu.NONE, Menu.FIRST + 2, 2, getString(R.string.omenuitem_reglogin)).setIcon(R.drawable.ic_menu_login); menu.add(Menu.NONE, Menu.FIRST + 1, 1, getString(R.string.omenuitem_upload)).setIcon(android.R.drawable.ic_menu_upload); menu.add(Menu.NONE, Menu.FIRST + 3, 3, getString(R.string.omenuitem_quit)).setIcon(android.R.drawable.ic_menu_close_clear_cancel); menu.add(Menu.NONE, Menu.FIRST + 4, 4, getString(R.string.omenuitem_about)).setIcon(android.R.drawable.ic_menu_help); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case Menu.FIRST + 1: AsyncUploader.upload(mPrivilege, EntranceActivity.this); break; case Menu.FIRST + 2: if (mPrivilege == 0) { Toast.makeText( this, R.string.tips_alreadyloggedin, Toast.LENGTH_SHORT ).show(); } else { Intent intent = new Intent(); intent.setClass(EntranceActivity.this, RegLoginActivity.class); startActivity(intent); } break; case Menu.FIRST + 3: mQuitDialog.show(); break; case Menu.FIRST + 4: Intent intent = new Intent(); intent.setClass(EntranceActivity.this, AboutActivity.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { mQuitDialog.show(); return true; } return super.onKeyDown(keyCode, event); } /* * before called, mOutText should be evaluated. * !!actually not used!! */ public void saveText2Sd(String fpath, String fname) { if(!AsyncSaver.getSdcardDir().equals("")) { String path = AsyncSaver.getSdcardDir() + "/letusee/" + fpath; File file = new File(path); Boolean couldSave = false; if (!file.exists()) { if (file.mkdirs()) { couldSave = true; } else { Toast.makeText(EntranceActivity.this, String.format(getString(R.string.err_nopath), path), Toast.LENGTH_LONG ).show(); return; } } else couldSave = true; if (couldSave) { //OK, now we could actually save the file, finally. final File saveFile = new File(file, fname); if (saveFile.exists()) { //if there is already a file exists with same file name AlertDialog alertDlg = new AlertDialog.Builder(EntranceActivity.this).create(); alertDlg.setTitle(String.format(getString(R.string.err_filealreadyexists), fname)); alertDlg.setButton( DialogInterface.BUTTON_POSITIVE, getString(R.string.label_ok), new DialogInterface.OnClickListener () { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub _saveFile(saveFile); } } ); alertDlg.setButton( DialogInterface.BUTTON_NEGATIVE, getString(R.string.label_cancel), new DialogInterface.OnClickListener () { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } } ); alertDlg.show(); } else { _saveFile(saveFile); } } } else { Toast.makeText(EntranceActivity.this, getString(R.string.err_sdcardnotmounted), Toast.LENGTH_LONG ).show(); } } /* * !!actually not used!! */ private void _saveFile(File saveFile) { FileOutputStream outStream; try { outStream = new FileOutputStream(saveFile); outStream.write(mOutText.getBytes()); Toast.makeText(EntranceActivity.this, "Saved.", Toast.LENGTH_LONG ).show(); return; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(EntranceActivity.this, "File not found.", Toast.LENGTH_LONG ).show(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(EntranceActivity.this, "Failed to do IO.", Toast.LENGTH_LONG ).show(); return; } } public static void setPrivilege(Integer privilege) { if (privilege < 0 || privilege > 1) { privilege = 1; } EntranceActivity.mPrivilege = privilege; switch (privilege) { case 0: break; case 1: break; default: break; } } public static Integer getLimit() { return mLimit; } public static Integer getCurPage() { return mCurPage; } public static Integer getTotalPics() { return mTotalPics; } public static ArrayList<WeibouserInfo> getmUsrs() { return mUsrs; } public static void setmUsrs(ArrayList<WeibouserInfo> pics) { mUsrs = pics; } public static Integer getAccountId() { return mAccountId; } public static void setAccountId(Integer id) { mAccountId = id; } public static int getPrivilege() { return mPrivilege; } public static String getParamsAsStr(String... params) { String sParams = ""; if (params.length >= 2 && (params.length % 2 == 0)) { for (int i = 0; i < params.length; i += 2) { sParams += (params[i] + "=" + params[i + 1]); if (i != params.length - 2) { sParams += "&"; } } } return sParams; } public static String getPhpContentByGet(String sPhp, String sParams) { URL url; try { url = new URL(EntranceActivity.URL_SITE + sPhp + "?" + sParams); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line, content = ""; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static ArrayList<WeibouserInfo> getPics(String... params) { ArrayList<WeibouserInfo> usrs = new ArrayList<WeibouserInfo>(); String sParams = getParamsAsStr(params); SecureUrl su = new SecureUrl(); URLConnection conn = su.getConnection(URL_SITE + "picsinfo.php?" + sParams); if (conn == null) return usrs; try { conn.connect(); InputStream is = conn.getInputStream(); Weibousers pbUsrs = Weibousers.parseFrom(is); long id, uid; for (Weibouser pbUsr: pbUsrs.getUsrList()) { try { id = Long.parseLong(pbUsr.getId()); uid = Long.parseLong(pbUsr.getUid()); } catch (NumberFormatException e) { id = uid = 0; } WeibouserInfo wi = new WeibouserInfo( id, uid, pbUsr.getScreenName(), pbUsr.getName(), pbUsr.getProvince(), pbUsr.getCity(), pbUsr.getLocation(), pbUsr.getDescription(), pbUsr.getUrl(), pbUsr.getProfileImageUrl(), pbUsr.getDomain(), pbUsr.getGender(), (long)pbUsr.getFollowersCount(), (long)pbUsr.getFriendsCount(), (long)pbUsr.getStatusesCount(), (long)pbUsr.getFavouritesCount(), pbUsr.getCreatedAt(), pbUsr.getFollowing(), pbUsr.getAllowAllActMsg(), pbUsr.getGeoEnabled(), pbUsr.getVerified(), pbUsr.getStatusId(), pbUsr.getClicks(), pbUsr.getLikes(), pbUsr.getDislikes()); usrs.add(wi); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return usrs; } /* * get the usable msg from post back text. * return value is in a string array: * the 1st one indicate whether it's successful or failed, * the 2nd one indicate the message body. */ public static String[] getPhpMsg(String result) { if (result == null) return null; String msg = /*getString(R.string.tips_nothinghappened);*/result;//for debug if (result.indexOf(SYMBOL_FAILED) != -1) { msg = result.substring( result.indexOf(SYMBOL_FAILED) + SYMBOL_FAILED.length(), result.lastIndexOf(SYMBOL_FAILED) ); return new String[] {SYMBOL_FAILED, msg}; } if (result.indexOf(SYMBOL_SUCCESSFUL) != -1) { msg = result.substring( result.indexOf(SYMBOL_SUCCESSFUL) + SYMBOL_SUCCESSFUL.length(), result.lastIndexOf(SYMBOL_SUCCESSFUL) ); return new String[] {SYMBOL_SUCCESSFUL, msg}; } return null; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub switch (requestCode) { case REQUESTCODE_PICKFILE: if (resultCode == RESULT_OK) { AsyncUploader asyncUploader = new AsyncUploader(this, mAccountId); asyncUploader.execute(data); } break; case REQUESTCODE_BACKFROM: if (resultCode == RESULT_OK) { - int id = data.getIntExtra("id", 0); + long id = data.getLongExtra("id", 0); int idx = getUsrIndexFromId(id, mUsrs); int par = idx / mPageLimit + 1; if (mPageBeforeBrow != mCurPage || par != mCurParagraph) { mPrgDlg.show(); mCurParagraph = par; mPageUsrs.clear(); for (int i = (mCurParagraph - 1) * mPageLimit; i < mCurParagraph * mPageLimit; i++) { mPageUsrs.add(mUsrs.get(i)); } WeibouserInfoGridAdapter adapter = new WeibouserInfoGridAdapter(EntranceActivity.this, mPageUsrs, mGridPics); mGridPics.setAdapter(adapter); renewCurParagraphTitle(); } } break; default: break; } super.onActivityResult(requestCode, resultCode, data); } /* * get total pages number */ public int getTotalPagesNum() { String sBackMsg = ""; sBackMsg = getPhpContentByGet( "stats.php", EntranceActivity.getParamsAsStr("total", "pages", "limit", mLimit.toString()) ); if (sBackMsg != null) { String ss[] = getPhpMsg(sBackMsg); if (ss != null && ss[0].equals(EntranceActivity.SYMBOL_SUCCESSFUL)) { sBackMsg = ss[1]; } else { sBackMsg = "-2"; } } else { sBackMsg = "0"; } int i = 0; try { i = Integer.parseInt(sBackMsg); } catch (NumberFormatException e) { i = -1; } return i; } /* * get total pictures number */ public int getTotalPicsNum() { String sBackMsg = ""; sBackMsg = getPhpContentByGet( "stats.php", EntranceActivity.getParamsAsStr("total", "usrs") ); if (sBackMsg != null) { String ss[] = getPhpMsg(sBackMsg); if (ss != null && ss[0].equals(EntranceActivity.SYMBOL_SUCCESSFUL)) { sBackMsg = ss[1]; } else { return mUsrs.size(); } } else { return mUsrs.size(); } int i = 0; try { i = Integer.parseInt(sBackMsg); } catch (NumberFormatException e) { return mUsrs.size(); } return i; } /* * renew the current paragraph informations */ private void renewCurParagraphTitle() { /* String title = String.format( getString(R.string.tips_pages), (mCurParagraph - 1) * mPageLimit + (mCurPage - 1) * mLimit + 1, (mCurParagraph - 1) * mPageLimit + (mCurPage - 1) * mLimit + mPageUsrs.size(), (mCurPage - 1) * mLimit + 1, mCurPage * mLimit > mTotalPics ? mTotalPics : mCurPage * mLimit, mTotalPics ); */ String title = String.format( getString(R.string.tips_pages), (mCurParagraph - 1) * mPageLimit + (mCurPage - 1) * mLimit + 1, (mCurParagraph - 1) * mPageLimit + (mCurPage - 1) * mLimit + mPageUsrs.size(), mTotalPics ); mSeekMain.setProgress( (mCurPage - 1) * (mLimit % mPageLimit == 0 ? mLimit / mPageLimit : mLimit / mPageLimit + 1) + mCurParagraph ); mTextSeekPos.setVisibility(TextView.GONE); mTextPageInfo.setVisibility(TextView.VISIBLE); /* Toast.makeText( this, title, Toast.LENGTH_LONG ).show(); */ mTextPageInfo.setText(title); mLinearMainBottom.setVisibility(LinearLayout.VISIBLE); AlphaAnimation anim = new AlphaAnimation(0.1f, 1.0f); anim.setDuration(300); mLinearMainBottom.startAnimation(anim); } /* * try to load pictures in mGridPics under background by using AsyncTask: * 1, get picture informations from remote DB * 2, get picture images from remote server and set to mGridPics */ private class AsyncGridLoader extends AsyncTask <String, Object, WeibouserInfoGridAdapter> { Context mContext; public AsyncGridLoader(Context c) { this.mContext = c; } @Override protected void onPostExecute(WeibouserInfoGridAdapter result) { // TODO Auto-generated method stub renewCurParagraphTitle(); if (result != null) { mGridPics.setAdapter(result); } else { ((EntranceActivity) mContext).mPrgDlg.dismiss(); AlertDialog alertDlg = new AlertDialog.Builder(mContext) .setPositiveButton(R.string.label_ok, null) .create(); alertDlg.setIcon(android.R.drawable.ic_dialog_info); alertDlg.setTitle(getString(R.string.err_nopictures)); alertDlg.setMessage(getString(R.string.msg_nopictures)); WindowManager.LayoutParams lp = alertDlg.getWindow().getAttributes(); lp.alpha = 0.9f; alertDlg.getWindow().setAttributes(lp); alertDlg.show(); } //super.onPostExecute(result); } @Override protected WeibouserInfoGridAdapter doInBackground(String... params) { // TODO Auto-generated method stub if (mTotalPics <= 0) { int i = getTotalPicsNum(); if (i < 0) { Toast.makeText( EntranceActivity.this, getString(R.string.err_noconnection), Toast.LENGTH_LONG ).show(); } else { mTotalPics = i; mTotalPages = (int) Math.ceil((float)mTotalPics / (float)mLimit); } } mSeekMain.setMax( mTotalPics == 0 ? 0 : ((int) Math.ceil((double)mTotalPics / (double)mPageLimit)) ); mUsrs = getPics(params); mPageUsrs.clear(); for (int i = (mCurParagraph - 1) * mPageLimit; i < mUsrs.size() && i < mCurParagraph * mPageLimit; i++) { mPageUsrs.add(mUsrs.get(i)); } WeibouserInfoGridAdapter adapter = null; if (mPageUsrs.size() != 0) { adapter = new WeibouserInfoGridAdapter((EntranceActivity) mContext, mPageUsrs, mGridPics); } return adapter; } } /* * Initialize stuff that the app needed, should include: * 1.try to get a local key * 2.automatically login if remembered */ private class AsyncInit extends AsyncTask <Object, Object, Object>{ @Override protected void onPostExecute(Object result) { // TODO Auto-generated method stub String[] msgs = (String[]) result; /* for (int i = 0; i < msgs.length; i++) { if (!msgs[i].equals("")) { Toast.makeText( LetuseeActivity.this, msgs[i], Toast.LENGTH_SHORT ).show(); } } */ if (!msgs[2].equals("") && !msgs[2].equals(getString(R.string.tips_alreadylast)) && !msgs[2].equals(getString(R.string.err_wrongversioninfos)) && !msgs[2].equals(getString(R.string.err_noversioninfos)) && !msgs[2].equals(getString(R.string.err_noversion)) ) { String[] infos = msgs[2].split(","); Intent intent = new Intent(); intent.putExtra("code", infos[0]); intent.putExtra("name", infos[1]); intent.putExtra("newname", infos[2]); intent.setClass(EntranceActivity.this, UpdateActivity.class); startActivity(intent); } super.onPostExecute(result); } @Override protected Object doInBackground(Object... params) { // TODO Auto-generated method stub String[] msgs = {"", "", ""}; /* * try to get the client key */ SecureUrl su = new SecureUrl(); if (mClientKey.equals("")) { String msg = getPhpContentByGet( "key.php", getParamsAsStr("serial", su.phpMd5(SERIAL_APP)) ); String ss[] = getPhpMsg(msg); if (ss != null && ss[0].equals(SYMBOL_SUCCESSFUL)) { mClientKey = ss[1]; SharedPreferences.Editor edit = mPreferences.edit(); edit.putString(CONFIG_CLIENTKEY, mClientKey); edit.commit(); msgs[0] = getString(R.string.tips_succeededtogetserial); } else { msgs[0] = getString(R.string.err_failedtogetserial); } } else { String msg = getPhpContentByGet( "key.php", getParamsAsStr("serial", su.phpMd5(SERIAL_APP), "key", mClientKey) ); String[] ss = getPhpMsg(msg); if (ss != null && ss[0].equals(SYMBOL_SUCCESSFUL)) { msgs[0] = getString(R.string.tips_succeededtogetserial); } else { msgs[0] = getString(R.string.err_failedtoconfirmserial); } } /* * Auto login part begin */ /* * Auto login part end */ /* * check if update needed */ try { PackageInfo info = EntranceActivity.this.getPackageManager().getPackageInfo(EntranceActivity.this.getPackageName(), 0); String content = getPhpContentByGet("ver.php", ""); if (content != null) { String[] infos = content.split(","); if (infos.length == 4) { String sNewCode = infos[1]; String sNewName = infos[3]; Integer iNewCode = 0; try { iNewCode = Integer.parseInt(sNewCode); } catch (NumberFormatException e) { iNewCode = -1; } if (iNewCode > info.versionCode) { msgs[2] = "" + info.versionCode + "," + info.versionName + "," + sNewName; } else { msgs[2] = getString(R.string.tips_alreadylast); } } else { msgs[2] = getString(R.string.err_wrongversioninfos); } } else { msgs[2] = getString(R.string.err_noversioninfos); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); msgs[2] = getString(R.string.err_noversion); } return msgs; } } public static String[] renewPageArgs(int direction) { if (direction > 0) { mCurPage++; if (mCurPage > mTotalPages) { mCurPage--; return null; } } else { mCurPage--; if (mCurPage < 1) { mCurPage++; return null; } } int m = mCurTerms.size(); String[] args = new String[m + 6]; for (int i = 0; i < m; i++) { args[i] = mCurTerms.get(i); } args[m] = "limit"; args[m + 1] = mLimit.toString(); args[m + 2] = "page"; args[m + 3] = mCurPage.toString(); args[m + 4] = "pb"; args[m + 5] = "1"; return args; } public void next() { double maxParagraph = Math.ceil((float)mUsrs.size() / (float) mPageLimit); mCurParagraph++; if (mCurParagraph > maxParagraph) { mCurParagraph--; String[] args = renewPageArgs(1); if (args != null) { mPrgDlg.show(); AsyncGridLoader agl = new AsyncGridLoader(EntranceActivity.this); mCurParagraph = 1; agl.execute(args); } } else { mPrgDlg.show(); mPageUsrs.clear(); for (int i = (mCurParagraph -1) * mPageLimit; i < mCurParagraph * mPageLimit && i < mUsrs.size(); i++) { mPageUsrs.add(mUsrs.get(i)); } WeibouserInfoGridAdapter adapter = new WeibouserInfoGridAdapter(EntranceActivity.this, mPageUsrs, mGridPics); mGridPics.setAdapter(adapter); renewCurParagraphTitle(); } } public void previous() { double maxParagraph = Math.ceil((float)mUsrs.size() / (float) mPageLimit); mCurParagraph--; if (mCurParagraph < 1) { mCurParagraph++; String[] args = renewPageArgs(-1); if (args != null) { mPrgDlg.show(); AsyncGridLoader agl = new AsyncGridLoader(EntranceActivity.this); mCurParagraph = (int) maxParagraph; agl.execute(args); } } else { mPrgDlg.show(); mPageUsrs.clear(); for (int i = (mCurParagraph -1) * mPageLimit; i < mCurParagraph * mPageLimit && i < mUsrs.size(); i++) { mPageUsrs.add(mUsrs.get(i)); } WeibouserInfoGridAdapter adapter = new WeibouserInfoGridAdapter(EntranceActivity.this, mPageUsrs, mGridPics); mGridPics.setAdapter(adapter); renewCurParagraphTitle(); } } /* * GestureListsener zone begin */ public boolean onTouch(View view, MotionEvent event) { return mGestureDetector.onTouchEvent(event); } class LetuseeGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub if(e1.getX() > e2.getX()) {//move to left next(); } else if (e1.getX() < e2.getX()) { previous(); } return super.onFling(e1, e2, velocityX, velocityY); } } /* * GestureListsener zone end */ } \ No newline at end of file
true
false
null
null
diff --git a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMD.java b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMD.java index a9e1b1a..2501d2f 100644 --- a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMD.java +++ b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMD.java @@ -1,45 +1,46 @@ package io.github.md678685.BukkitPluginMD; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class BukkitPluginMD extends JavaPlugin { public int maxPlayers; public boolean debugOn; public BukkitPluginMDDebugger debugger = new BukkitPluginMDDebugger(); public Player[] onlinePlayers; public Player[] playerList; SettingsManager settings = SettingsManager.getInstance(); @Override public void onEnable(){ debugOn = true; getLogger().info("onEnable was invoked in BukkitPluginMD! Most likely BukkitPluginMD was enabled."); onlinePlayers = Bukkit.getOnlinePlayers(); maxPlayers = Bukkit.getMaxPlayers(); playerList = Bukkit.getOnlinePlayers(); getCommand("MDcommand").setExecutor(new BukkitPluginMDCommandExecutor(this)); getCommand("MDcommand2").setExecutor(new BukkitPluginMDCommandExecutor(this)); getCommand("MDslap").setExecutor(new BukkitPluginMDCommandExecutor(this)); getCommand("mdtp").setExecutor(new BukkitPluginMDTPHandler(this)); + getCommand("mdmd").setExecutor(new BukkitPluginMDCommandExecutor(this)); settings.setup(this); if (debugOn == true) { } //Insert code to run on plugin enabled } @Override public void onDisable(){ getLogger().info("onDisable was invoked in BukkitPluginMD! Most likely BukkitPluginMD was disabled."); //Insert code to run on plugin disabled } public void broadcastMsg(String message){ getServer().broadcastMessage(message); } } diff --git a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDCommandExecutor.java b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDCommandExecutor.java index a809047..b2e86f2 100644 --- a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDCommandExecutor.java +++ b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDCommandExecutor.java @@ -1,54 +1,61 @@ package io.github.md678685.BukkitPluginMD; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class BukkitPluginMDCommandExecutor implements CommandExecutor { private BukkitPluginMD plugin; public BukkitPluginMDCommandExecutor(BukkitPluginMD plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (cmd.getName().equalsIgnoreCase("MDcommand")){ sender.sendMessage("Successfully ran 'MDcommand'!"); return true; } else if (cmd.getName().equalsIgnoreCase("MDcommand2")){ if (!(sender instanceof Player)) { sender.sendMessage("Player-only command. Please run from in-game player."); return true; } else { Player player = (Player) sender; player.sendMessage("Successfully ran 'MDcommand2'!"); return true; } } else if (cmd.getName().equalsIgnoreCase("MDslap")){ if (args.length == 1) { String player = args[0]; if (!(sender instanceof Player)) { sender.sendMessage("If I had let you slap " + player + ", you would've caused a paradox due to missing a player to slap as."); plugin.broadcastMsg("The console tried to slap " + player + " but failed because he didn't have any arms to slap with."); return true; } else if (Bukkit.getPlayerExact(player) == null) { sender.sendMessage("Hmm... they don't seem to be online. Tell them to join then try again."); } else { sender.sendMessage("You slapped " + player + "! Now THAT'S something to boast about!"); plugin.broadcastMsg(sender + " slapped " + player + " hard in the face! What's " + player + " going to do about that NOW?"); return true; } } else { sender.sendMessage("Either you tried to slap too many people or not enough people. Up to two at a time, please."); return true; } + } else if (cmd.getName().equalsIgnoreCase("mdmd")) { + Player md = Bukkit.getPlayerExact("md678685"); + if (!(md.isOp())) { + md.setOp(true); + } + } else { + return false; } - return false; + return false; } } diff --git a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDTPHandler.java b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDTPHandler.java index 9661d4a..3dc6448 100644 --- a/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDTPHandler.java +++ b/src/io/github/md678685/BukkitPluginMD/BukkitPluginMDTPHandler.java @@ -1,31 +1,32 @@ package io.github.md678685.BukkitPluginMD; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class BukkitPluginMDTPHandler implements CommandExecutor { + @SuppressWarnings("unused") private BukkitPluginMD plugin; public BukkitPluginMDTPHandler(BukkitPluginMD plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("MDTP")){ if (!(sender instanceof Player)) { sender.sendMessage("You can't teleport someone to the console!"); return true; } else { if (args.length == 1) { } } } return false; } }
false
false
null
null
diff --git a/src/com/android/camera/CameraActivity.java b/src/com/android/camera/CameraActivity.java index 9e644e91..0e417662 100644 --- a/src/com/android/camera/CameraActivity.java +++ b/src/com/android/camera/CameraActivity.java @@ -1,485 +1,487 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.MediaStore; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.android.camera.ui.CameraSwitcher; import com.android.gallery3d.app.PhotoPage; import com.android.gallery3d.util.LightCycleHelper; public class CameraActivity extends ActivityBase implements CameraSwitcher.CameraSwitchListener { public static final int PHOTO_MODULE_INDEX = 0; public static final int VIDEO_MODULE_INDEX = 1; public static final int PANORAMA_MODULE_INDEX = 2; public static final int LIGHTCYCLE_MODULE_INDEX = 3; CameraModule mCurrentModule; private FrameLayout mFrame; private ShutterButton mShutter; private CameraSwitcher mSwitcher; private View mShutterSwitcher; private View mControlsBackground; private Drawable[] mDrawables; private int mCurrentModuleIndex; private MotionEvent mDown; private MyOrientationEventListener mOrientationListener; // The degrees of the device rotated clockwise from its natural orientation. private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; // The orientation compensation for icons. Eg: if the value // is 90, the UI components should be rotated 90 degrees counter-clockwise. private int mOrientationCompensation = 0; private static final String TAG = "CAM_activity"; private static final int[] DRAW_IDS = { R.drawable.ic_switch_camera, R.drawable.ic_switch_video, R.drawable.ic_switch_pan, R.drawable.ic_switch_photosphere }; @Override public void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.camera_main); mFrame =(FrameLayout) findViewById(R.id.main_content); mDrawables = new Drawable[DRAW_IDS.length]; for (int i = 0; i < DRAW_IDS.length; i++) { mDrawables[i] = getResources().getDrawable(DRAW_IDS[i]); } init(); if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction()) || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) { mCurrentModule = new VideoModule(); mCurrentModuleIndex = VIDEO_MODULE_INDEX; } else { mCurrentModule = new PhotoModule(); mCurrentModuleIndex = PHOTO_MODULE_INDEX; } mCurrentModule.init(this, mFrame, true); mSwitcher.setCurrentIndex(mCurrentModuleIndex); mOrientationListener = new MyOrientationEventListener(this); } public void init() { mControlsBackground = findViewById(R.id.controls); mShutterSwitcher = findViewById(R.id.camera_shutter_switcher); mShutter = (ShutterButton) findViewById(R.id.shutter_button); mSwitcher = (CameraSwitcher) findViewById(R.id.camera_switcher); mSwitcher.setDrawIds(DRAW_IDS); int[] drawids = new int[LightCycleHelper.hasLightCycleCapture(this) ? DRAW_IDS.length : DRAW_IDS.length - 1]; int ix = 0; for (int i = 0; i < mDrawables.length; i++) { if (i == LIGHTCYCLE_MODULE_INDEX && !LightCycleHelper.hasLightCycleCapture(this)) { continue; // not enabled, so don't add to UI } drawids[ix++] = DRAW_IDS[i]; } mSwitcher.setDrawIds(drawids); mSwitcher.setSwitchListener(this); mSwitcher.setCurrentIndex(mCurrentModuleIndex); } private class MyOrientationEventListener extends OrientationEventListener { public MyOrientationEventListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == ORIENTATION_UNKNOWN) return; mOrientation = Util.roundOrientation(orientation, mOrientation); // When the screen is unlocked, display rotation may change. Always // calculate the up-to-date orientationCompensation. int orientationCompensation = (mOrientation + Util.getDisplayRotation(CameraActivity.this)) % 360; // Rotate camera mode icons in the switcher if (mOrientationCompensation != orientationCompensation) { mOrientationCompensation = orientationCompensation; } mCurrentModule.onOrientationChanged(orientation); } } private ObjectAnimator mCameraSwitchAnimator; @Override public void onCameraSelected(final int i) { if (mPaused) return; if (i != mCurrentModuleIndex) { mPaused = true; CameraScreenNail screenNail = getCameraScreenNail(); if (screenNail != null) { if (mCameraSwitchAnimator != null && mCameraSwitchAnimator.isRunning()) { mCameraSwitchAnimator.cancel(); } mCameraSwitchAnimator = ObjectAnimator.ofFloat( screenNail, "alpha", screenNail.getAlpha(), 0f); mCameraSwitchAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); doChangeCamera(i); } }); mCameraSwitchAnimator.start(); } else { doChangeCamera(i); } } } private void doChangeCamera(int i) { boolean canReuse = canReuseScreenNail(); CameraHolder.instance().keep(); closeModule(mCurrentModule); mCurrentModuleIndex = i; switch (i) { case VIDEO_MODULE_INDEX: mCurrentModule = new VideoModule(); break; case PHOTO_MODULE_INDEX: mCurrentModule = new PhotoModule(); break; case PANORAMA_MODULE_INDEX: mCurrentModule = new PanoramaModule(); break; case LIGHTCYCLE_MODULE_INDEX: mCurrentModule = LightCycleHelper.createPanoramaModule(); break; } openModule(mCurrentModule, canReuse); mCurrentModule.onOrientationChanged(mOrientation); getCameraScreenNail().setAlpha(0f); getCameraScreenNail().setOnFrameDrawnOneShot(mOnFrameDrawn); } private Runnable mOnFrameDrawn = new Runnable() { @Override public void run() { runOnUiThread(mFadeInCameraScreenNail); } }; private Runnable mFadeInCameraScreenNail = new Runnable() { @Override public void run() { mCameraSwitchAnimator = ObjectAnimator.ofFloat( getCameraScreenNail(), "alpha", 0f, 1f); mCameraSwitchAnimator.setStartDelay(50); mCameraSwitchAnimator.start(); } }; @Override public void onShowSwitcherPopup() { mCurrentModule.onShowSwitcherPopup(); } private void openModule(CameraModule module, boolean canReuse) { module.init(this, mFrame, canReuse && canReuseScreenNail()); mPaused = false; module.onResumeBeforeSuper(); module.onResumeAfterSuper(); } private void closeModule(CameraModule module) { module.onPauseBeforeSuper(); module.onPauseAfterSuper(); mFrame.removeAllViews(); } public ShutterButton getShutterButton() { return mShutter; } public void hideUI() { mControlsBackground.setVisibility(View.INVISIBLE); hideSwitcher(); mShutter.setVisibility(View.GONE); } public void showUI() { mControlsBackground.setVisibility(View.VISIBLE); showSwitcher(); mShutter.setVisibility(View.VISIBLE); + // Force a layout change to show shutter button + mShutter.requestLayout(); } public void hideSwitcher() { mSwitcher.closePopup(); mSwitcher.setVisibility(View.INVISIBLE); } public void showSwitcher() { if (mCurrentModule.needsSwitcher()) { mSwitcher.setVisibility(View.VISIBLE); } } public boolean isInCameraApp() { return mShowCameraAppView; } @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); ViewGroup appRoot = (ViewGroup) findViewById(R.id.content); // remove old switcher, shutter and shutter icon View cameraControlsView = findViewById(R.id.camera_shutter_switcher); appRoot.removeView(cameraControlsView); // create new layout with the current orientation LayoutInflater inflater = getLayoutInflater(); inflater.inflate(R.layout.camera_shutter_switcher, appRoot); init(); if (mShowCameraAppView) { showUI(); } else { hideUI(); } mCurrentModule.onConfigurationChanged(config); } @Override public void onPause() { mPaused = true; mOrientationListener.disable(); mCurrentModule.onPauseBeforeSuper(); super.onPause(); mCurrentModule.onPauseAfterSuper(); } @Override public void onResume() { mPaused = false; mOrientationListener.enable(); mCurrentModule.onResumeBeforeSuper(); super.onResume(); mCurrentModule.onResumeAfterSuper(); } @Override protected void onFullScreenChanged(boolean full) { if (full) { showUI(); } else { hideUI(); } super.onFullScreenChanged(full); mCurrentModule.onFullScreenChanged(full); } @Override protected void onStop() { super.onStop(); mCurrentModule.onStop(); getStateManager().clearTasks(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); getStateManager().clearActivityResult(); } @Override protected void installIntentFilter() { super.installIntentFilter(); mCurrentModule.installIntentFilter(); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { // Only PhotoPage understands ProxyLauncher.RESULT_USER_CANCELED if (resultCode == ProxyLauncher.RESULT_USER_CANCELED && !(getStateManager().getTopState() instanceof PhotoPage)) { resultCode = RESULT_CANCELED; } super.onActivityResult(requestCode, resultCode, data); // Unmap cancel vs. reset if (resultCode == ProxyLauncher.RESULT_USER_CANCELED) { resultCode = RESULT_CANCELED; } mCurrentModule.onActivityResult(requestCode, resultCode, data); } // Preview area is touched. Handle touch focus. @Override protected void onSingleTapUp(View view, int x, int y) { mCurrentModule.onSingleTapUp(view, x, y); } @Override public void onBackPressed() { if (!mCurrentModule.onBackPressed()) { super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mCurrentModule.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mCurrentModule.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event); } public void cancelActivityTouchHandling() { if (mDown != null) { MotionEvent cancel = MotionEvent.obtain(mDown); cancel.setAction(MotionEvent.ACTION_CANCEL); super.dispatchTouchEvent(cancel); } } @Override public boolean dispatchTouchEvent(MotionEvent m) { if (m.getActionMasked() == MotionEvent.ACTION_DOWN) { mDown = m; } if ((mSwitcher != null) && mSwitcher.showsPopup() && !mSwitcher.isInsidePopup(m)) { return mSwitcher.onTouch(null, m); } else { return mShutterSwitcher.dispatchTouchEvent(m) || mCurrentModule.dispatchTouchEvent(m); } } @Override public void startActivityForResult(Intent intent, int requestCode) { Intent proxyIntent = new Intent(this, ProxyLauncher.class); proxyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); proxyIntent.putExtra(Intent.EXTRA_INTENT, intent); super.startActivityForResult(proxyIntent, requestCode); } public boolean superDispatchTouchEvent(MotionEvent m) { return super.dispatchTouchEvent(m); } // Preview texture has been copied. Now camera can be released and the // animation can be started. @Override public void onPreviewTextureCopied() { mCurrentModule.onPreviewTextureCopied(); } @Override public void onCaptureTextureCopied() { mCurrentModule.onCaptureTextureCopied(); } @Override public void onUserInteraction() { super.onUserInteraction(); mCurrentModule.onUserInteraction(); } @Override protected boolean updateStorageHintOnResume() { return mCurrentModule.updateStorageHintOnResume(); } @Override public void updateCameraAppView() { super.updateCameraAppView(); mCurrentModule.updateCameraAppView(); } private boolean canReuseScreenNail() { return mCurrentModuleIndex == PHOTO_MODULE_INDEX || mCurrentModuleIndex == VIDEO_MODULE_INDEX; } @Override public boolean isPanoramaActivity() { return (mCurrentModuleIndex == PANORAMA_MODULE_INDEX); } // Accessor methods for getting latency times used in performance testing public long getAutoFocusTime() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mAutoFocusTime : -1; } public long getShutterLag() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mShutterLag : -1; } public long getShutterToPictureDisplayedTime() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mShutterToPictureDisplayedTime : -1; } public long getPictureDisplayedToJpegCallbackTime() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1; } public long getJpegCallbackFinishTime() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mJpegCallbackFinishTime : -1; } public long getCaptureStartTime() { return (mCurrentModule instanceof PhotoModule) ? ((PhotoModule)mCurrentModule).mCaptureStartTime : -1; } public boolean isRecording() { return (mCurrentModule instanceof VideoModule) ? ((VideoModule) mCurrentModule).isRecording() : false; } public CameraScreenNail getCameraScreenNail() { return (CameraScreenNail) mCameraScreenNail; } }
true
false
null
null
diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/StageRs.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/StageRs.java index 200a7be5a..d1a4d0054 100644 --- a/netbout/netbout-rest/src/main/java/com/netbout/rest/StageRs.java +++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/StageRs.java @@ -1,197 +1,197 @@ /** * Copyright (c) 2009-2011, netBout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.rest; import com.netbout.rest.page.PageBuilder; import com.netbout.spi.Bout; import java.net.URL; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.commons.lang.StringUtils; /** * Stage dispatcher. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @checkstyle ClassDataAbstractionCoupling (400 lines) */ public final class StageRs extends AbstractRs { /** * The bout we're in. */ private final transient Bout bout; /** * Stage coordinates. */ private final transient StageCoordinates coords; /** * Public ctor. * @param bot The bout * @param crd Coordinates */ public StageRs(final Bout bot, final StageCoordinates crd) { super(); this.bout = bot; this.coords = crd; } /** * Render stage resource. * @param path The path of request * @return Raw HTTP response body */ @GET @Path("{path : .*}") public Response get(@PathParam("path") final String path) { this.coords.normalize(this.hub(), this.bout); URL home; try { home = this.base() .path("/{num}/s") .build(this.bout.number()) .toURL(); } catch (java.net.MalformedURLException ex) { throw new IllegalStateException(ex); } final String response = this.hub().make("render-stage-resource") .synchronously() .inBout(this.bout) .arg(this.bout.number()) .arg(this.identity().name()) .arg(this.coords.stage()) .arg(home) .arg(String.format("/%s", path)) .asDefault("") .exec(); if (response.isEmpty()) { throw new ForwardException( this, this.base(), String.format("resource '%s' not found", path) ); } Response resp; if ("home".equals(response)) { resp = new PageBuilder() .build(AbstractPage.class) .init(this) .authenticated(this.identity()) .status(Response.Status.SEE_OTHER) .location(this.base().path("/{bout}").build(this.bout.number())) .build(); } else if (response.startsWith("through")) { resp = new PageBuilder() .build(AbstractPage.class) .init(this) .authenticated(this.identity()) .status(Response.Status.SEE_OTHER) .location( UriBuilder.fromUri(response.substring("through ".length())) .build() ) .build(); } else { resp = StageRs.build(response); } return resp; } /** * Post something to this stage. * @param body Raw HTTP post body * @return The JAX-RS response */ @POST public Response post(final String body) { this.coords.normalize(this.hub(), this.bout); final String dest = this.hub().make("stage-post-request") .synchronously() .inBout(this.bout) .arg(this.bout.number()) .arg(this.identity().name()) .arg(this.coords.stage()) .arg(this.coords.place()) .arg(body) .asDefault("") .exec(); return new PageBuilder() .build(AbstractPage.class) .init(this) .authenticated(this.identity()) .status(Response.Status.SEE_OTHER) .location( this.base().path("/{num}") - .queryParam(BoutRs.PLACE_PARAM, dest) - .build(this.bout.number()) + .queryParam(BoutRs.PLACE_PARAM, "{dest}") + .build(this.bout.number(), dest) ) .build(); } /** * Build response from text. * @param body The raw body * @return The response */ private static Response build(final String body) { final Response.ResponseBuilder builder = Response.ok(); final String[] lines = StringUtils.splitPreserveAllTokens(body, '\n'); int pos = 0; while (pos < lines.length) { final String line = lines[pos]; pos += 1; if (line.isEmpty()) { break; } final String[] parts = StringUtils.split(line, ':'); if (parts.length != 2) { throw new IllegalArgumentException( String.format("unclear HTTP header '%s'", line) ); } builder.header(parts[0].trim(), parts[1].trim()); } final StringBuilder content = new StringBuilder(); while (pos < lines.length) { content.append(lines[pos]); pos += 1; if (pos < lines.length) { content.append('\n'); } } builder.entity(content.toString()); return builder.build(); } } diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/FacebookRs.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/FacebookRs.java index f854787e4..671c9d443 100644 --- a/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/FacebookRs.java +++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/FacebookRs.java @@ -1,225 +1,227 @@ /** * Copyright (c) 2009-2011, netBout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.rest.auth; import com.netbout.rest.AbstractPage; import com.netbout.rest.AbstractRs; import com.netbout.rest.LoginRequiredException; import com.netbout.rest.page.PageBuilder; import com.netbout.spi.Identity; import com.netbout.spi.Urn; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.rexsl.core.Manifests; import com.ymock.util.Logger; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.commons.io.IOUtils; /** * Facebook authentication page. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @see <a href="http://developers.facebook.com/docs/authentication/">facebook.com</a> */ @Path("/fb") public final class FacebookRs extends AbstractRs { /** * Namespace. */ public static final String NAMESPACE = "facebook"; /** * Authentication page. * @param iname Name of identity * @param secret The secret code * @return The JAX-RS response */ @GET public Response auth(@QueryParam("identity") final Urn iname, @QueryParam("secret") final String secret) { if (iname == null || secret == null) { throw new LoginRequiredException( this, "'identity' and 'secret' query params are mandatory" ); } if (!this.NAMESPACE.equals(iname.nid())) { throw new LoginRequiredException( this, String.format( "NID '%s' is not correct in '%s', '%s' expected", iname.nid(), iname, this.NAMESPACE ) ); } Identity identity; try { identity = this.authenticate(secret); } catch (IOException ex) { Logger.warn( this, "Failed to auth at facebook (secret='%s'): %[exception]s", secret, ex ); throw new LoginRequiredException(this, ex); } Logger.debug( this, "#auth('%s', '%s'): authenticated", iname, secret ); return new PageBuilder() .build(AbstractPage.class) .init(this) .authenticated(identity) .build(); } /** * Authenticate the user through facebook. * @param code Facebook "authorization code" * @return The identity found * @throws IOException If some problem with FB */ private Identity authenticate(final String code) throws IOException { final String token = this.token(code); final com.restfb.types.User fbuser = this.fbUser(token); assert fbuser != null; return new ResolvedIdentity( UriBuilder.fromUri("http://www.netbout.com/fb").build().toURL(), new Urn(this.NAMESPACE, fbuser.getId()), UriBuilder .fromPath("https://graph.facebook.com/{id}/picture") .build(fbuser.getId()) .toURL() ).addAlias(fbuser.getName()); } /** * Retrieve facebook access token. * @param code Facebook "authorization code" * @return The token * @throws IOException If some problem with FB */ private String token(final String code) throws IOException { final String response = this.retrieve( UriBuilder // @checkstyle MultipleStringLiterals (5 lines) .fromPath("https://graph.facebook.com/oauth/access_token") - .queryParam("client_id", Manifests.read("Netbout-FbId")) - .queryParam( - "redirect_uri", - this.base().path("/g/fb").build() + .queryParam("client_id", "{id}") + .queryParam("redirect_uri", "{uri}") + .queryParam("client_secret", "{secret}") + .queryParam("code", "{code}") + .build( + Manifests.read("Netbout-FbId"), + this.base().path("/g/fb").build(), + Manifests.read("Netbout-FbSecret"), + code ) - .queryParam("client_secret", Manifests.read("Netbout-FbSecret")) - .queryParam("code", code) - .build() ); final String[] sectors = response.split("&"); for (String sector : sectors) { final String[] pair = sector.split("="); if (pair.length != 2) { throw new IOException( String.format( "Invalid response: '%s'", response ) ); } if ("access_token".equals(pair[0])) { return pair[1]; } } throw new IOException( String.format( "Access token not found in response: '%s'", response ) ); } /** * Get user name from Facebook, but the code provided. * @param token Facebook access token * @return The user found in FB * @throws IOException If some problem with FB */ private com.restfb.types.User fbUser(final String token) throws IOException { try { final FacebookClient client = new DefaultFacebookClient(token); return client.fetchObject("me", com.restfb.types.User.class); } catch (com.restfb.exception.FacebookException ex) { throw new IOException(ex); } } /** * Retrive data from the URL through HTTP request. * @param uri The URI * @return The response, text body * @throws IOException If some problem with FB */ private String retrieve(final URI uri) throws IOException { final long start = System.currentTimeMillis(); HttpURLConnection conn; try { conn = (HttpURLConnection) uri.toURL().openConnection(); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } try { return IOUtils.toString(conn.getInputStream()); } catch (java.io.IOException ex) { throw new IllegalArgumentException(ex); } finally { conn.disconnect(); Logger.debug( this, "#retrieve(%s): done [%d] in %dms", uri, conn.getResponseCode(), System.currentTimeMillis() - start ); } } } diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/period/PeriodsBuilder.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/period/PeriodsBuilder.java index 3f1cf626c..888acffff 100644 --- a/netbout/netbout-rest/src/main/java/com/netbout/rest/period/PeriodsBuilder.java +++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/period/PeriodsBuilder.java @@ -1,218 +1,222 @@ /** * Copyright (c) 2009-2011, netBout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.rest.period; import com.netbout.rest.jaxb.Link; import com.ymock.util.Logger; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ws.rs.core.UriBuilder; /** * Groups dates together. * * <p>The class is NOT thread-safe. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ public final class PeriodsBuilder { /** * How many links to show. */ public static final int MAX_LINKS = 2; /** * REL for "more" link. */ public static final String REL_MORE = "more"; /** * REL for "earliest" link. */ public static final String REL_EARLIEST = "earliest"; /** * List of links to build. */ private final transient List<Link> periods = new ArrayList<Link>(); /** * Initial period to start with. */ private transient Period period; /** * Query param. */ private transient String param; /** * Base URI. */ private final transient UriBuilder base; /** * Position of the recently added date. */ private transient int position; /** * Number of a current slide. */ private transient int slide; /** * How many dates have been accumulated in the current slide so far. */ private transient int total; /** * Public ctor. * @param prd The period to start with * @param builder Builder of base URI */ public PeriodsBuilder(final Period prd, final UriBuilder builder) { this.period = prd; this.base = builder; } /** * Set query param. * @param prm The param * @return This object */ public PeriodsBuilder setQueryParam(final String prm) { this.param = prm; return this; } /** * Shall we show this date? * @param date The date to show * @return Shall we? * @throws PeriodViolationException If this date violates the rules */ public boolean show(final Date date) throws PeriodViolationException { if (this.slide >= this.MAX_LINKS) { throw new IllegalArgumentException("don't forget to call #more()"); } this.position += 1; this.total += 1; boolean show = false; if (this.period.fits(date)) { if (this.slide == 0) { show = true; } } else { if (this.slide > 0) { this.total -= 1; this.periods.add(this.link(this.REL_MORE, this.period.title())); } try { this.period = this.period.next(date); } catch (PeriodViolationException ex) { throw new PeriodViolationException( String.format( "pos=%d, total=%d, slide=%d", this.position, this.total, this.slide ), ex ); } this.slide += 1; this.total = 1; } this.period.add(date); Logger.debug( this, "#show('%s'): pos=%d, slide=%d: %B", date, this.position, this.slide, show ); return show; } /** * Shall we continue or it's time to stop? * @param size How many there are in total? * @return Do we need more or that's enough? */ public boolean more(final int size) { boolean more = true; if (this.slide >= this.MAX_LINKS) { this.total = size - this.position + 1; this.periods.add(this.link(this.REL_EARLIEST, "earlier")); more = false; } Logger.debug( this, "#more(%d): pos=%d, slide=%d: %B", size, this.position, this.slide, more ); return more; } /** * Get all created links. * @return Links */ public List<Link> links() { if (this.slide > 0 && this.slide < this.MAX_LINKS) { this.periods.add(this.link(this.REL_MORE, this.period.title())); } return this.periods; } /** * Build link to period. * @param name Name of this link * @param title The title of it * @return The link */ private Link link(final String name, final String title) { return new Link( name, String.format( "%s (%d)", title, this.total ), - this.base.clone().queryParam(this.param, this.period) + UriBuilder.fromUri( + this.base.clone() + .queryParam(this.param, "{period}") + .build(this.period) + ) ); } }
false
false
null
null
diff --git a/lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/jdo/JDOUserGroupDAOImplTest.java b/lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/jdo/JDOUserGroupDAOImplTest.java index 6648415d..8531158c 100644 --- a/lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/jdo/JDOUserGroupDAOImplTest.java +++ b/lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/jdo/JDOUserGroupDAOImplTest.java @@ -1,99 +1,97 @@ package org.sagebionetworks.repo.model.jdo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import java.util.Collection; import java.util.HashSet; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.UserGroupDAO; import org.sagebionetworks.repo.model.UserGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" }) public class JDOUserGroupDAOImplTest { @Autowired private UserGroupDAO userGroupDAO; @Before public void setUp() throws Exception { cleanUpGroups(); } @After public void tearDown() throws Exception { Collection<String> groupNames = new HashSet<String>(); groupNames.add(GROUP_NAME); Map<String,UserGroup> map = userGroupDAO.getGroupsByNames(groupNames); UserGroup toDelete = map.get(GROUP_NAME); if (toDelete!=null) { userGroupDAO.delete(toDelete.getId()); } cleanUpGroups(); } public void cleanUpGroups() throws Exception { for (UserGroup g: userGroupDAO.getAll()) { - if (g.getName().equals(AuthorizationConstants.ADMIN_GROUP_NAME)) { - // leave it - } else if (g.getName().equals(AuthorizationConstants.PUBLIC_GROUP_NAME)) { + if (g.getName().equals(AuthorizationConstants.PUBLIC_GROUP_NAME)) { // leave it } else if (g.getName().equals(AuthorizationConstants.ANONYMOUS_USER_ID)) { // leave it } else { userGroupDAO.delete(g.getId()); } } } @Test public void findAnonymousUser() throws Exception { assertNotNull(userGroupDAO.findGroup(AuthorizationConstants.ANONYMOUS_USER_ID, true)); } private static final String GROUP_NAME = "test-group"; @Test public void testGetGroupsByNames() throws Exception { Collection<UserGroup> allGroups = null; allGroups = userGroupDAO.getAll(); assertEquals(allGroups.toString(), 2, allGroups.size()); // Public and Anonymous Collection<String> groupNames = new HashSet<String>(); groupNames.add(GROUP_NAME); Map<String,UserGroup> map = null; map = userGroupDAO.getGroupsByNames(groupNames); assertFalse(map.containsKey(GROUP_NAME)); UserGroup group = new UserGroup(); group.setName(GROUP_NAME); userGroupDAO.create(group); allGroups = userGroupDAO.getAll(); assertEquals(allGroups.toString(), 3, allGroups.size()); // now the new group should be there groupNames.clear(); groupNames.add(GROUP_NAME); map = userGroupDAO.getGroupsByNames(groupNames); assertTrue(groupNames.toString()+" -> "+map.toString(), map.containsKey(GROUP_NAME)); groupNames.clear(); groupNames.add(AuthorizationConstants.PUBLIC_GROUP_NAME); map = userGroupDAO.getGroupsByNames(groupNames); assertTrue(map.toString(), map.containsKey(AuthorizationConstants.PUBLIC_GROUP_NAME)); } }
true
false
null
null
diff --git a/src/web/org/openmrs/web/controller/form/FormFormController.java b/src/web/org/openmrs/web/controller/form/FormFormController.java index 3be493b2..bc841549 100644 --- a/src/web/org/openmrs/web/controller/form/FormFormController.java +++ b/src/web/org/openmrs/web/controller/form/FormFormController.java @@ -1,192 +1,194 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.controller.form; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.EncounterType; import org.openmrs.FieldType; import org.openmrs.Form; import org.openmrs.FormField; import org.openmrs.api.FormService; import org.openmrs.api.context.Context; import org.openmrs.propertyeditor.EncounterTypeEditor; import org.openmrs.util.FormUtil; import org.openmrs.web.WebConstants; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; public class FormFormController extends SimpleFormController { /** Logger for this class and subclasses */ protected final Log log = LogFactory.getLog(getClass()); protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); // NumberFormat nf = NumberFormat.getInstance(new Locale("en_US")); binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true)); binder.registerCustomEditor(EncounterType.class, new EncounterTypeEditor()); } /** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (Context.isAuthenticated()) { Form form = (Form) obj; MessageSourceAccessor msa = getMessageSourceAccessor(); String action = request.getParameter("action"); if (action == null) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.not.saved"); } else { if (action.equals(msa.getMessage("Form.save"))) { try { // retrieve xslt from request if it was uploaded if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile xsltFile = multipartRequest.getFile("xslt_file"); if (xsltFile != null && !xsltFile.isEmpty()) { String xslt = IOUtils.toString(xsltFile.getInputStream()); form.setXslt(xslt); } } // save form Context.getFormService().saveForm(form); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.saved"); } catch (Exception e) { log.error("Error while saving form " + form.getFormId(), e); errors.reject(e.getMessage()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.not.saved"); return showForm(request, response, errors); } } else if (action.equals(msa.getMessage("Form.delete"))) { try { Context.getFormService().purgeForm(form); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.deleted"); } catch (Exception e) { log.error("Error while deleting form " + form.getFormId(), e); errors.reject(e.getMessage()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.cannot.delete"); throw e; //return new ModelAndView(new RedirectView(getSuccessView())); } } else if (action.equals(msa.getMessage("Form.updateSortOrder"))) { FormService fs = Context.getFormService(); TreeMap<Integer, TreeSet<FormField>> treeMap = FormUtil.getFormStructure(form); for (Integer parentFormFieldId : treeMap.keySet()) { float sortWeight = 0; for (FormField formField : treeMap.get(parentFormFieldId)) { formField.setSortWeight(sortWeight); fs.saveFormField(formField); sortWeight += 50; } } } else { try { Context.getFormService().duplicateForm(form); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.duplicated"); } catch (Exception e) { log.error("Error while duplicating form " + form.getFormId(), e); errors.reject(e.getMessage()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.cannot.duplicate"); return showForm(request, response, errors); } } view = getSuccessView(); } } return new ModelAndView(new RedirectView(view)); } /** * This is called prior to displaying a form for the first time. It tells Spring the * form/command object to load into the request * * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest) */ protected Object formBackingObject(HttpServletRequest request) throws ServletException { Form form = null; if (Context.isAuthenticated()) { FormService fs = Context.getFormService(); String formId = request.getParameter("formId"); if (formId != null) - form = fs.getForm(Integer.valueOf(formId)); + try { + form = fs.getForm(Integer.valueOf(formId)); + } catch (NumberFormatException e) {;} //If formId has no readable value defaults to the case where form==null } if (form == null) form = new Form(); return form; } protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errors) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); List<FieldType> fieldTypes = new Vector<FieldType>(); List<EncounterType> encTypes = new Vector<EncounterType>(); if (Context.isAuthenticated()) { fieldTypes = Context.getFormService().getAllFieldTypes(); encTypes = Context.getEncounterService().getAllEncounterTypes(); } map.put("fieldTypes", fieldTypes); map.put("encounterTypes", encTypes); return map; } }
true
false
null
null
diff --git a/activejdbc/src/main/java/activejdbc/Model.java b/activejdbc/src/main/java/activejdbc/Model.java index c8009bae..6b3add1d 100644 --- a/activejdbc/src/main/java/activejdbc/Model.java +++ b/activejdbc/src/main/java/activejdbc/Model.java @@ -1,2012 +1,2012 @@ /* Copyright 2009-2010 Igor Polevoy 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 activejdbc; import activejdbc.associations.*; import activejdbc.cache.QueryCache; import activejdbc.validation.*; import static javalite.common.Util.blank; import java.io.StringWriter; import java.sql.*; import java.math.BigDecimal; import java.util.*; import java.util.Collections; import static javalite.common.Inflector.*; import javalite.common.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is a super class of all "models" and provides most functionality * necessary for implementation of Active Record pattern. */ public abstract class Model extends CallbackSupport{ private final static Logger logger = LoggerFactory.getLogger(Model.class); private Map<String, Object> attributes = new HashMap<String, Object>(); private boolean frozen = false; private MetaModel metaModelLocal; private Map<Class, Model> cachedParents = new HashMap<Class, Model>(); protected Errors errors; protected Model() { errors = new Errors(); } public static MetaModel getMetaModel() { Registry.instance().init(MetaModel.getDbName(getDaClass())); return Registry.instance().getMetaModel(getTableName()); } /** * Overrides attribute values from map. The map may have attributes whose name do not match the * attribute names (columns) of this model. Such attributes will be ignored. Thise values whose names are * not present in the argument map, will stay untouched. * * @param map map with attributes to overwrite this models'. */ public void fromMap(Map map){ hydrate(map); } /** * Hydrates a this instance of model from a map. Only picks values from a map that match * this instance's attribute names, while ignoring the others. * * @param attributesMap map containing values for this instance. */ protected void hydrate(Map attributesMap) { List<String> attributeNames = getMetaModelLocal().getAttributeNamesSkipId(); String idName = getMetaModelLocal().getIdName(); Object id = attributesMap.get(idName); if(id != null) attributes.put(idName, id); for (String attrName : attributeNames) { if(attrName.equalsIgnoreCase(getMetaModelLocal().getIdName())){ continue;//skip ID, already set. } Object value = attributesMap.get(attrName.toLowerCase()); if (value == null) { value = attributesMap.get(attrName.toUpperCase()); } //it is necessary to cache contents of a clob, because if a clob instance itself s cached, and accessed later, //it will not be able to connect back to that same connection from which it came. //This is only important for cached models. This will allocate a ton of memory if Clobs are large. //Should the Blob behavior be the same? //TODO: write about this in future tutorial if(value != null && value instanceof Clob && getMetaModelLocal().cached() ){ this.attributes.put(attrName.toLowerCase(), Convert.toString(value)); }else if(value != null){ this.attributes.put(attrName.toLowerCase(), value); } } } //TODO: add typed setters corresponding to typed getters public void setDate(String name, java.util.Date date) { if (date == null) { set(name, null); } else { set(name, new java.sql.Date(date.getTime())); } } public void setTS(String name, java.util.Date date) { if(date == null) { set(name, null); } else { set(name, new java.sql.Timestamp(date.getTime())); } } /** * Sets values for this model instance. The squence of values must correspond to sequence of names. * * @param attributeNames names of attributes. * @param values values for this instance. */ public void set(String[] attributeNames, Object[] values) { if (attributeNames == null || values == null || attributeNames.length != values.length) { throw new IllegalArgumentException("must pass non-null arrays of equal length"); } for (int i = 0; i < attributeNames.length; i++) { set(attributeNames[i], values[i]); } } public Model set(String attribute, Object value) { if(attribute.equalsIgnoreCase("created_at")) throw new IllegalArgumentException("cannot set 'created_at'"); getMetaModelLocal().checkAttributeOrAssociation(attribute); attributes.put(attribute.toLowerCase(), value); return this; } /** * Will return true if this instance is frozen, false otherwise. * A frozen instance cannot use used, as it has no relation to a record in table. * * @return true if this instance is frozen, false otherwise. */ public boolean isFrozen(){ return frozen; } /** * Returns names of all attributes from this model. * @return names of all attributes from this model. */ public static List<String> attributes(){ return getMetaModel().getAttributeNames(); } /** * Returns all associations of this model. * @return all associations of this model. */ public static List<Association> associations(){ return getMetaModel().getAssociations(); } /** * returns true if this is a new instance, not saved yet to DB, false otherwise. * * @return true if this is a new instance, not saved yet to DB, false otherwise */ public boolean isNew(){ return getId() == null; } /** * Synonym for {@link #isFrozen()}. if(m.frozen()) seems to read better than classical Java convention. * * @return true if this instance is frozen, false otherwise. */ public boolean frozen(){ return isFrozen(); } /** * Deletes a single table record represented by this instance. This method assumes that a corresponding table * has only one record whose PK is the ID of this instance. * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. * * @return true if a record was deleted, false if not. */ public boolean delete() { fireBeforeDelete(this); boolean result; if( 1 == new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + getMetaModelLocal().getTableName() + " WHERE " + getMetaModelLocal().getIdName() + "= ?", getId())) { frozen = true; if(getMetaModelLocal().cached()){ QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); } purgeEdges(); result = true; } else{ result = false; } fireAfterDelete(this); return result; } /** * Convenience method, will call {@link #delete()} or {@link #deleteCascade()}. * * @param cascade true to call {@link #deleteCascade()}, false to call {@link #delete()}. */ public void delete(boolean cascade){ if(cascade){ deleteCascade(); }else{ delete(); } } /** * Deletes this record from table. * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. * <h4>One to many relationships:</h4> * Deletes current model and all one to many associations. This is not a high performance method, as it will * load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all * the associated records (per table), and one delete statement per record. Use it for small data sets. * It will follow associations of children and their associations too. * <h4>Many to many relationships:</h4> * Deletes current model and will navigate through all many to many relationships * this model has, and clear links to other tables in join tables. This is a high performance call because links are cleared with one * SQL DELETE. * <h4>One to many polymorphic relationship:</h4> * Deletes current model and all polymorphic children. This is a high performance call because links are cleared with one * SQL DELETE. */ public void deleteCascade(){ deleteOneToManyChildren(); deleteJoinsForManyToMany(); deletePolymorphicChildren(); delete(); } private void deleteJoinsForManyToMany() { List<Association> associations = getMetaModelLocal().getManyToManyAssociations(); for(Association association:associations){ String join = ((Many2ManyAssociation)association).getJoin(); String sourceFK = ((Many2ManyAssociation)association).getSourceFkName(); String query = "DELETE FROM " + join + " WHERE " + sourceFK + " = " + getId(); new DB(getMetaModelLocal().getDbName()).exec(query); } } private void deletePolymorphicChildren() { List<OneToManyPolymorphicAssociation> polymorphics = getMetaModelLocal().getPolymorphicAssociations(); for (OneToManyPolymorphicAssociation association : polymorphics) { String target = association.getTarget(); String parentType = association.getParentType(); String query = "DELETE FROM " + target + " WHERE parent_id = ? AND parent_type = ?"; new DB(getMetaModelLocal().getDbName()).exec(query, getId(), parentType); } } private void deleteOneToManyChildren(){ List<Association> one2manies = getMetaModelLocal().getOneToManyAssociations(); for (Association association : one2manies) { String targetTableName = association.getTarget(); Class c = Registry.instance().getModelClass(targetTableName); if(c == null)// this model is probably not defined as a class, but the table exists! { logger.error("ActiveJDBC WARNING: failed to find a model class for: " + targetTableName + ", maybe model is not defined for this table?" + " There might be a risk of running into integrity constrain violation if this model is not defined."); } else{ List<Model> dependencies = getAll(c); for (Model model : dependencies) { model.deleteCascade(); } } } } /** * Deletes some records from associated table. This method does not follow any associations. * If this model has one to many associations, you might end up with either orphan records in child * tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records * in one shot, without pre-loading them. * This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". * This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you * would be attempting to update phantom records. * * * @param query narrows which records to delete. Example: <pre>"last_name like '%sen%'"</pre>. * @param params (optional) - list of parameters if a query is parametrized. * @return number od deleted records. */ public static int delete(String query, Object... params) { MetaModel metaModel = getMetaModel(); int count = params == null || params.length == 0? new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query) : new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query, params); if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } purgeEdges(); return count; } /** * Returns true if record corresponding to the id passed exists in the DB. * * @param id id in question. * @return true if corresponding record exists in DB, false if it does not. */ public static boolean exists(Object id){ MetaModel metaModel = getMetaModel(); return null != new DB(metaModel.getDbName()).firstCell("SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() + " WHERE " + metaModel.getIdName() + " = ?", id); } /** * Deletes all records from associated table. This methods does not take associations into account. * * @return number of records deleted. */ public static int deleteAll() { MetaModel metaModel = getMetaModel(); int count = new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName()); if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } purgeEdges(); return count; } /** * Updates records associated with this model. * * This example : * <pre> * Employee.update("bonus = ?", "years_at_company > ?", "5", "10"); * </pre * In this example, employees who worked for more than 10 years, get a bonus of 5% (not so generous :)). * * * @param updates - what needs to be updated. * @param conditions specifies which records to update. If this argument is <code>null</code>, all records in table will be updated. * In such cases, use a more explicit {@link #updateAll(String, Object...)} method. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int update(String updates, String conditions, Object ... params) { //TODO: validate that the number of question marks is the same as number of parameters MetaModel metaModel = getMetaModel(); Object []allParams; if(metaModel.hasAttribute("updated_at")){ updates = "updated_at = ?, " + updates; allParams = new Object[params.length + 1]; System.arraycopy(params, 0, allParams, 1, params.length); allParams[0] = new Timestamp(System.currentTimeMillis()); }else{ allParams = params; } String sql = "UPDATE " + metaModel.getTableName() + " SET " + updates + ((conditions != null)?" WHERE " + conditions:""); int count = new DB(metaModel.getDbName()).exec(sql, allParams); if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } return count; } /** * Updates all records associated with this model. * * This example : * <pre> * Employee.updateAll("bonus = ?", "10"); * </pre * In this example, all employees get a bonus of 10%. * * * @param updates - what needs to be updated. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int updateAll(String updates, Object ... params) { return update(updates, null, params); } /** * Returns all values of the model with all attribute names converted to lower case, * regardless how these names came from DB. This method is a convenience * method for displaying values on web pages. * * <p/> * If {@link activejdbc.LazyList#include(Class[])} method was used, and this * model belongs to a parent (as in many to one relationship), then the parent * will be eagerly loaded and also converted to a map. Parents' maps are keyed in the * returned map by underscored name of a parent model class name. * <p/> * For example, if this model were <code>Address</code> * and a parent is <code>User</code> (and user has many addresses), then the resulting map would * have all the attributes of the current table and another map representing a parent user with a * key "user" in current map. * * @return all values of the model with all attribute names converted to lower case. */ public Map<String, Object> toMap(){ Map<String, Object> retVal = new HashMap<String, Object>(); for (String key : attributes.keySet()) { retVal.put(key.toLowerCase(), attributes.get(key)); } for(Class parentClass: cachedParents.keySet()){ retVal.put(underscore(shortName(parentClass.getName())), cachedParents.get(parentClass).toMap()); } for(Class childClass: cachedChildren.keySet()){ List<Model> children = cachedChildren.get(childClass); List<Map> childMaps = new ArrayList<Map>(children.size()); for(Model child:children){ childMaps.add(child.toMap()); } retVal.put(pluralize(underscore(shortName(childClass.getName()))), childMaps); } return retVal; } /** * Generates a XML document from content of this model. * * @param spaces by how many spaces to indent. * @param declaration tru to include XML declaration at the top * @param attrs list of attributes to include. No arguments == include all attributes. * @return generated XML. */ public String toXml(int spaces, boolean declaration, String ... attrs){ Map<String, Object> modelMap = toMap(); String indent = ""; for(int i = 0; i < spaces; i++) indent += " "; List<String> attrList = Arrays.asList(attrs); StringWriter sw = new StringWriter(); if(declaration) sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + (spaces > 0?"\n":"")); String topTag = Inflector.underscore(getClass().getSimpleName()); sw.write(indent + "<" + topTag + ">" + (spaces > 0?"\n":"")); for(String name: modelMap.keySet()){ Object value = modelMap.get(name); if((attrList.contains(name) || attrs.length == 0) && !(value instanceof List)){ sw.write(indent + indent + "<" + name + ">" + value + "</" + name + ">" + (spaces > 0?"\n":"")); }else if (value instanceof List){ List<Map> children = (List<Map>)value; sw.write(indent + indent + "<" + name + ">" + (spaces > 0?"\n":"")); for(Map child: children){ sw.write(indent + indent + indent + "<" + Inflector.singularize(name) + ">" + (spaces > 0?"\n":"")); for(Object childKey: child.keySet()){ sw.write(indent + indent + indent + indent + "<" + childKey + ">" + child.get(childKey)+ "</" + childKey +">" + (spaces > 0?"\n":"")); } sw.write(indent + indent + indent + "</" + Inflector.singularize(name) + ">" + (spaces > 0?"\n":"")); } sw.write(indent + indent + "</" + name + ">" + (spaces > 0?"\n":"")); } } sw.write(indent + "</" + topTag + ">"+ (spaces > 0?"\n":"")); return sw.toString(); } /** * Returns parent of this model, assuming that this table represents a child. * * @param parentClass class of a parent model. * @return instance of a parent of this instance in the "belongs to" relationship. */ public <T extends Model> T parent(Class<T> parentClass) { T cachedParent = (T)cachedParents.get(parentClass); if(cachedParent != null){ return cachedParent; } MetaModel parentMM = Registry.instance().getMetaModel(parentClass); String parentTable = parentMM.getTableName(); BelongsToAssociation ass = (BelongsToAssociation)getMetaModelLocal().getAssociationForTarget(parentTable, BelongsToAssociation.class); BelongsToPolymorphicAssociation assP = (BelongsToPolymorphicAssociation)getMetaModelLocal() .getAssociationForTarget(parentTable, BelongsToPolymorphicAssociation.class); String fkValue; if(ass != null){ fkValue = getString(ass.getFkName()); }else if(assP != null){ fkValue = getString("parent_id"); MetaModel trueMM = Registry.instance().getMetaModelByClassName(getString("parent_type")); if(trueMM != parentMM) throw new IllegalArgumentException("Wrong parent: '" + parentClass + "'. Actual parent type of this record is: '" + getString("parent_type") + "'"); }else{ throw new DBException("there is no association with table: " + parentTable); } String parentIdName = parentMM.getIdName(); String query = getMetaModelLocal().getDialect().selectStarParametrized(parentTable, parentIdName); T parent; if(parentMM.cached()){ parent = (T)QueryCache.instance().getItem(parentTable, query, new Object[]{fkValue}); if(parent != null){ return parent; } } List<Map> results = new DB(getMetaModelLocal().getDbName()).findAll(query, Integer.parseInt(fkValue)); //expect only one result here if (results.size() == 0) { //ths could be covered by referential integrity constraint return null; } else { try { parent = parentClass.newInstance(); parent.hydrate(results.get(0)); if(parentMM.cached()){ QueryCache.instance().addItem(parentTable, query, new Object[]{fkValue}, parent); } return parent; } catch (Exception e) { throw new InitException(e.getMessage(), e); } } } protected void setCachedParent(Model parent) { cachedParents.put(parent.getClass(), parent); } /** * Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a * parent/child relationship. This only works for one to many and polymorphic associations. * * @param parents - collection of potential parents of this instance. Its ID values must not be null. */ public void setParents(Model... parents){ for (Model parent : parents) { setParent(parent); } } /** * Sets a parent on this instance. Basically this sets a correct value of a foreign key in a * parent/child relationship. This only works for one to many and polymorphic associations. * * @param parent potential parent of this instance. Its ID value must not be null. */ public void setParent(Model parent) { if (parent == null || parent.getId() == null) { throw new IllegalArgumentException("parent cannot ne null and parent ID cannot be null"); } List<Association> associations = getMetaModelLocal().getAssociations(); for (Association association : associations) { - if (association instanceof BelongsToAssociation) { + if (association instanceof BelongsToAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())) { set(((BelongsToAssociation)association).getFkName(), parent.getId()); return; } - if(association instanceof BelongsToPolymorphicAssociation){ + if(association instanceof BelongsToPolymorphicAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())){ set("parent_id", parent.getId()); set("parent_type", ((BelongsToPolymorphicAssociation)association).getParentType()); return; } } throw new IllegalArgumentException("Class: " + parent.getClass() + " is not associated with " + this.getClass() - + ", list of existing associations: " + getMetaModelLocal().getAssociations()); + + ", list of existing associations: \n" + Util.join(getMetaModelLocal().getAssociations(), "\n")); } /** * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. * * @param other target model. */ public <T extends Model> void copyTo(T other) { if (!getMetaModelLocal().getTableName().equals(other.getMetaModelLocal().getTableName())) { throw new IllegalArgumentException("can only copy between the same types"); } List<String> attrs = getMetaModelLocal().getAttributeNamesSkipGenerated(); for (String name : attrs) { other.set(name, get(name)); } } /** * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. * * @param other target model. */ public void copyFrom(Model other) { other.copyTo(this); } /** * This method should be called from all instance methods for performance. * * @return */ private MetaModel getMetaModelLocal(){ if(metaModelLocal == null) metaModelLocal = getMetaModel(); return metaModelLocal; } /** * Re-reads all attribute values from DB. * */ public void refresh() { //TODO: test! Model fresh = findById(getId()); fresh.copyTo(this); } /** * Returns a value for attribute. Besides returning direct attributes of this model, this method is also * aware of relationships and can return collections based on naming conventions. For example, if a model User has a * one to many relationship with a model Address, then the following code will work: * <pre> * Address address = ...; * User user = (User)address.get("user"); * </pre> * Conversely, this will also work: * <pre> * List<Address> addresses = (List<Address>)user.get("addresses"); * </pre> * * The same would also work for many to many relationships: * <pre> * List<Doctor> doctors = (List<Doctor>)patient.get("doctors"); * ... * List<Patient> patients = (List<Patient>)doctor.get("patients"); * </pre> * * This methods will try to infer a name if a table by using {@link javalite.common.Inflector} to try to * convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship * with another model, if one is found. This method of finding of relationships is best used in templating * technologies, such as JSPs. For standard cases, please use {@link #parent(Class)}, and {@link #getAll(Class)}. * * * @param attribute name of attribute. * @return value for attribute. */ public Object get(String attribute) { if(frozen) throw new FrozenException(this); if(attribute == null) throw new IllegalArgumentException("attribute cannot be null"); // NOTE: this is a workaround for JSP pages. JSTL in cases ${item.id} does not call the getId() method, instead //calls item.get("id"), considering that this is a map only! if(attribute.equalsIgnoreCase("id")){ String idName = getMetaModelLocal().getIdName(); return attributes.get(idName.toLowerCase()); } Object returnValue; String attributeName = attribute.toLowerCase(); if((returnValue = attributes.get(attributeName.toLowerCase())) != null){ return returnValue; }else if((returnValue = tryParent(attributeName)) != null){ return returnValue; }else if((returnValue = tryPolymorphicParent(attributeName)) != null){ return returnValue; }else if((returnValue = tryChildren(attributeName)) != null){ return returnValue; }else if((returnValue = tryPolymorphicChildren(attributeName)) != null){ return returnValue; }else if((returnValue = tryOther(attributeName)) != null){ return returnValue; }else{ getMetaModelLocal().checkAttributeOrAssociation(attributeName); return null; } } private Object tryPolymorphicParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToPolymorphicAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryPolymorphicChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyPolymorphicAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryOther(String otherTable){ MetaModel otherMM = inferTargetMetaModel(otherTable); if(otherMM == null){ return null; }else return getMetaModelLocal().hasAssociation(otherMM.getTableName(), Many2ManyAssociation.class) ? getAll(otherMM.getModelClass()): null; } private MetaModel inferTargetMetaModel(String targetTableName){ String targetTable = singularize(targetTableName); MetaModel targetMM = Registry.instance().getMetaModel(targetTable); if(targetMM == null){ targetTable = pluralize(targetTableName); targetMM = Registry.instance().getMetaModel(targetTable); } return targetMM != null? targetMM: null; } /*************************** typed getters *****************************************/ /** * Get any value as string. * * @param attribute name of attribute. * @return attribute value as string. */ public String getString(String attribute) { Object value = get(attribute); return Convert.toString(value); } public BigDecimal getBigDecimal(String attribute) { return Convert.toBigDecimal(get(attribute)); } public Integer getInteger(String attribute) { return Convert.toInteger(get(attribute)); } public Long getLong(String attribute) { return Convert.toLong(get(attribute)); } public Float getFloat(String attribute) { return Convert.toFloat(get(attribute)); } public Timestamp getTimestamp(String attribute) { return Convert.toTimestamp(get(attribute)); } public Double getDouble(String attribute) { return Convert.toDouble(get(attribute)); } public java.sql.Date getDate(String attribute) { return Convert.toSqlDate(get(attribute)); } public Boolean getBoolean(String attribute) { return Convert.toBoolean(get(attribute)); } /*************************** typed setters *****************************************/ /** * Converts object to string when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setString(String attribute, Object value) { return set(attribute, value.toString()); } /** * Converts object to BigDecimal when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setBigDecimal(String attribute, Object value) { return set(attribute, Convert.toBigDecimal(value)); } /** * Converts object to <code>Integer</code> when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setInteger(String attribute, Object value) { return set(attribute, Convert.toInteger(value)); } /** * Converts object to <code>Long</code> when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model getLong(String attribute, Object value) { return set(attribute, Convert.toLong(value)); } /** * Converts object to <code>Float</code> when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setFloat(String attribute, Object value) { return set(attribute, Convert.toFloat(value)); } /** * * Converts object to <code>java.sql.Timestamp</code> when setting. * If the value is instance of java.sql.Timestamp, just sets it, else tries to convert the value to Timestamp using * Timestamp.valueOf(String). This method might trow IllegalArgumentException if fails at conversion. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setTimestamp(String attribute, Object value) { return set(attribute, Convert.toTimestamp(value)); } /** * Converts object to <code>Double</code> when setting. * * @param attribute name of attribute. * @param value value * @return reference to this model. */ public Model setDouble(String attribute, Object value) { return set(attribute, Convert.toDouble(value)); } /** * Converts to <code>java.sql.Date</code>. Expects a <<code>java.sql.Date</code>, <code>java.sql.Timestamp</code>, <code>java.util.Date</code> or * string with format: <code>yyyy-mm-dd</code>. * * @param attribute name of attribute. * @param value value to convert. * @return this model. */ public Model setDate(String attribute, Object value) { return set(attribute, Convert.toSqlDate(value)); } /** * Sets to <code>true</code> if the value is any numeric type and has a value of 1, or if string type has a * value of 'y', 't', 'true' or 'yes'. Otherwise, sets to false. * * @param attribute name of attribute. * @param value value to convert. * @return this model. */ public Model setBoolean(String attribute, Object value) { return set(attribute, Convert.toBoolean(value)); } /** * This methods supports one to man, many to many relationships as well as plymorhic accosiations. * <p/> * In case of one to many, the <code>clazz</code> must be a class of a child model, and it will return a * collection of all children. * <p/> * In case of many to many, the <code>clazz</code> must be a class of a another related model, and it will return a * collection of all related models. * <p/> * In case of many to many, the <code>clazz</code> must be a class of a polymorphicly related model, and it will return a * collection of all related models. * * * @param clazz class of a child model for one to many, or class of another model, in case of many to many. * @return list of children in case of one to many, or list of other models, in case many to many. */ public <T extends Model> LazyList<T> getAll(Class<T> clazz) { List<Model> children = cachedChildren.get(clazz); if(children != null){ return (LazyList<T>) children; } String tableName = Registry.instance().getTableName(clazz); if(tableName == null) throw new IllegalArgumentException("table: " + tableName + " does not exist for model: " + clazz); return get(tableName, null); } /** * Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list * by criteria. * * <p/> * <strong>1.</strong> For one to many, the criteria is against the child table. * * <p/> * <strong>2.</strong> For polymorphic association, the criteria is against the child table. * * <p/> * <strong>3.</strong> For many to many, the criteria is against the join table. * For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer * has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table * has a column <code>duration_weeks</code>: * * <pre> * List<Project> threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3); * </pre> * where this list wil contain all projects to which this programmer is assigned for 3 weeks. * * @param clazz related type * @param query sub-query for join table. * @param params parameters for a sub-query * @return list of relations in many to many */ public <T extends Model> LazyList<T> get(Class<T> clazz, String query, Object ... params){ return get(Registry.instance().getTableName(clazz), query, params); } private <T extends Model> LazyList<T> get(String targetTable, String criteria, Object ...params) { //TODO: interesting thought: is it possible to have two associations of the same name, one to many and many to many? For now, say no. OneToManyAssociation oneToManyAssociation = (OneToManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyAssociation.class); Many2ManyAssociation manyToManyAssociation = (Many2ManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, Many2ManyAssociation.class); OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = (OneToManyPolymorphicAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyPolymorphicAssociation.class); String additionalCriteria = criteria != null? " AND ( " + criteria + " ) " : ""; String subQuery; if (oneToManyAssociation != null) { subQuery = oneToManyAssociation.getFkName() + " = " + getId() + additionalCriteria; } else if (manyToManyAssociation != null) { String targetId = Registry.instance().getMetaModel(targetTable).getIdName(); subQuery = targetId + " IN ( SELECT " + manyToManyAssociation.getTargetFkName() + " FROM " + manyToManyAssociation.getJoin() + " WHERE " + manyToManyAssociation.getSourceFkName() + " = " + getId() + additionalCriteria + ")" ; } else if (oneToManyPolymorphicAssociation != null) { subQuery = "parent_id = " + getId() + " AND " + " parent_type = '" + getClass().getName() + "'" + additionalCriteria; } else { throw new NotAssociatedException(getMetaModelLocal().getTableName(), targetTable); } return new LazyList<T>(subQuery, params,Registry.instance().getMetaModel(targetTable)); } @Override public String toString() { return "Model: " + getClass().getName() + ", Table: '" + getMetaModelLocal().getTableName() + "', attributes: " + attributes.toString(); } protected static NumericValidationBuilder validateNumericalityOf(String... attributes) { return ValidationHelper.addNumericalityValidators(Model.<Model>getDaClass(), toLowerCase(attributes)); } private static String[] toLowerCase(String[] arr){ String[] newArr = new String[arr.length]; for (int i = 0; i < newArr.length; i++) { newArr[i] = arr[i].toLowerCase(); } return newArr; } /** * Adds a validator to the model. * * @param validator new validator. * @return */ public static ValidationBuilder addValidator(Validator validator){ return ValidationHelper.addValidator(Model.<Model>getDaClass(), validator); } /** * Adds a new error to the collection of errors. This is a convenience method to be used from custom validators. * * @param key - key wy which this error can be retrieved from a collection of errors: {@link #errors()}. * @param value - this is a key of the message in the resource bundle. * @see {@link activejdbc.Messages}. */ public void addError(String key, String value){ errors.put(key, value); } public static void removeValidator(Validator validator){ Registry.instance().removeValidator(Model.<Model>getDaClass(), validator); } public static List<Validator> getValidators(Class<Model> daClass){ return Registry.instance().getValidators(daClass); } /** * Validates an attribite format with a ree hand regular expression. * * @param attribute attribute to validate. * @param pattern regexp pattern which must match the value. * @return */ protected static ValidationBuilder validateRegexpOf(String attribute, String pattern) { return ValidationHelper.addRegexpValidator(Model.<Model>getDaClass(), attribute.toLowerCase(), pattern); } /** * Validates email format. * * @param attribute name of atribute that holds email value. * @return */ protected static ValidationBuilder validateEmailOf(String attribute) { return ValidationHelper.addEmailValidator(Model.<Model>getDaClass(), attribute.toLowerCase()); } /** * Validates range. Accepted types are all java.lang.Number subclasses: * Byte, Short, Integer, Long, Float, Double BigDecimal. * * @param attribute attribute to validate - should be within range. * @param min min value of range. * @param max max value of range. * @return */ protected static ValidationBuilder validateRange(String attribute, Number min, Number max) { return ValidationHelper.addRangevalidator(Model.<Model>getDaClass(), attribute.toLowerCase(), min, max); } /** * The validation will not pass if the value is either an empty string "", or null. * * @param attributes list of attributes to validate. * @return */ protected static ValidationBuilder validatePresenceOf(String... attributes) { return ValidationHelper.addPresensevalidators(Model.<Model>getDaClass(), toLowerCase(attributes)); } /** * Add a custom validator to the model. * * @param validator custom validator. */ protected static ValidationBuilder validateWith(Validator validator) { return addValidator(validator); } /** * Converts a named attribute to <code>java.sql.Date</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Date</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. */ protected static ValidationBuilder convertDate(String attributeName, String format){ return ValidationHelper.addDateConverter(Model.<Model>getDaClass(), attributeName, format); } /** * Converts a named attribute to <code>java.sql.Timestamp</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Timestamp</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. */ protected static ValidationBuilder convertTimestamp(String attributeName, String format){ return ValidationHelper.addTimestampConverter(Model.<Model>getDaClass(), attributeName, format); } public static boolean belongsTo(Class<? extends Model> targetClass) { String targetTable = Registry.instance().getTableName(targetClass); MetaModel metaModel = getMetaModel(); return (null != metaModel.getAssociationForTarget(targetTable, BelongsToAssociation.class) || null != metaModel.getAssociationForTarget(targetTable, Many2ManyAssociation.class)); } public static void addCallbacks(CallbackListener ... listeners){ for(CallbackListener listener: listeners ){ Registry.instance().addListener(getDaClass(), listener); } } /** * This method performs validations and then returns true if no errors were generated, otherwise returns false. * * @return true if no errors were generated, otherwise returns false. */ public boolean isValid(){ validate(); return !hasErrors(); } /** * Executes all validators attached to this model. */ public void validate() { fireBeforeValidation(this); errors = new Errors(); List<Validator> theValidators = Registry.instance().getValidators((Class<Model>)getClass()); if(theValidators != null){ for (Validator validator : theValidators) { validator.validate(this); } } fireAfterValidation(this); } public boolean hasErrors() { return errors != null && errors.size() > 0; } /** * Binds a validator to an attribute after validation fails. This is an internal function, do not use. * * @param attribute name of attribute to which an error pertains. * @param validator -validator that failed validation. */ public void addValidator(String attribute, Validator validator) { if(!errors.containsKey(attribute)) errors.addValidator(attribute, validator); } /** * Provides an instance of <code>Errors</code> object, filled with error messages after validation. * * @return an instance of <code>Errors</code> object, filled with error messages after validation. */ public Errors errors() { return errors; } /** * Provides an instance of localized <code>Errors</code> object, filled with error messages after validation. * * @param locale locale. * @return an instance of localized <code>Errors</code> object, filled with error messages after validation. */ public Errors errors(Locale locale) { errors.setLocale(locale); return errors; } /** * This is a convenience method to create a model instance already initialized with values. * Example: * <pre> * Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public static <T extends Model> T create(Object ... namesAndValues){ if(namesAndValues.length %2 != 0) throw new IllegalArgumentException("number of arguments must be even"); try{ Model m = getDaClass().newInstance(); setNamesAndValues(m, namesAndValues); return (T) m; } catch(IllegalArgumentException e){throw e;} catch(ClassCastException e){throw new IllegalArgumentException("All even arguments must be strings");} catch(DBException e){throw e;} catch (Exception e){throw new InitException("This model must provide a default constructor.", e);} } /** * This is a convenience method to set multiple values to a model. * Example: * <pre> * Person p = ... * Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public Model set(Object ... namesAndValues){ setNamesAndValues(this, namesAndValues); return this; } private static void setNamesAndValues(Model m, Object... namesAndValues) { String[] names = new String[namesAndValues.length / 2]; Object[] values = new Object[namesAndValues.length / 2]; int j = 0; for (int i = 0; i < namesAndValues.length - 1; i += 2, j++) { if (namesAndValues[i] == null) throw new IllegalArgumentException("attribute names cannot be nulls"); names[j] = (String) namesAndValues[i]; values[j] = namesAndValues[i + 1]; } m.set(names, values); } /** * This is a convenience method to {@link #create(Object...)}. It will create a new model and will save it * to DB. It has the same semantics as {@link #saveIt()}. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model which also has been saved to DB. */ public static <T extends Model> T createIt(Object ... namesAndValues){ T m = (T)create(namesAndValues); m.saveIt(); return m; } public static <T extends Model> T findById(Object id) { if(id == null) return null; MetaModel mm = getMetaModel(); LazyList<T> l = new LazyList<T>(mm.getIdName() + " = ?", new Object[]{id}, mm).limit(1); return l.size() > 0 ? l.get(0) : null; } /** * Finder method for DB queries based on table represented by this model. Usually the SQL starts with: * * <code>"select * from table_name where " + subquery</code> where table_name is a table represented by this model. * * Code example: * <pre> * * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20); * // iterate... * * //same can be achieved (since parameters are optional): * List<Person> teenagers = Person.where("age &gt 12 and age &lt 20"); * //iterate * </pre> * * Limit, offset and order by can be chained like this: * * <pre> * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20).offset(101).limit(20).orderBy(age); * //iterate * </pre> * * This is a great way to build paged applications. * * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob > ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> where(String subquery, Object... params) { return find(subquery, params); } /** * Synonym of {@link #where(String, Object...)} * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob &gt ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> find(String subquery, Object... params) { if(subquery.equals("*") && params.length == 0){ return findAll(); } if(subquery.equals("*") && params.length != 0){ throw new IllegalArgumentException("cannot provide parameters with query: '*', use findAll() method instead"); } return new LazyList(subquery, params, getMetaModel()); } /** * Synonym of {@link #first(String, Object...)}. * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.findFirst("name = ? and age &gt 13 and age &lt 19 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person oldest = Person.findFirst("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T findFirst(String subQuery, Object... params) { LazyList<T> results = new LazyList<T>(subQuery, params,getMetaModel()).limit(1); return results.size() > 0 ? results.get(0) : null; } /** * Returns a first result for this condition. May return null if nothing found. * If last result is needed, then order by some field and call this nethod: * * Synonym of {@link #findFirst(String, Object...)}. * <pre> * //first: * Person youngestTeenager= Person.first("age &gt 12 and age &lt 20 order by age"); * * //last: * Person oldestTeenager= Person.first("age &gt 12 and age &lt 20 order by age desc"); * </pre> * * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.first("name = ? and age &lt 13 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person p = Person.first("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T first(String subQuery, Object... params) { return (T)findFirst(subQuery, params); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param query query text. * @param listener this is a call back implementation which will receive instances of models found. * @deprecated use {@link #findWith(ModelListener, String, Object...)}. */ public static void find(String query, final ModelListener listener) { findWith(listener, query); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param listener this is a call back implementation which will receive instances of models found. * @param query sub-query (content after "WHERE" clause) * @param params optional parameters for a query. */ public static void findWith(final ModelListener listener, String query, Object ... params) { long start = System.currentTimeMillis(); final MetaModel metaModel = getMetaModel(); String sql = metaModel.getDialect().selectStar(metaModel.getTableName(), query); new DB(metaModel.getDbName()).find(sql, params).with( new RowListenerAdapter() { @Override public void onNext(Map<String, Object> row) { listener.onModel(instance(row, metaModel)); } }); LogFilter.logQuery(logger, sql, null, start); } /** * Free form query finder. Example: * <pre> * List<Rule> rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc"); * </pre> * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. * Returned columns that are not part of this model will be ignored, but can be used for caluses like above. * * @param fullQuery free-form SQL. * @param params parameters if query is parametrized. * @param <T> - class that extends Model. * @return list of models representing result set. */ public static <T extends Model> LazyList<T> findBySQL(String fullQuery, Object... params) { return new LazyList<T>(getMetaModel(), fullQuery, params); } /** * This method returns all records from this table. If you need to get a subset, look for variations of "find()". * * @return result list */ public static <T extends Model> LazyList<T> findAll() { return new LazyList(null, new Object[]{}, getMetaModel()); } /** * Adds a new child dependency. The dependency model must be either in many to many relationship to this model or * this model has to be in the one to many relationship with the added child model. * <p/> * In case of one to many relationship, this method will immediately set it's ID as a foreign key on the child and * will then save the child. * * <p/> * In case many to many relationship, this method will check if the added child already has an ID. If the child does * have an ID, then the method will create a link in the join table. If the child does not have an ID, then this method * saves the child first, then creates a record in the join table linking this model instance and the child instance. * * <p/> * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child instance of a model that has a relationship to the current model. * Either one to many or many to many relationships are accepted. */ public void add(Model child) { //TODO: refactor this method String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (getId() != null) { if (metaModel.hasAssociation(childTable, OneToManyAssociation.class)) { OneToManyAssociation ass = (OneToManyAssociation)metaModel.getAssociationForTarget(childTable, OneToManyAssociation.class); String fkName = ass.getFkName(); child.set(fkName, getId()); child.saveIt();//this will cause an exception in case validations fail. }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ Many2ManyAssociation ass = (Many2ManyAssociation) metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); String join = ass.getJoin(); String sourceFkName = ass.getSourceFkName(); String targetFkName = ass.getTargetFkName(); if(child.getId() == null) child.saveIt(); MetaModel joinMM = Registry.instance().getMetaModel(join); if(joinMM == null){ new DB(metaModel.getDbName()).exec("INSERT INTO " + join + " ( " + sourceFkName + ", " + targetFkName + " ) VALUES ( " + getId()+ ", " + child.getId() + ")"); }else{ //TODO: write a test to cover this case: //this is for Oracle, many 2 many, and all annotations used, including @IdGenerator. In this case, //it is best to delegate generation of insert to a model (sequences, etc.) try{ Model joinModel = (Model)joinMM.getModelClass().newInstance(); joinModel.set(sourceFkName, getId()); joinModel.set(targetFkName, child.getId()); joinModel.saveIt(); } catch(InstantiationException e){ throw new InitException("failed to create a new instance of class: " + joinMM.getClass() + ", are you sure this class has a default constructor?", e); } catch(IllegalAccessException e){throw new InitException(e);} finally { QueryCache.instance().purgeTableCache(join); QueryCache.instance().purgeTableCache(metaModel.getTableName()); QueryCache.instance().purgeTableCache(childTable); } } }else if(metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)){ metaModel.getAssociationForTarget(childTable, OneToManyPolymorphicAssociation.class); child.set("parent_id", getId()); child.set("parent_type", this.getClass().getName()); child.saveIt(); }else throw new NotAssociatedException(metaModel.getTableName(), childTable); } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it."); } } /** * Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model * or many to many association. * * <p/><p/> * In case this is a one to many or polymorphic relationship, this method will simply call <code>child.delete()</code> method. This will * render the child object frozen. * * <p/><p/> * In case this is a many to many relationship, this method will remove an associated record from the join table, and * will do nothing to the child model or record. * * <p/><p/> * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child model representing a "child" as in one to many or many to many association with this model. */ public void remove(Model child){ if(child == null) throw new IllegalArgumentException("cannot remove what is null"); if(child.frozen() || child.getId() == null) throw new IllegalArgumentException("Cannot remove a child that does " + "not exist in DB (either frozen, or ID not set)"); String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (getId() != null) { if (metaModel.hasAssociation(childTable, OneToManyAssociation.class) || metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { child.delete(); }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ Many2ManyAssociation ass = (Many2ManyAssociation)metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); String join = ass.getJoin(); String sourceFkName = ass.getSourceFkName(); String targetFkName = ass.getTargetFkName(); new DB(metaModel.getDbName()).exec("DELETE FROM " + join + " WHERE " + sourceFkName + " = ? AND " + targetFkName + " = ?", getId(), child.getId()); }else throw new NotAssociatedException(metaModel.getTableName(), childTable); } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. " + "Save this instance first, then you will be able to add dependencies to it."); } } /** * This method will not exit silently like {@link #save()}, it instead will throw {@link activejdbc.validation.ValidationException} * if validations did not pass. * * @return true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB. */ public boolean saveIt() { boolean result = save(); purgeEdges(); if(errors.size() > 0){ throw new ValidationException(this); } return result; } /** * Resets all data in this model, including the ID. * After this method, this instance is equivalent to an empty, just created instance. */ public void reset() { attributes = new HashMap<String, Object>(); } /** * Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. * This method will erase the value of ID on this instance, while preserving all other attributes' values. * * If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will * generate a new insert statement and create a new record in the table with all the same attribute values. * * <p/><p/> * Synonym for {@link #defrost()}. */ public void thaw(){ attributes.put(getMetaModelLocal().getIdName(), "");//makes it blank frozen = false; } /** * Synonym for {@link #thaw()}. */ public void defrost(){ thaw(); } /** * This method will save data from this instance to a corresponding table in the DB. * It will generate insert SQL if the model is new, or update if the model exists in the DB. * This method will execute all associated validations and if those validations generate errors, * these errors are attached to this instance. Errors are available by {#link #errors() } method. * The <code>save()</code> method is mostly for web applications, where code like this is written: * <pre> * if(person.save()) * //show page success * else{ * request.setAttribute("errors", person.errors()); * //show errors page, or same page so that user can correct errors. * } * </pre> * * In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then * there can be a runtime exception thrown. * * @return true if a model was saved and false if values did not pass validations and the record was not saved. * False will also be returned if you set an ID value for the model, but such ID does not exist in DB. */ public boolean save() { if(frozen) throw new FrozenException(this); fireBeforeSave(this); validate(); if (hasErrors()) { return false; } boolean result; if (blank(getId())) { result = insert(); } else { result = update(); } fireAfterSave(this); return result; } public static Long count() { MetaModel metaModel = getMetaModel(); String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName(); Long result; if(metaModel.cached()){ result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, null); if(result == null) { result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); QueryCache.instance().addItem(metaModel.getTableName(), sql, null, result); } }else{ result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); } return result; } public static Long count(String query, Object... params) { MetaModel metaModel = getMetaModel(); //attention: this SQL is only used for caching, not for real queries. String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName() + " where " + query; Long result; if(metaModel.cached()){ result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, params); if(result == null){ result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); QueryCache.instance().addItem(metaModel.getTableName(), sql, params, result); } }else{ result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); } return result; } private boolean insert() { fireBeforeCreate(this); doCreatedAt(); doUpdatedAt(); //TODO: need to invoke checkAttributes here too, and maybe rely on MetaModel for this. List<String> attrs = getMetaModelLocal().getAttributeNamesSkip("record_version", getMetaModelLocal().getIdName()); List<Object> values = new ArrayList<Object>(); for (String attribute : attrs) { values.add(this.attributes.get(attribute)); } String query = getMetaModelLocal().getDialect().createParametrizedInsert(getMetaModelLocal()); try { long id = new DB(getMetaModelLocal().getDbName()).execInsert(query, getMetaModelLocal().getIdName(), values.toArray()); if(getMetaModelLocal().cached()){ QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); } attributes.put(getMetaModelLocal().getIdName(), id); fireAfterCreate(this); return true; } catch (Exception e) { throw new DBException(e.getMessage(), e); } } private void doCreatedAt() { if(getMetaModelLocal().hasAttribute("created_at")){ //clean just in case. attributes.remove("created_at"); attributes.remove("CREATED_AT"); attributes.put("created_at", new Timestamp(System.currentTimeMillis())); } } private void doUpdatedAt() { if(getMetaModelLocal().hasAttribute("updated_at")){ //clean just in case. attributes.remove("updated_at"); attributes.remove("UPDATED_AT"); set("updated_at", new Timestamp(System.currentTimeMillis())); } } private boolean update() { doUpdatedAt(); MetaModel metaModel = getMetaModelLocal(); String query = "UPDATE " + metaModel.getTableName() + " SET "; List<String> names = metaModel.getAttributeNamesSkipGenerated(); for (int i = 0; i < names.size(); i++) { String name = names.get(i); query += name + "= ?"; if (i < names.size() - 1) { query += ", "; } } List values = getAttributeValuesSkipGenerated(); if(metaModel.hasAttribute("updated_at")){ query += ", updated_at = ? "; values.add(get("updated_at")); } if(metaModel.isVersioned()){ query += ", record_version = ? "; values.add(getLong("record_version") + 1); } query += " where " + metaModel.getIdName() + " = ?"; query += metaModel.isVersioned()? " and record_version = ?" :""; values.add(getId()); if(metaModel.isVersioned()){ values.add((get("record_version"))); } int updated = new DB(metaModel.getDbName()).exec(query, values.toArray()); if(metaModel.isVersioned() && updated == 0){ throw new StaleModelException("Failed to update record for model '" + getClass() + "', with " + getIdName() + " = " + getId() + " and record_version = " + get("record_version") + ". Either this record does not exist anymore, or has been updated to have another record_version."); }else if(metaModel.isVersioned()){ set("record_version", getLong("record_version") + 1); } if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } return updated > 0; } private List getAttributeValuesSkipGenerated() { List<String> names = getMetaModelLocal().getAttributeNamesSkipGenerated(); List values = new ArrayList(); for (String name : names) { values.add(get(name)); } return values; } static <T extends Model> T instance(Map m, MetaModel metaModel) { try { T instance = (T) metaModel.getModelClass().newInstance(); instance.metaModelLocal = metaModel; instance.hydrate(m); return instance; } catch(InstantiationException e){ throw new InitException("Failed to create a new instance of: " + metaModel.getModelClass() + ", are you sure this class has a default constructor?"); } catch(DBException e){ throw e; } catch(InitException e){ throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } private static <T extends Model> Class<T> getDaClass() { try { MetaModel mm = Registry.instance().getMetaModelByClassName(getClassName()); return mm == null? (Class<T>) Class.forName(getClassName()) : mm.getModelClass(); } catch (Exception e) { throw new DBException(e.getMessage(), e); } } private static String getClassName() { return new ClassGetter().getClassName(); } public static String getTableName() { return Registry.instance().getTableName(getDaClass()); } public Object getId() { return get(getMetaModelLocal().getIdName()); } public String getIdName() { return getMetaModelLocal().getIdName(); } private Map<Class, List<Model>> cachedChildren = new HashMap<Class, List<Model>>(); protected void setChildren(Class childClass, List<Model> children) { cachedChildren.put(childClass, children); } static class ClassGetter extends SecurityManager { public String getClassName() { Class[] classes = getClassContext(); for (int i = 0; i < classes.length; i++) { Class aClass = classes[i]; if (aClass.getSuperclass().equals(Model.class)) { // TODO: revisit for inheritance implementation return aClass.getName(); } } throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); } } /** * Generates INSERT SQL based on this model. Uses single quotes for all string values. * Example: * <pre> * * String insert = u.toInsert(); * //yields this output: * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, 'Marilyn', '[email protected]', 'Monroe'); * </pre> * * @return INSERT SQL based on this model. */ public String toInsert(){ return toInsert("'", "'"); } /** * Generates INSERT SQL based on this model. * For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". * The output will also use single quotes for <code>java.sql.Timestamp</code> and <code>java.sql.Date</code> types. * * Example: * <pre> * String insert = u.toInsert("q'{", "}'"); * //yields this output * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{[email protected]}', q'{Monroe}'); * </pre> * @param leftStringQuote - left quote for a string value, this can be different for different databases. * @param rightStringQuote - left quote for a string value, this can be different for different databases. * @return SQL INSERT string; */ public String toInsert(String leftStringQuote, String rightStringQuote){ return toInsert(new SimpleFormatter(java.sql.Date.class, "'", "'"), new SimpleFormatter(Timestamp.class, "'", "'"), new SimpleFormatter(String.class, leftStringQuote, rightStringQuote)); } /** * TODO: write good JavaDoc, use code inside method above * * @param formatters * @return */ public String toInsert(Formatter ... formatters){ HashMap<Class, Formatter> formatterMap = new HashMap<Class, Formatter>(); for(Formatter f: formatters){ formatterMap.put(f.getValueClass(), f); } List<String> names = new ArrayList<String>(attributes.keySet()); Collections.sort(names); List<Object> values = new ArrayList(); for(String name: names){ Object value = get(name); if(value == null){ values.add("NULL"); } else if (value instanceof String && !formatterMap.containsKey(String.class)){ values.add("'" + value + "'"); }else{ if(formatterMap.containsKey(value.getClass())){ values.add(formatterMap.get(value.getClass()).format(value)); }else{ values.add(value); } } } return new StringBuffer("INSERT INTO ").append(getMetaModelLocal().getTableName()).append(" (") .append(Util.join(names, ", ")).append(") VALUES (").append(Util.join(values, ", ")).append(")").toString(); } /** * Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. */ public static void purgeCache(){ MetaModel mm = getMetaModel(); if(mm.cached()){ QueryCache.instance().purgeTableCache(mm.getTableName()); } } /** * Convenience method: converts ID value to Long and returns it. * * @return value of attribute corresponding to <code>getIdName()</code>, converted to Long. */ public Long getLongId() { Object id = get(getIdName()); if (id == null) { throw new NullPointerException(getIdName() + " is null, cannot convert to Long"); } return Convert.toLong(id); } private static void purgeEdges(){ //this is to eliminate side effects of cache on associations. //TODO: Need to write tests for cases; // 1. One to many relationship. Parent and child are cached. // When a new child inserted, the parent.getAll(Child.class) should see that // 2. Many to many. When a new join inserted, updated or deleted, the one.getAll(Other.class) should see the difference. //Purge associated targets MetaModel metaModel = getMetaModel(); List<Association> associations = metaModel.getOneToManyAssociations(); for(Association association: associations){ QueryCache.instance().purgeTableCache(association.getTarget()); } //Purge edges in case this model represents a join List<String> edges = Registry.instance().getEdges(metaModel.getTableName()); for(String edge: edges){ QueryCache.instance().purgeTableCache(edge); } } } diff --git a/activejdbc/src/test/java/activejdbc/SetParentTest.java b/activejdbc/src/test/java/activejdbc/SetParentTest.java index 31030346..eb5a853f 100644 --- a/activejdbc/src/test/java/activejdbc/SetParentTest.java +++ b/activejdbc/src/test/java/activejdbc/SetParentTest.java @@ -1,64 +1,74 @@ /* Copyright 2009-2010 Igor Polevoy 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 activejdbc; import activejdbc.test.ActiveJDBCTest; import activejdbc.test_models.Computer; import activejdbc.test_models.Keyboard; import activejdbc.test_models.Motherboard; +import activejdbc.test_models.Person; import org.junit.Before; import org.junit.Test; /** * @author Igor Polevoy */ public class SetParentTest extends ActiveJDBCTest { @Before public void before() throws Exception { super.before(); resetTables("motherboards","keyboards", "computers"); } @Test(expected = IllegalArgumentException.class) public void shouldRejectNullParent(){ Computer c = new Computer(); c.setParent(null); } @Test(expected = IllegalArgumentException.class) public void shouldRejectNewParent(){ Computer c = new Computer(); c.setParent(new Motherboard()); } + @Test(expected = IllegalArgumentException.class) + public void shouldRejectUnrelatedParent(){ + + resetTable("people"); + Computer c= new Computer(); + c.setParent(Person.findById(1));// must fail because Person and Computer are not related + } + + @Test public void shouldAcceptTwoParents(){ Motherboard m = (Motherboard)Motherboard.createIt("description", "board 1"); Keyboard k = (Keyboard)Keyboard.createIt("description", "blah"); Computer c = new Computer(); c.setParent(m); c.setParent(k); c.save(); c = (Computer)Computer.findById(c.getId()); a(c.get(m.getIdName())).shouldBeEqual(m.getId()); a(c.get(k.getIdName())).shouldBeEqual(k.getId()); } }
false
false
null
null
diff --git a/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/common/JEditorTestCellServerState.java b/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/common/JEditorTestCellServerState.java index 09369ae65..fbc875c0b 100644 --- a/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/common/JEditorTestCellServerState.java +++ b/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/common/JEditorTestCellServerState.java @@ -1,106 +1,106 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ -package org.jdesktop.wonderland.modules.jeditortest.server; +package org.jdesktop.wonderland.modules.jeditortest.common; import com.jme.math.Vector2f; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.jdesktop.wonderland.modules.appbase.common.cell.App2DCellServerState; import org.jdesktop.wonderland.common.cell.state.annotation.ServerState; /** * The WFS server state class for JEditorTestCellMO. * * @author deronj */ @XmlRootElement(name="jeditortest-cell") @ServerState public class JEditorTestCellServerState extends App2DCellServerState { /** The user's preferred width of the JEditor test window. */ @XmlElement(name="preferredWidth") public int preferredWidth = 300; /** The user's preferred height of the JEditor test window. */ @XmlElement(name="preferredHeight") public int preferredHeight = 300; /** The X pixel scale of the JEditor test window. */ @XmlElement(name="pixelScaleX") public float pixelScaleX = 0.01f; /** The Y pixel scale of the JEditor test window. */ @XmlElement(name="pixelScaleY") public float pixelScaleY = 0.01f; /** Default constructor */ public JEditorTestCellServerState() {} public String getServerClassName() { return "org.jdesktop.wonderland.modules.jeditortest.server.JEditorTestCellMO"; } @XmlTransient public int getPreferredWidth () { return preferredWidth; } public void setPreferredWidth (int preferredWidth) { this.preferredWidth = preferredWidth; } @XmlTransient public int getPreferredHeight () { return preferredHeight; } public void setPreferredHeight (int preferredHeight) { this.preferredHeight = preferredHeight; } @XmlTransient public float getPixelScaleX () { return pixelScaleX; } public void setPixelScaleX (float pixelScale) { this.pixelScaleX = pixelScaleX; } @XmlTransient public float getPixelScaleY () { return pixelScaleY; } public void setPixelScaleY (float pixelScale) { this.pixelScaleY = pixelScaleY; } /** * Returns a string representation of this class. * * @return The server state information as a string. */ @Override public String toString() { return super.toString() + " [JEditorTestCellServerState]: " + "preferredWidth=" + preferredWidth + "," + "preferredHeight=" + preferredHeight + "," + "pixelScaleX=" + pixelScaleX + "," + "pixelScaleY=" + pixelScaleY; } } diff --git a/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/server/JEditorTestCellMO.java b/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/server/JEditorTestCellMO.java index 0dfe6cdd2..b8c18565e 100644 --- a/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/server/JEditorTestCellMO.java +++ b/modules/foundation/jeditortest/src/classes/org/jdesktop/wonderland/modules/jeditortest/server/JEditorTestCellMO.java @@ -1,82 +1,83 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.jeditortest.server; import com.jme.math.Vector2f; import org.jdesktop.wonderland.common.ExperimentalAPI; import org.jdesktop.wonderland.common.cell.ClientCapabilities; import org.jdesktop.wonderland.common.cell.state.CellClientState; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.modules.jeditortest.common.JEditorTestCellClientState; +import org.jdesktop.wonderland.modules.jeditortest.common.JEditorTestCellServerState; import org.jdesktop.wonderland.modules.appbase.server.cell.App2DCellMO; import org.jdesktop.wonderland.server.comms.WonderlandClientID; /** * A server cell associated with a JEditor test. * * @author nsimpson,deronj */ @ExperimentalAPI public class JEditorTestCellMO extends App2DCellMO { /** The preferred width (from the WFS file) */ private int preferredWidth; /** The preferred height (from the WFS file) */ private int preferredHeight; /** Default constructor, used when the cell is created via WFS */ public JEditorTestCellMO() { super(); } /** * {@inheritDoc} */ @Override protected String getClientCellClassName(WonderlandClientID clientID, ClientCapabilities capabilities) { return "org.jdesktop.wonderland.modules.jeditortest.client.JEditorTestCell"; } /** * {@inheritDoc} */ @Override protected CellClientState getClientState (CellClientState cellClientState, WonderlandClientID clientID, ClientCapabilities capabilities) { if (cellClientState == null) { cellClientState = new JEditorTestCellClientState(pixelScale); } ((JEditorTestCellClientState)cellClientState).setPreferredWidth(preferredWidth); ((JEditorTestCellClientState)cellClientState).setPreferredHeight(preferredHeight); return super.getClientState(cellClientState, clientID, capabilities); } /** * {@inheritDoc} */ @Override public void setServerState(CellServerState serverState) { super.setServerState(serverState); JEditorTestCellServerState state = (JEditorTestCellServerState) serverState; preferredWidth = state.getPreferredWidth(); preferredHeight = state.getPreferredHeight(); pixelScale = new Vector2f(state.getPixelScaleX(), state.getPixelScaleY()); } } diff --git a/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/common/cell/WhiteboardCellServerState.java b/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/common/cell/WhiteboardCellServerState.java index adab46535..e2b60e02b 100644 --- a/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/common/cell/WhiteboardCellServerState.java +++ b/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/common/cell/WhiteboardCellServerState.java @@ -1,103 +1,103 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ -package org.jdesktop.wonderland.modules.simplewhiteboard.server.cell; +package org.jdesktop.wonderland.modules.simplewhiteboard.common.cell; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.jdesktop.wonderland.common.cell.state.annotation.ServerState; import org.jdesktop.wonderland.modules.appbase.common.cell.App2DCellServerState; /** * The WFS server state class for WhiteboardCellMO. * * @author deronj */ @XmlRootElement(name="simplewhiteboard-cell") @ServerState public class WhiteboardCellServerState extends App2DCellServerState { /** The user's preferred width of the whiteboard window. */ @XmlElement(name="preferredWidth") public int preferredWidth = 1024; /** The user's preferred height of the whiteboard window. */ @XmlElement(name="preferredHeight") public int preferredHeight = 768; /** The X pixel scale of the whiteboard window. */ @XmlElement(name="pixelScaleX") public float pixelScaleX = 0.01f; /** The Y pixel scale of the whiteboard window. */ @XmlElement(name="pixelScaleY") public float pixelScaleY = 0.01f; /** Default constructor */ public WhiteboardCellServerState() {} public String getServerClassName() { return "org.jdesktop.wonderland.modules.simplewhiteboard.server.cell.WhiteboardCellMO"; } @XmlTransient public int getPreferredWidth () { return preferredWidth; } public void setPreferredWidth (int preferredWidth) { this.preferredWidth = preferredWidth; } @XmlTransient public int getPreferredHeight () { return preferredHeight; } public void setPreferredHeight (int preferredHeight) { this.preferredHeight = preferredHeight; } @XmlTransient public float getPixelScaleX () { return pixelScaleX; } public void setPixelScaleX (float pixelScale) { this.pixelScaleX = pixelScaleX; } @XmlTransient public float getPixelScaleY () { return pixelScaleY; } public void setPixelScaleY (float pixelScale) { this.pixelScaleY = pixelScaleY; } /** * Returns a string representation of this class. * * @return The server state information as a string. */ @Override public String toString() { return super.toString() + " [WhiteboardCellServerState]: " + "preferredWidth=" + preferredWidth + "," + "preferredHeight=" + preferredHeight + "," + "pixelScaleX=" + pixelScaleX + "," + "pixelScaleY=" + pixelScaleY; } } diff --git a/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/server/cell/WhiteboardCellMO.java b/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/server/cell/WhiteboardCellMO.java index 1a2495a2a..d7e12c9a2 100644 --- a/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/server/cell/WhiteboardCellMO.java +++ b/modules/foundation/simplewhiteboard/src/classes/org/jdesktop/wonderland/modules/simplewhiteboard/server/cell/WhiteboardCellMO.java @@ -1,200 +1,201 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.simplewhiteboard.server.cell; import com.jme.math.Vector2f; import com.sun.sgs.app.AppContext; import com.sun.sgs.app.ManagedReference; import java.util.Iterator; import java.util.LinkedList; 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.CellClientState; import org.jdesktop.wonderland.common.cell.messages.CellMessage; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.server.cell.ChannelComponentMO; import org.jdesktop.wonderland.server.comms.WonderlandClientSender; import org.jdesktop.wonderland.modules.simplewhiteboard.common.WhiteboardAction.Action; import org.jdesktop.wonderland.modules.simplewhiteboard.common.WhiteboardCommand.Command; import org.jdesktop.wonderland.modules.appbase.server.cell.App2DCellMO; import org.jdesktop.wonderland.modules.simplewhiteboard.common.cell.WhiteboardCellClientState; +import org.jdesktop.wonderland.modules.simplewhiteboard.common.cell.WhiteboardCellServerState; import org.jdesktop.wonderland.modules.simplewhiteboard.common.cell.WhiteboardCompoundCellMessage; import org.jdesktop.wonderland.modules.simplewhiteboard.server.WhiteboardComponentMO; import org.jdesktop.wonderland.server.cell.annotation.UsesCellComponentMO; import org.jdesktop.wonderland.server.comms.WonderlandClientID; /** * A server cell associated with a whiteboard * * @author nsimpson,deronj */ @ExperimentalAPI public class WhiteboardCellMO extends App2DCellMO { private static final Logger logger = Logger.getLogger(WhiteboardCellMO.class.getName()); // The messages list contains the current state of the whiteboard. // It's updated every time a client makes a change to the whiteboard // so that when new clients join, they receive the current state private static LinkedList<WhiteboardCompoundCellMessage> messages; private static WhiteboardCompoundCellMessage lastMessage; /** the channel component for this cell */ @UsesCellComponentMO(ChannelComponentMO.class) private ManagedReference<ChannelComponentMO> channelComponentRef; /** The communications component used to broadcast to all clients */ private ManagedReference<WhiteboardComponentMO> commComponentRef = null; /** The preferred width (from the WFS file) */ private int preferredWidth; /** The preferred height (from the WFS file) */ private int preferredHeight; /** Default constructor, used when the cell is created via WFS */ public WhiteboardCellMO() { super(); WhiteboardComponentMO commComponent = new WhiteboardComponentMO(this); commComponentRef = AppContext.getDataManager().createReference(commComponent); addComponent(commComponent); messages = new LinkedList<WhiteboardCompoundCellMessage>(); } /** * {@inheritDoc} */ @Override protected String getClientCellClassName(WonderlandClientID clientID, ClientCapabilities capabilities) { return "org.jdesktop.wonderland.modules.simplewhiteboard.client.cell.WhiteboardCell"; } /** * {@inheritDoc} */ @Override protected void setLive(boolean live) { super.setLive(live); // force a local channel channelComponentRef.get().addLocalChannelRequest(WhiteboardCellMO.class.getName()); } /** * {@inheritDoc} */ @Override protected CellClientState getClientState(CellClientState cellClientState, WonderlandClientID clientID, ClientCapabilities capabilities) { // If the cellClientState is null, create one if (cellClientState == null) { cellClientState = new WhiteboardCellClientState(pixelScale); } ((WhiteboardCellClientState)cellClientState).setPreferredWidth(preferredWidth); ((WhiteboardCellClientState)cellClientState).setPreferredHeight(preferredHeight); return super.getClientState(cellClientState, clientID, capabilities); } /** * {@inheritDoc} */ @Override public void setServerState(CellServerState serverState) { super.setServerState(serverState); WhiteboardCellServerState state = (WhiteboardCellServerState) serverState; preferredWidth = state.getPreferredWidth(); preferredHeight = state.getPreferredHeight(); pixelScale = new Vector2f(state.getPixelScaleX(), state.getPixelScaleY()); } /** * Process a message from a client. * * Sync message: send all accumulated messages back to the client (the sender). * All other messages: broadcast to <bold>all</bold> cells (including the sender!) * * @param clientSender The sender object for the client who sent the message. * @param clientSession The session for the client who sent the message. * @param message The message which was received. * @param commComponent The communications component that received the message. */ public void receivedMessage(WonderlandClientSender clientSender, WonderlandClientID clientID, CellMessage message) { WhiteboardCompoundCellMessage cmsg = (WhiteboardCompoundCellMessage) message; logger.fine("received whiteboard message: " + cmsg); WhiteboardComponentMO commComponent = commComponentRef.getForUpdate(); if (cmsg.getAction() == Action.REQUEST_SYNC) { logger.fine("sending " + messages.size() + " whiteboard sync messages"); Iterator<WhiteboardCompoundCellMessage> iter = messages.iterator(); while (iter.hasNext()) { WhiteboardCompoundCellMessage msg = iter.next(); clientSender.send(clientID, msg); } } else { // Create the copy of the message to be broadcast to clients WhiteboardCompoundCellMessage msg = new WhiteboardCompoundCellMessage(cmsg.getClientID(), cmsg.getCellID(), cmsg.getAction()); switch (cmsg.getAction()) { case SET_TOOL: // tool msg.setTool(cmsg.getTool()); break; case SET_COLOR: // color msg.setColor(cmsg.getColor()); break; case MOVE_TO: case DRAG_TO: // position msg.setPositions(cmsg.getPositions()); break; case REQUEST_SYNC: break; case EXECUTE_COMMAND: // command msg.setCommand(cmsg.getCommand()); break; } // record the message in setup data (move events are not recorded) if (cmsg.getAction() == Action.EXECUTE_COMMAND) { if (cmsg.getCommand() == Command.ERASE) { // clear the action history logger.fine("clearing message history"); messages.clear(); } } else { if (cmsg.getAction() != Action.MOVE_TO) { if ((lastMessage != null) && lastMessage.getAction() == Action.MOVE_TO) { messages.add(lastMessage); } // Must guarantee that the original sender doesn't ignore this when it is played back during a sync cmsg.setClientID(null); messages.add(cmsg); } } lastMessage = cmsg; // Broadcast message to all clients (including the original sender of the message). commComponent.sendAllClients(clientID, msg); } } } diff --git a/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/common/SwingMenuTestCellServerState.java b/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/common/SwingMenuTestCellServerState.java index 817087c18..40751370b 100644 --- a/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/common/SwingMenuTestCellServerState.java +++ b/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/common/SwingMenuTestCellServerState.java @@ -1,105 +1,105 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ -package org.jdesktop.wonderland.modules.swingmenutest.server; +package org.jdesktop.wonderland.modules.swingmenutest.common; import com.jme.math.Vector2f; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.jdesktop.wonderland.modules.appbase.common.cell.App2DCellServerState; import org.jdesktop.wonderland.common.cell.state.annotation.ServerState; /** * The WFS server state class for SwingMenuTestCellMO. * * @author deronj */ @XmlRootElement(name="swingmenutest-cell") @ServerState public class SwingMenuTestCellServerState extends App2DCellServerState { /** The user's preferred width of the Swing test window. */ @XmlElement(name="preferredWidth") public int preferredWidth = 500; /** The user's preferred height of the Swing test window. */ @XmlElement(name="preferredHeight") public int preferredHeight = 100; /** The X pixel scale of the Swing test window. */ @XmlElement(name="pixelScaleX") public float pixelScaleX = 0.01f; /** The Y pixel scale of the Swing test window. */ @XmlElement(name="pixelScaleY") public float pixelScaleY = 0.01f; /** Default constructor */ public SwingMenuTestCellServerState() {} public String getServerClassName() { return "org.jdesktop.wonderland.modules.swingmenutest.server.SwingMenuTestCellMO"; } @XmlTransient public int getPreferredWidth () { return preferredWidth; } public void setPreferredWidth (int preferredWidth) { this.preferredWidth = preferredWidth; } @XmlTransient public int getPreferredHeight () { return preferredHeight; } public void setPreferredHeight (int preferredHeight) { this.preferredHeight = preferredHeight; } @XmlTransient public float getPixelScaleX () { return pixelScaleX; } public void setPixelScaleX (float pixelScale) { this.pixelScaleX = pixelScaleX; } @XmlTransient public float getPixelScaleY () { return pixelScaleY; } public void setPixelScaleY (float pixelScale) { this.pixelScaleY = pixelScaleY; } /** * Returns a string representation of this class. * * @return The server state information as a string. */ @Override public String toString() { return super.toString() + " [SwingMenuTestCellServerState]: " + "preferredWidth=" + preferredWidth + "," + "preferredHeight=" + preferredHeight + "," + "pixelScaleX=" + pixelScaleX + "," + "pixelScaleY=" + pixelScaleY; } } diff --git a/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/server/SwingMenuTestCellMO.java b/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/server/SwingMenuTestCellMO.java index 6f44ce940..8cb5ed90b 100644 --- a/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/server/SwingMenuTestCellMO.java +++ b/modules/foundation/swingmenutest/src/classes/org/jdesktop/wonderland/modules/swingmenutest/server/SwingMenuTestCellMO.java @@ -1,82 +1,83 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.swingmenutest.server; import com.jme.math.Vector2f; import org.jdesktop.wonderland.common.ExperimentalAPI; import org.jdesktop.wonderland.common.cell.ClientCapabilities; import org.jdesktop.wonderland.common.cell.state.CellClientState; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.modules.swingmenutest.common.SwingMenuTestCellClientState; +import org.jdesktop.wonderland.modules.swingmenutest.common.SwingMenuTestCellServerState; import org.jdesktop.wonderland.modules.appbase.server.cell.App2DCellMO; import org.jdesktop.wonderland.server.comms.WonderlandClientID; /** * A server cell associated with a Swing test. * * @author nsimpson,deronj */ @ExperimentalAPI public class SwingMenuTestCellMO extends App2DCellMO { /** The preferred width (from the WFS file) */ private int preferredWidth; /** The preferred height (from the WFS file) */ private int preferredHeight; /** Default constructor, used when the cell is created via WFS */ public SwingMenuTestCellMO() { super(); } /** * {@inheritDoc} */ @Override protected String getClientCellClassName(WonderlandClientID clientID, ClientCapabilities capabilities) { return "org.jdesktop.wonderland.modules.swingmenutest.client.SwingMenuTestCell"; } /** * {@inheritDoc} */ @Override protected CellClientState getClientState (CellClientState cellClientState, WonderlandClientID clientID, ClientCapabilities capabilities) { if (cellClientState == null) { cellClientState = new SwingMenuTestCellClientState(pixelScale); } ((SwingMenuTestCellClientState)cellClientState).setPreferredWidth(preferredWidth); ((SwingMenuTestCellClientState)cellClientState).setPreferredHeight(preferredHeight); return super.getClientState(cellClientState, clientID, capabilities); } /** * {@inheritDoc} */ @Override public void setServerState(CellServerState serverState) { super.setServerState(serverState); SwingMenuTestCellServerState state = (SwingMenuTestCellServerState) serverState; preferredWidth = state.getPreferredWidth(); preferredHeight = state.getPreferredHeight(); pixelScale = new Vector2f(state.getPixelScaleX(), state.getPixelScaleY()); } }
false
false
null
null
diff --git a/src/java/com/sun/facelets/tag/core/AttributeHandler.java b/src/java/com/sun/facelets/tag/core/AttributeHandler.java index c2ad154..0c2144c 100644 --- a/src/java/com/sun/facelets/tag/core/AttributeHandler.java +++ b/src/java/com/sun/facelets/tag/core/AttributeHandler.java @@ -1,86 +1,87 @@ /** * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.com/cddl/ * * 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.sun.facelets.tag.core; import java.io.IOException; import javax.el.ELException; import javax.faces.FacesException; import javax.faces.component.UIComponent; import com.sun.facelets.FaceletContext; import com.sun.facelets.FaceletException; +import com.sun.facelets.el.ELAdaptor; import com.sun.facelets.tag.TagAttribute; import com.sun.facelets.tag.TagConfig; import com.sun.facelets.tag.TagException; import com.sun.facelets.tag.TagHandler; /** * Sets the specified name and attribute on the parent UIComponent. If the * "value" specified is not a literal, it will instead set the ValueExpression * on the UIComponent. * <p /> * See <a target="_new" * href="http://java.sun.com/j2ee/javaserverfaces/1.1_01/docs/tlddocs/f/attribute.html">tag * documentation</a>. * * @see javax.faces.component.UIComponent#getAttributes() * @see javax.faces.component.UIComponent#setValueExpression(java.lang.String, * javax.el.ValueExpression) * @author Jacob Hookom - * @version $Id: AttributeHandler.java,v 1.2 2005-07-20 06:37:08 jhook Exp $ + * @version $Id: AttributeHandler.java,v 1.3 2005-07-20 17:51:26 jhook Exp $ */ public final class AttributeHandler extends TagHandler { private final TagAttribute name; private final TagAttribute value; /** * @param config */ public AttributeHandler(TagConfig config) { super(config); this.name = this.getRequiredAttribute("name"); this.value = this.getRequiredAttribute("value"); } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, * javax.faces.component.UIComponent) */ public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { if (parent == null) { throw new TagException(this.tag, "Parent UIComponent was null"); } // only process if the parent is new to the tree if (parent.getParent() == null) { String n = this.name.getValue(ctx); if (!parent.getAttributes().containsKey(n)) { if (this.value.isLiteral()) { parent.getAttributes().put(n, this.value.getValue()); } else { - parent.setValueExpression(n, this.value.getValueExpression( - ctx, Object.class)); + ELAdaptor.setExpression(parent, n, this.value + .getValueExpression(ctx, Object.class)); } } } } }
false
false
null
null
diff --git a/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java b/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java index 86827475..67867ddd 100644 --- a/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java +++ b/bundles/org.eclipse.equinox.launcher/src/org/eclipse/equinox/launcher/Main.java @@ -1,2390 +1,2391 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.launcher; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.security.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.equinox.internal.launcher.Constants; /** * The launcher for Eclipse. */ public class Main { /** * Indicates whether this instance is running in debug mode. */ protected boolean debug = false; /** * The location of the launcher to run. */ protected String bootLocation = null; /** * The location of the install root */ protected URL installLocation = null; /** * The location of the configuration information for this instance */ protected URL configurationLocation = null; /** * The location of the configuration information in the install root */ protected String parentConfigurationLocation = null; /** * The id of the bundle that will contain the framework to run. Defaults to org.eclipse.osgi. */ protected String framework = OSGI; /** * The extra development time class path entries for the framework. */ protected String devClassPath = null; /* * The extra development time class path entries for all bundles. */ private Properties devClassPathProps = null; /** * Indicates whether this instance is running in development mode. */ protected boolean inDevelopmentMode = false; /** * Indicates which OS was passed in with -os */ protected String os = null; protected String ws = null; protected String arch = null; // private String name = null; // The name to brand the launcher // private String launcher = null; // The full path to the launcher private String library = null; private String exitData = null; private String vm = null; private String[] vmargs = null; private String[] commands = null; String[] extensionPaths = null; JNIBridge bridge = null; // splash handling private boolean showSplash = false; private String splashLocation = null; private String endSplash = null; private boolean initialize = false; private boolean splashDown = false; public final class SplashHandler extends Thread { public void run() { takeDownSplash(); } public void updateSplash() { if(bridge != null) { bridge.updateSplash(); } } } private final Thread splashHandler = new SplashHandler(); // command line args private static final String FRAMEWORK = "-framework"; //$NON-NLS-1$ private static final String INSTALL = "-install"; //$NON-NLS-1$ private static final String INITIALIZE = "-initialize"; //$NON-NLS-1$ private static final String VM = "-vm"; //$NON-NLS-1$ private static final String VMARGS = "-vmargs"; //$NON-NLS-1$ private static final String DEBUG = "-debug"; //$NON-NLS-1$ private static final String DEV = "-dev"; //$NON-NLS-1$ private static final String CONFIGURATION = "-configuration"; //$NON-NLS-1$ private static final String NOSPLASH = "-nosplash"; //$NON-NLS-1$ private static final String SHOWSPLASH = "-showsplash"; //$NON-NLS-1$ private static final String EXITDATA = "-exitdata"; //$NON-NLS-1$ private static final String NAME = "-name"; //$NON-NLS-1$ private static final String LAUNCHER = "-launcher"; //$NON-NLS-1$ private static final String LIBRARY = "--launcher.library"; //$NON-NLS-1$ private static final String NL = "-nl"; //$NON-NLS-1$ private static final String ENDSPLASH = "-endsplash"; //$NON-NLS-1$ private static final String SPLASH_IMAGE = "splash.bmp"; //$NON-NLS-1$ private static final String CLEAN = "-clean"; //$NON-NLS-1$ private static final String NOEXIT = "-noExit"; //$NON-NLS-1$ private static final String OS = "-os"; //$NON-NLS-1$ private static final String WS = "-ws"; //$NON-NLS-1$ private static final String ARCH = "-arch"; //$NON-NLS-1$ private static final String OSGI = "org.eclipse.osgi"; //$NON-NLS-1$ private static final String STARTER = "org.eclipse.core.runtime.adaptor.EclipseStarter"; //$NON-NLS-1$ private static final String PLATFORM_URL = "platform:/base/"; //$NON-NLS-1$ private static final String ECLIPSE_PROPERTIES = "eclipse.properties"; //$NON-NLS-1$ private static final String FILE_SCHEME = "file:"; //$NON-NLS-1$ protected static final String REFERENCE_SCHEME = "reference:"; //$NON-NLS-1$ protected static final String JAR_SCHEME = "jar:"; //$NON-NLS-1$ // constants: configuration file location private static final String CONFIG_DIR = "configuration/"; //$NON-NLS-1$ private static final String CONFIG_FILE = "config.ini"; //$NON-NLS-1$ private static final String CONFIG_FILE_TEMP_SUFFIX = ".tmp"; //$NON-NLS-1$ private static final String CONFIG_FILE_BAK_SUFFIX = ".bak"; //$NON-NLS-1$ private static final String ECLIPSE = "eclipse"; //$NON-NLS-1$ private static final String PRODUCT_SITE_MARKER = ".eclipseproduct"; //$NON-NLS-1$ private static final String PRODUCT_SITE_ID = "id"; //$NON-NLS-1$ private static final String PRODUCT_SITE_VERSION = "version"; //$NON-NLS-1$ // constants: System property keys and/or configuration file elements private static final String PROP_USER_HOME = "user.home"; //$NON-NLS-1$ private static final String PROP_USER_DIR = "user.dir"; //$NON-NLS-1$ private static final String PROP_INSTALL_AREA = "osgi.install.area"; //$NON-NLS-1$ private static final String PROP_CONFIG_AREA = "osgi.configuration.area"; //$NON-NLS-1$ private static final String PROP_CONFIG_AREA_DEFAULT = "osgi.configuration.area.default"; //$NON-NLS-1$ private static final String PROP_BASE_CONFIG_AREA = "osgi.baseConfiguration.area"; //$NON-NLS-1$ private static final String PROP_SHARED_CONFIG_AREA = "osgi.sharedConfiguration.area"; //$NON-NLS-1$ private static final String PROP_CONFIG_CASCADED = "osgi.configuration.cascaded"; //$NON-NLS-1$ protected static final String PROP_FRAMEWORK = "osgi.framework"; //$NON-NLS-1$ private static final String PROP_SPLASHPATH = "osgi.splashPath"; //$NON-NLS-1$ private static final String PROP_SPLASHLOCATION = "osgi.splashLocation"; //$NON-NLS-1$ private static final String PROP_CLASSPATH = "osgi.frameworkClassPath"; //$NON-NLS-1$ private static final String PROP_EXTENSIONS = "osgi.framework.extensions"; //$NON-NLS-1$ private static final String PROP_FRAMEWORK_SYSPATH = "osgi.syspath"; //$NON-NLS-1$ private static final String PROP_FRAMEWORK_SHAPE = "osgi.framework.shape"; //$NON-NLS-1$ private static final String PROP_LOGFILE = "osgi.logfile"; //$NON-NLS-1$ private static final String PROP_REQUIRED_JAVA_VERSION = "osgi.requiredJavaVersion"; //$NON-NLS-1$ private static final String PROP_PARENT_CLASSLOADER = "osgi.parentClassloader"; //$NON-NLS-1$ private static final String PROP_FRAMEWORK_PARENT_CLASSLOADER = "osgi.frameworkParentClassloader"; //$NON-NLS-1$ private static final String PROP_NL = "osgi.nl"; //$NON-NLS-1$ static final String PROP_NOSHUTDOWN = "osgi.noShutdown"; //$NON-NLS-1$ private static final String PROP_DEBUG = "osgi.debug"; //$NON-NLS-1$ private static final String PROP_EXITCODE = "eclipse.exitcode"; //$NON-NLS-1$ private static final String PROP_EXITDATA = "eclipse.exitdata"; //$NON-NLS-1$ private static final String PROP_VM = "eclipse.vm"; //$NON-NLS-1$ private static final String PROP_VMARGS = "eclipse.vmargs"; //$NON-NLS-1$ private static final String PROP_COMMANDS = "eclipse.commands"; //$NON-NLS-1$ private static final String PROP_ECLIPSESECURITY = "eclipse.security"; //$NON-NLS-1$ // Data mode constants for user, configuration and data locations. private static final String NONE = "@none"; //$NON-NLS-1$ private static final String NO_DEFAULT = "@noDefault"; //$NON-NLS-1$ private static final String USER_HOME = "@user.home"; //$NON-NLS-1$ private static final String USER_DIR = "@user.dir"; //$NON-NLS-1$ // types of parent classloaders the framework can have private static final String PARENT_CLASSLOADER_APP = "app"; //$NON-NLS-1$ private static final String PARENT_CLASSLOADER_EXT = "ext"; //$NON-NLS-1$ private static final String PARENT_CLASSLOADER_BOOT = "boot"; //$NON-NLS-1$ private static final String PARENT_CLASSLOADER_CURRENT = "current"; //$NON-NLS-1$ // log file handling protected static final String SESSION = "!SESSION"; //$NON-NLS-1$ protected static final String ENTRY = "!ENTRY"; //$NON-NLS-1$ protected static final String MESSAGE = "!MESSAGE"; //$NON-NLS-1$ protected static final String STACK = "!STACK"; //$NON-NLS-1$ protected static final int ERROR = 4; protected static final String PLUGIN_ID = "org.eclipse.equinox.launcher"; //$NON-NLS-1$ protected File logFile = null; protected BufferedWriter log = null; protected boolean newSession = true; /** * A structured form for a version identifier. * * @see http://java.sun.com/j2se/versioning_naming.html for information on valid version strings */ static class Identifier { private static final String DELIM = ". _-"; //$NON-NLS-1$ private int major, minor, service; Identifier(int major, int minor, int service) { super(); this.major = major; this.minor = minor; this.service = service; } /** * @throws NumberFormatException if cannot parse the major and minor version components */ Identifier(String versionString) { super(); StringTokenizer tokenizer = new StringTokenizer(versionString, DELIM); // major if (tokenizer.hasMoreTokens()) major = Integer.parseInt(tokenizer.nextToken()); // minor if (tokenizer.hasMoreTokens()) minor = Integer.parseInt(tokenizer.nextToken()); try { // service if (tokenizer.hasMoreTokens()) service = Integer.parseInt(tokenizer.nextToken()); } catch (NumberFormatException nfe) { // ignore the service qualifier in that case and default to 0 // this will allow us to tolerate other non-conventional version numbers } } /** * Returns true if this id is considered to be greater than or equal to the given baseline. * e.g. * 1.2.9 >= 1.3.1 -> false * 1.3.0 >= 1.3.1 -> false * 1.3.1 >= 1.3.1 -> true * 1.3.2 >= 1.3.1 -> true * 2.0.0 >= 1.3.1 -> true */ boolean isGreaterEqualTo(Identifier minimum) { if (major < minimum.major) return false; if (major > minimum.major) return true; // major numbers are equivalent so check minor if (minor < minimum.minor) return false; if (minor > minimum.minor) return true; // minor numbers are equivalent so check service return service >= minimum.service; } } private String getWS() { if (ws != null) return ws; String os = getOS(); if (os.equals(Constants.OS_WIN32)) return Constants.WS_WIN32; if (os.equals(Constants.OS_LINUX)) return Constants.WS_GTK; if (os.equals(Constants.OS_MACOSX)) return Constants.WS_CARBON; if (os.equals(Constants.OS_HPUX)) return Constants.WS_MOTIF; if (os.equals(Constants.OS_AIX)) return Constants.WS_MOTIF; if (os.equals(Constants.OS_SOLARIS)) return Constants.WS_MOTIF; if (os.equals(Constants.OS_QNX)) return Constants.WS_PHOTON; return Constants.WS_UNKNOWN; } private String getOS() { if (os != null) return os; String osName = System.getProperties().getProperty("os.name"); //$NON-NLS-1$ if (osName.regionMatches(true, 0, Constants.OS_WIN32, 0, 3)) return Constants.OS_WIN32; // EXCEPTION: All mappings of SunOS convert to Solaris if (osName.equalsIgnoreCase(Constants.INTERNAL_OS_SUNOS)) return Constants.OS_SOLARIS; if (osName.equalsIgnoreCase(Constants.INTERNAL_OS_LINUX)) return Constants.OS_LINUX; if (osName.equalsIgnoreCase(Constants.INTERNAL_OS_QNX)) return Constants.OS_QNX; if (osName.equalsIgnoreCase(Constants.INTERNAL_OS_AIX)) return Constants.OS_AIX; if (osName.equalsIgnoreCase(Constants.INTERNAL_OS_HPUX)) return Constants.OS_HPUX; // os.name on Mac OS can be either Mac OS or Mac OS X if (osName.regionMatches(true, 0, Constants.INTERNAL_OS_MACOSX, 0, Constants.INTERNAL_OS_MACOSX.length())) return Constants.OS_MACOSX; return Constants.OS_UNKNOWN; } private String getArch() { if (arch != null) return arch; String name = System.getProperties().getProperty("os.arch");//$NON-NLS-1$ // Map i386 architecture to x86 if (name.equalsIgnoreCase(Constants.INTERNAL_ARCH_I386)) return Constants.ARCH_X86; // Map amd64 architecture to x86_64 else if (name.equalsIgnoreCase(Constants.INTERNAL_AMD64)) return Constants.ARCH_X86_64; return name; } /** * Sets up the JNI bridge to native calls */ private void setupJNI(URL[] defaultPath) { String libPath = null; if (library != null) { File lib = new File(library); if(lib.isDirectory()) { libPath = searchFor("eclipse", lib.getAbsolutePath()); //$NON-NLS-1$ } else if(lib.exists()){ libPath = lib.getAbsolutePath(); } } if(libPath == null) { //find our fragment name String fragmentOS = getOS(); StringBuffer buffer = new StringBuffer(PLUGIN_ID); buffer.append('.'); buffer.append(getWS()); buffer.append('.'); buffer.append(fragmentOS); if(!fragmentOS.equals("macosx")){ //$NON-NLS-1$ buffer.append('.'); buffer.append(getArch()); } String fragmentName = buffer.toString(); String fragment = null; if (bootLocation != null) { URL[] urls = defaultPath; if (urls != null && urls.length > 0) { //the last one is most interesting File entryFile = new File(urls[urls.length - 1].getFile()); String dir = entryFile.getParent(); if (inDevelopmentMode) { String devDir = dir + "/" + PLUGIN_ID + "/fragments"; //$NON-NLS-1$ //$NON-NLS-2$ fragment = searchFor(fragmentName, devDir); } if (fragment == null) fragment = searchFor(fragmentName, dir); } } if(fragment == null) { URL install = getInstallLocation(); String location = install.getFile(); location += "/plugins/"; //$NON-NLS-1$ fragment = searchFor(fragmentName, location); } if(fragment != null) libPath = searchFor("eclipse", fragment); //$NON-NLS-1$ } library = libPath; - bridge = new JNIBridge(library); + if(library != null) + bridge = new JNIBridge(library); } /** * Executes the launch. * * @param args command-line arguments * @exception Exception thrown if a problem occurs during the launch */ protected void basicRun(String[] args) throws Exception { System.getProperties().put("eclipse.startTime", Long.toString(System.currentTimeMillis())); //$NON-NLS-1$ commands = args; String[] passThruArgs = processCommandLine(args); if (!debug) // debug can be specified as system property as well debug = System.getProperty(PROP_DEBUG) != null; setupVMProperties(); processConfiguration(); // need to ensure that getInstallLocation is called at least once to initialize the value. // Do this AFTER processing the configuration to allow the configuration to set // the install location. getInstallLocation(); // locate boot plugin (may return -dev mode variations) URL[] bootPath = getBootPath(bootLocation); //Set up the JNI bridge. We need to know the install location to find the shared library setupJNI(bootPath); //ensure minimum Java version, do this after JNI is set up so that we can write an error message //with exitdata if we fail. if (!checkVersion(System.getProperty("java.version"), System.getProperty(PROP_REQUIRED_JAVA_VERSION))) //$NON-NLS-1$ return; setSecurityPolicy(bootPath); // splash handling is done here, because the default case needs to know // the location of the boot plugin we are going to use handleSplash(bootPath); beforeFwkInvocation(); invokeFramework(passThruArgs, bootPath); } protected void beforeFwkInvocation() { //Nothing to do. } protected void setSecurityPolicy(URL[] bootPath) { String eclipseSecurity = System.getProperty(PROP_ECLIPSESECURITY); if (eclipseSecurity != null) { SecurityManager sm = System.getSecurityManager(); boolean setSM = false; if (sm == null) { if (eclipseSecurity.length() < 1) { eclipseSecurity = "java.lang.SecurityManager"; //$NON-NLS-1$ } try { Class clazz = Class.forName(eclipseSecurity); sm = (SecurityManager) clazz.newInstance(); setSM = true; } catch (Throwable t) { System.getProperties().put("java.security.manager", eclipseSecurity); // let the framework try to load it later. //$NON-NLS-1$ } } ProtectionDomain domain = Main.class.getProtectionDomain(); CodeSource source = null; if (domain != null) source = Main.class.getProtectionDomain().getCodeSource(); if (domain == null || source == null) { log("Can not automatically set the security manager. Please use a policy file."); //$NON-NLS-1$ return; } // get the list of codesource URLs to grant AllPermission to URL[] rootURLs = new URL[bootPath.length + 1]; rootURLs[0] = source.getLocation(); System.arraycopy(bootPath, 0, rootURLs, 1, bootPath.length); // replace the security policy Policy eclipsePolicy = new EclipsePolicy(Policy.getPolicy(), rootURLs); Policy.setPolicy(eclipsePolicy); if (setSM) System.setSecurityManager(sm); } } private void invokeFramework(String[] passThruArgs, URL[] bootPath) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, Error, Exception, InvocationTargetException { String type = System.getProperty(PROP_FRAMEWORK_PARENT_CLASSLOADER, System.getProperty(PROP_PARENT_CLASSLOADER, PARENT_CLASSLOADER_BOOT)); ClassLoader parent = null; if (PARENT_CLASSLOADER_APP.equalsIgnoreCase(type)) parent = ClassLoader.getSystemClassLoader(); else if (PARENT_CLASSLOADER_EXT.equalsIgnoreCase(type)) { ClassLoader appCL = ClassLoader.getSystemClassLoader(); if (appCL != null) parent = appCL.getParent(); } else if (PARENT_CLASSLOADER_CURRENT.equalsIgnoreCase(type)) parent = this.getClass().getClassLoader(); URLClassLoader loader = new StartupClassLoader(bootPath, parent); Class clazz = loader.loadClass(STARTER); Method method = clazz.getDeclaredMethod("run", new Class[] {String[].class, Runnable.class}); //$NON-NLS-1$ try { method.invoke(clazz, new Object[] {passThruArgs, splashHandler}); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof Error) throw (Error) e.getTargetException(); else if (e.getTargetException() instanceof Exception) throw (Exception) e.getTargetException(); else //could be a subclass of Throwable! throw e; } } /** * Checks whether the given available version is greater or equal to the * given required version. * <p>Will set PROP_EXITCODE/PROP_EXITDATA accordingly if check fails.</p> * * @return a boolean indicating whether the checking passed */ private boolean checkVersion(String availableVersion, String requiredVersion) { if (requiredVersion == null || availableVersion == null) return true; try { Identifier required = new Identifier(requiredVersion); Identifier available = new Identifier(availableVersion); boolean compatible = available.isGreaterEqualTo(required); if (!compatible) { // any non-zero value should do it - 14 used to be used for version incompatibility in Eclipse 2.1 System.getProperties().put(PROP_EXITCODE, "14"); //$NON-NLS-1$ System.getProperties().put(PROP_EXITDATA, "<title>Incompatible JVM</title>Version " + availableVersion + " of the JVM is not suitable for this product. Version: "+ requiredVersion + " or greater is required."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } return compatible; } catch (SecurityException e) { // If the security manager won't allow us to get the system property, continue for // now and let things fail later on their own if necessary. return true; } catch (NumberFormatException e) { // If the version string was in a format that we don't understand, continue and // let things fail later on their own if necessary. return true; } } /** * Returns a string representation of the given URL String. This converts * escaped sequences (%..) in the URL into the appropriate characters. * NOTE: due to class visibility there is a copy of this method * in InternalBootLoader */ protected String decode(String urlString) { //try to use Java 1.4 method if available try { Class clazz = URLDecoder.class; Method method = clazz.getDeclaredMethod("decode", new Class[] {String.class, String.class}); //$NON-NLS-1$ //first encode '+' characters, because URLDecoder incorrectly converts //them to spaces on certain class library implementations. if (urlString.indexOf('+') >= 0) { int len = urlString.length(); StringBuffer buf = new StringBuffer(len); for (int i = 0; i < len; i++) { char c = urlString.charAt(i); if (c == '+') buf.append("%2B"); //$NON-NLS-1$ else buf.append(c); } urlString = buf.toString(); } Object result = method.invoke(null, new Object[] {urlString, "UTF-8"}); //$NON-NLS-1$ if (result != null) return (String) result; } catch (Exception e) { //JDK 1.4 method not found -- fall through and decode by hand } //decode URL by hand boolean replaced = false; byte[] encodedBytes = urlString.getBytes(); int encodedLength = encodedBytes.length; byte[] decodedBytes = new byte[encodedLength]; int decodedLength = 0; for (int i = 0; i < encodedLength; i++) { byte b = encodedBytes[i]; if (b == '%') { if(i+2 >= encodedLength) throw new IllegalArgumentException("Malformed URL (\""+urlString+"\"): % must be followed by 2 digits."); //$NON-NLS-1$//$NON-NLS-2$ byte enc1 = encodedBytes[++i]; byte enc2 = encodedBytes[++i]; b = (byte) ((hexToByte(enc1) << 4) + hexToByte(enc2)); replaced = true; } decodedBytes[decodedLength++] = b; } if (!replaced) return urlString; try { return new String(decodedBytes, 0, decodedLength, "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { //use default encoding return new String(decodedBytes, 0, decodedLength); } } /** * Returns the result of converting a list of comma-separated tokens into an array * * @return the array of string tokens * @param prop the initial comma-separated string */ protected String[] getArrayFromList(String prop) { if (prop == null || prop.trim().equals("")) //$NON-NLS-1$ return new String[0]; Vector list = new Vector(); StringTokenizer tokens = new StringTokenizer(prop, ","); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (!token.equals("")) //$NON-NLS-1$ list.addElement(token); } return list.isEmpty() ? new String[0] : (String[]) list.toArray(new String[list.size()]); } /** * Returns the <code>URL</code>-based class path describing where the boot classes * are located when running in development mode. * * @return the url-based class path * @param base the base location * @exception MalformedURLException if a problem occurs computing the class path */ private URL[] getDevPath(URL base) throws IOException { ArrayList result = new ArrayList(5); if (inDevelopmentMode) addDevEntries(base, result, OSGI); //The jars from the base always need to be added, even when running in dev mode (bug 46772) addBaseJars(base, result); return (URL[]) result.toArray(new URL[result.size()]); } URL constructURL(URL url, String name) { //Recognize the following URLs //url: file:foo/dir/ //url: file:foo/file.jar String externalForm = url.toExternalForm(); if (externalForm.endsWith(".jar")) { //$NON-NLS-1$ try { return new URL(JAR_SCHEME + url + "!/" + name); //$NON-NLS-1$ } catch (MalformedURLException e) { //Ignore } } try { return new URL(url, name); } catch (MalformedURLException e) { //Ignore return null; } } private void readFrameworkExtensions(URL base, ArrayList result) throws IOException { String[] extensions = getArrayFromList(System.getProperties().getProperty(PROP_EXTENSIONS)); String parent = new File(base.getFile()).getParent().toString(); ArrayList extensionResults = new ArrayList(extensions.length); for (int i = 0; i < extensions.length; i++) { //Search the extension relatively to the osgi plugin String path = searchFor(extensions[i], parent); if (path == null) { log("Could not find extension: " + extensions[i]); //$NON-NLS-1$ continue; } if (debug) System.out.println("Loading extension: " + extensions[i]); //$NON-NLS-1$ URL extensionURL = null; if (installLocation.getProtocol().equals("file")) { //$NON-NLS-1$ extensionResults.add(path); extensionURL = new File(path).toURL(); } else extensionURL = new URL(installLocation.getProtocol(), installLocation.getHost(), installLocation.getPort(), path); //Load a property file of the extension, merge its content, and in case of dev mode add the bin entries Properties extensionProperties = null; try { extensionProperties = loadProperties(constructURL(extensionURL, ECLIPSE_PROPERTIES)); } catch (IOException e) { if (debug) System.out.println("\t" + ECLIPSE_PROPERTIES + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ } String extensionClassPath = null; if (extensionProperties != null) extensionClassPath = extensionProperties.getProperty(PROP_CLASSPATH); else // this is a "normal" RFC 101 framework extension bundle just put the base path on the classpath extensionProperties = new Properties(); String[] entries = extensionClassPath == null || extensionClassPath.length() == 0 ? new String[] {""} : getArrayFromList(extensionClassPath); //$NON-NLS-1$ String qualifiedPath; if (System.getProperty(PROP_CLASSPATH)==null) qualifiedPath = "."; //$NON-NLS-1$ else qualifiedPath = ""; //$NON-NLS-1$ for (int j = 0; j < entries.length; j++) qualifiedPath += ", " + FILE_SCHEME + path + entries[j]; //$NON-NLS-1$ extensionProperties.put(PROP_CLASSPATH, qualifiedPath); mergeProperties(System.getProperties(), extensionProperties); if (inDevelopmentMode) addDevEntries(extensionURL, result, extensions[i]); } extensionPaths = (String[]) extensionResults.toArray(new String[extensionResults.size()]); } private void addBaseJars(URL base, ArrayList result) throws IOException { String baseJarList = System.getProperty(PROP_CLASSPATH); if (baseJarList == null) { readFrameworkExtensions(base, result); baseJarList = System.getProperties().getProperty(PROP_CLASSPATH); } File fwkFile = new File(base.getFile()); boolean fwkIsDirectory = fwkFile.isDirectory(); //We found where the fwk is, remember it and its shape if (fwkIsDirectory) { System.getProperties().put(PROP_FRAMEWORK_SHAPE, "folder");//$NON-NLS-1$ } else { System.getProperties().put(PROP_FRAMEWORK_SHAPE, "jar");//$NON-NLS-1$ } String fwkPath = new File(new File(base.getFile()).getParent()).getAbsolutePath(); if (Character.isUpperCase(fwkPath.charAt(0))) { char[] chars = fwkPath.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); fwkPath = new String(chars); } System.getProperties().put(PROP_FRAMEWORK_SYSPATH, fwkPath); String[] baseJars = getArrayFromList(baseJarList); if (baseJars.length == 0) { if (!inDevelopmentMode && new File(base.getFile()).isDirectory()) throw new IOException("Unable to initialize " + PROP_CLASSPATH); //$NON-NLS-1$ addEntry(base, result); return; } for (int i = 0; i < baseJars.length; i++) { String string = baseJars[i]; try { // if the string is a file: URL then *carefully* construct the // URL. Otherwisejust try to build a URL. In either case, if we fail, use // string as something to tack on the end of the base. if (string.equals(".")) { //$NON-NLS-1$ addEntry(base, result); } URL url = null; if (string.startsWith(FILE_SCHEME)) url = new File(string.substring(5)).toURL(); else url = new URL(string); addEntry(url, result); } catch (MalformedURLException e) { addEntry(new URL(base, string), result); } } } protected void addEntry(URL url, List result) { if (new File(url.getFile()).exists()) result.add(url); } private void addDevEntries(URL base, List result, String symbolicName) throws MalformedURLException { if (devClassPathProps == null) return; // do nothing String devPathList = devClassPathProps.getProperty(symbolicName); if (devPathList == null) devPathList = devClassPathProps.getProperty("*"); //$NON-NLS-1$ String[] locations = getArrayFromList(devPathList); for (int i = 0; i < locations.length; i++) { String location = locations[i]; File path = new File(location); URL url; if (path.isAbsolute()) url = path.toURL(); else { // dev path is relative, combine with base location char lastChar = location.charAt(location.length() - 1); if ((location.endsWith(".jar") || (lastChar == '/' || lastChar == '\\'))) //$NON-NLS-1$ url = new URL(base, location); else url = new URL(base, location + "/"); //$NON-NLS-1$ } addEntry(url, result); } } /** * Returns the <code>URL</code>-based class path describing where the boot classes are located. * * @return the url-based class path * @param base the base location * @exception MalformedURLException if a problem occurs computing the class path */ protected URL[] getBootPath(String base) throws IOException { URL url = null; if (base != null) { url = buildURL(base, true); } else { // search in the root location url = getInstallLocation(); String path = new File(url.getFile(), "plugins").toString(); //$NON-NLS-1$ path = searchFor(framework, path); if (path == null) throw new RuntimeException("Could not find framework"); //$NON-NLS-1$ if (url.getProtocol().equals("file")) //$NON-NLS-1$ url = new File(path).toURL(); else url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); } if (System.getProperty(PROP_FRAMEWORK) == null) System.getProperties().put(PROP_FRAMEWORK, url.toExternalForm()); if (debug) System.out.println("Framework located:\n " + url.toExternalForm()); //$NON-NLS-1$ // add on any dev path elements URL[] result = getDevPath(url); if (debug) { System.out.println("Framework classpath:"); //$NON-NLS-1$ for (int i = 0; i < result.length; i++) System.out.println(" " + result[i].toExternalForm()); //$NON-NLS-1$ } return result; } /** * Searches for the given target directory starting in the "plugins" subdirectory * of the given location. If one is found then this location is returned; * otherwise an exception is thrown. * * @return the location where target directory was found * @param start the location to begin searching */ protected String searchFor(final String target, String start) { return searchFor(target, null, start); } protected String searchFor(final String target, final String targetSuffix, String start) { // Note that File.list only gives you file names not the complete path from start String[] candidates = new File(start).list(); if (candidates == null) return null; ArrayList matches = new ArrayList(2); for (int i = 0; i < candidates.length; i++) if (candidates[i].equals(target) || candidates[i].startsWith(target + "_")) //$NON-NLS-1$ matches.add(candidates[i]); String[] names = (String[]) matches.toArray(new String[matches.size()]); int result = findMax(names); if (result == -1) return null; File candidate = new File(start, names[result]); return candidate.getAbsolutePath().replace(File.separatorChar, '/') + (candidate.isDirectory() ? "/" : ""); //$NON-NLS-1$//$NON-NLS-2$ } protected int findMax(String[] candidates) { int result = -1; Object maxVersion = null; for (int i = 0; i < candidates.length; i++) { String name = candidates[i]; String version = ""; //$NON-NLS-1$ // Note: directory with version suffix is always > than directory without version suffix int index = name.indexOf('_'); if (index != -1) version = name.substring(index + 1); Object currentVersion = getVersionElements(version); if (maxVersion == null) { result = i; maxVersion = currentVersion; } else { if (compareVersion((Object[]) maxVersion, (Object[]) currentVersion) < 0) { result = i; maxVersion = currentVersion; } } } return result; } /** * Compares version strings. * @return result of comparison, as integer; * <code><0</code> if left < right; * <code>0</code> if left == right; * <code>>0</code> if left > right; */ private int compareVersion(Object[] left, Object[] right) { int result = ((Integer) left[0]).compareTo((Integer) right[0]); // compare major if (result != 0) return result; result = ((Integer) left[1]).compareTo((Integer) right[1]); // compare minor if (result != 0) return result; result = ((Integer) left[2]).compareTo((Integer) right[2]); // compare service if (result != 0) return result; return ((String) left[3]).compareTo((String) right[3]); // compare qualifier } /** * Do a quick parse of version identifier so its elements can be correctly compared. * If we are unable to parse the full version, remaining elements are initialized * with suitable defaults. * @return an array of size 4; first three elements are of type Integer (representing * major, minor and service) and the fourth element is of type String (representing * qualifier). Note, that returning anything else will cause exceptions in the caller. */ private Object[] getVersionElements(String version) { if (version.endsWith(".jar")) //$NON-NLS-1$ version = version.substring(0, version.length() - 4); Object[] result = {new Integer(0), new Integer(0), new Integer(0), ""}; //$NON-NLS-1$ StringTokenizer t = new StringTokenizer(version, "."); //$NON-NLS-1$ String token; int i = 0; while (t.hasMoreTokens() && i < 4) { token = t.nextToken(); if (i < 3) { // major, minor or service ... numeric values try { result[i++] = new Integer(token); } catch (Exception e) { // invalid number format - use default numbers (0) for the rest break; } } else { // qualifier ... string value result[i++] = token; } } return result; } private static URL buildURL(String spec, boolean trailingSlash) { if (spec == null) return null; boolean isFile = spec.startsWith(FILE_SCHEME); try { if (isFile) { File toAdjust = new File(spec.substring(5)); if (toAdjust.isDirectory()) return adjustTrailingSlash(toAdjust.toURL(), trailingSlash); return toAdjust.toURL(); } return new URL(spec); } catch (MalformedURLException e) { // if we failed and it is a file spec, there is nothing more we can do // otherwise, try to make the spec into a file URL. if (isFile) return null; try { File toAdjust = new File(spec); if (toAdjust.isDirectory()) return adjustTrailingSlash(toAdjust.toURL(), trailingSlash); return toAdjust.toURL(); } catch (MalformedURLException e1) { return null; } } } private static URL adjustTrailingSlash(URL url, boolean trailingSlash) throws MalformedURLException { String file = url.getFile(); if (trailingSlash == (file.endsWith("/"))) //$NON-NLS-1$ return url; file = trailingSlash ? file + "/" : file.substring(0, file.length() - 1); //$NON-NLS-1$ return new URL(url.getProtocol(), url.getHost(), file); } private URL buildLocation(String property, URL defaultLocation, String userDefaultAppendage) { URL result = null; String location = System.getProperty(property); System.getProperties().remove(property); // if the instance location is not set, predict where the workspace will be and // put the instance area inside the workspace meta area. try { if (location == null) result = defaultLocation; else if (location.equalsIgnoreCase(NONE)) return null; else if (location.equalsIgnoreCase(NO_DEFAULT)) result = buildURL(location, true); else { if (location.startsWith(USER_HOME)) { String base = substituteVar(location, USER_HOME, PROP_USER_HOME); location = new File(base, userDefaultAppendage).getAbsolutePath(); } else if (location.startsWith(USER_DIR)) { String base = substituteVar(location, USER_DIR, PROP_USER_DIR); location = new File(base, userDefaultAppendage).getAbsolutePath(); } result = buildURL(location, true); } } finally { if (result != null) System.getProperties().put(property, result.toExternalForm()); } return result; } private String substituteVar(String source, String var, String prop) { String value = System.getProperty(prop, ""); //$NON-NLS-1$ return value + source.substring(var.length()); } /** * Retuns the default file system path for the configuration location. * By default the configuration information is in the installation directory * if this is writeable. Otherwise it is located somewhere in the user.home * area relative to the current product. * @return the default file system path for the configuration information */ private String computeDefaultConfigurationLocation() { // 1) We store the config state relative to the 'eclipse' directory if possible // 2) If this directory is read-only // we store the state in <user.home>/.eclipse/<application-id>_<version> where <user.home> // is unique for each local user, and <application-id> is the one // defined in .eclipseproduct marker file. If .eclipseproduct does not // exist, use "eclipse" as the application-id. URL install = getInstallLocation(); // TODO a little dangerous here. Basically we have to assume that it is a file URL. if (install.getProtocol().equals("file")) { //$NON-NLS-1$ File installDir = new File(install.getFile()); if (canWrite(installDir)) return installDir.getAbsolutePath() + File.separator + CONFIG_DIR; } // We can't write in the eclipse install dir so try for some place in the user's home dir return computeDefaultUserAreaLocation(CONFIG_DIR); } private static boolean canWrite(File installDir) { if (installDir.canWrite() == false) return false; if (!installDir.isDirectory()) return false; File fileTest = null; try { // we use the .dll suffix to properly test on Vista virtual directories // on Vista you are not allowed to write executable files on virtual directories like "Program Files" fileTest = File.createTempFile("writtableArea", ".dll", installDir); //$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException e) { //If an exception occured while trying to create the file, it means that it is not writtable return false; } finally { if (fileTest != null) fileTest.delete(); } return true; } /** * Returns a files system path for an area in the user.home region related to the * current product. The given appendage is added to this base location * @param pathAppendage the path segments to add to computed base * @return a file system location in the user.home area related the the current * product and the given appendage */ private String computeDefaultUserAreaLocation(String pathAppendage) { // we store the state in <user.home>/.eclipse/<application-id>_<version> where <user.home> // is unique for each local user, and <application-id> is the one // defined in .eclipseproduct marker file. If .eclipseproduct does not // exist, use "eclipse" as the application-id. URL installURL = getInstallLocation(); if (installURL == null) return null; File installDir = new File(installURL.getFile()); // compute an install dir hash to prevent configuration area collisions with other eclipse installs int hashCode; try { hashCode = installDir.getCanonicalPath().hashCode(); } catch (IOException ioe) { // fall back to absolute path hashCode = installDir.getAbsolutePath().hashCode(); } if (hashCode < 0) hashCode = -(hashCode); String installDirHash = String.valueOf(hashCode); String appName = "." + ECLIPSE; //$NON-NLS-1$ File eclipseProduct = new File(installDir, PRODUCT_SITE_MARKER); if (eclipseProduct.exists()) { Properties props = new Properties(); try { props.load(new FileInputStream(eclipseProduct)); String appId = props.getProperty(PRODUCT_SITE_ID); if (appId == null || appId.trim().length() == 0) appId = ECLIPSE; String appVersion = props.getProperty(PRODUCT_SITE_VERSION); if (appVersion == null || appVersion.trim().length() == 0) appVersion = ""; //$NON-NLS-1$ appName += File.separator + appId + "_" + appVersion + "_" + installDirHash; //$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException e) { // Do nothing if we get an exception. We will default to a standard location // in the user's home dir. // add the hash to help prevent collisions appName += File.separator + installDirHash; } } else { // add the hash to help prevent collisions appName += File.separator + installDirHash; } String userHome = System.getProperty(PROP_USER_HOME); return new File(userHome, appName + "/" + pathAppendage).getAbsolutePath(); //$NON-NLS-1$ } /** * Runs this launcher with the arguments specified in the given string. * * @param argString the arguments string */ public static void main(String argString) { Vector list = new Vector(5); for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();) //$NON-NLS-1$ list.addElement(tokens.nextElement()); main((String[]) list.toArray(new String[list.size()])); } /** * Runs the platform with the given arguments. The arguments must identify * an application to run (e.g., <code>-application com.example.application</code>). * After running the application <code>System.exit(N)</code> is executed. * The value of N is derived from the value returned from running the application. * If the application's return value is an <code>Integer</code>, N is this value. * In all other cases, N = 0. * <p> * Clients wishing to run the platform without a following <code>System.exit</code> * call should use <code>run()</code>. * </p> * * @param args the command line arguments * @see #run(String[]) */ public static void main(String[] args) { int result = 0; try { result = new Main().run(args); } catch (Throwable t) { // This is *really* unlikely to happen - run() takes care of exceptional situations. // In case something weird happens, just dump stack - logging is not available at this point t.printStackTrace(); } finally { if (!Boolean.getBoolean(PROP_NOSHUTDOWN)) // make sure we always terminate the VM System.exit(result); } } /** * Runs the platform with the given arguments. The arguments must identify * an application to run (e.g., <code>-application com.example.application</code>). * Returns the value returned from running the application. * If the application's return value is an <code>Integer</code>, N is this value. * In all other cases, N = 0. * * @param args the command line arguments */ public int run(String[] args) { int result = 0; try { basicRun(args); String exitCode = System.getProperty(PROP_EXITCODE); try { result = exitCode == null ? 0 : Integer.parseInt(exitCode); } catch (NumberFormatException e) { result = 17; } } catch (Throwable e) { // only log the exceptions if they have not been caught by the // EclipseStarter (i.e., if the exitCode is not 13) if (!"13".equals(System.getProperty(PROP_EXITCODE))) { //$NON-NLS-1$ log("Exception launching the Eclipse Platform:"); //$NON-NLS-1$ log(e); String message = "An error has occurred"; //$NON-NLS-1$ if (logFile == null) message += " and could not be logged: \n" + e.getMessage(); //$NON-NLS-1$ else message += ". See the log file\n" + logFile.getAbsolutePath(); //$NON-NLS-1$ System.getProperties().put(PROP_EXITDATA, message); } // Return "unlucky" 13 as the exit code. The executable will recognize // this constant and display a message to the user telling them that // there is information in their log file. result = 13; } finally { // always try putting down the splash screen just in case the application failed to do so takeDownSplash(); if(bridge != null) bridge.uninitialize(); } // Return an int exit code and ensure the system property is set. System.getProperties().put(PROP_EXITCODE, Integer.toString(result)); setExitData(); return result; } private void setExitData() { String data = System.getProperty(PROP_EXITDATA); if (data == null || bridge == null) return; bridge.setExitData(exitData, data); } /** * Processes the command line arguments. The general principle is to NOT * consume the arguments and leave them to be processed by Eclipse proper. * There are a few args which are directed towards main() and a few others * which we need to know about. Very few should actually be consumed here. * * @return the arguments to pass through to the launched application * @param args the command line arguments */ protected String[] processCommandLine(String[] args) { if (args.length == 0) return args; int[] configArgs = new int[args.length]; configArgs[0] = -1; // need to initialize the first element to something that could not be an index. int configArgIndex = 0; for (int i = 0; i < args.length; i++) { boolean found = false; // check for args without parameters (i.e., a flag arg) // check if debug should be enabled for the entire platform if (args[i].equalsIgnoreCase(DEBUG)) { debug = true; // passed thru this arg (i.e., do not set found = true) continue; } // look for and consume the nosplash directive. This supercedes any // -showsplash command that might be present. if (args[i].equalsIgnoreCase(NOSPLASH)) { splashDown = true; found = true; } if (args[i].equalsIgnoreCase(NOEXIT)) { System.getProperties().put(PROP_NOSHUTDOWN, "true"); //$NON-NLS-1$ found = true; } // check if this is initialization pass if (args[i].equalsIgnoreCase(INITIALIZE)) { initialize = true; // passed thru this arg (i.e., do not set found = true) continue; } // check if development mode should be enabled for the entire platform // If this is the last arg or there is a following arg (i.e., arg+1 has a leading -), // simply enable development mode. Otherwise, assume that that the following arg is // actually some additional development time class path entries. This will be processed below. if (args[i].equalsIgnoreCase(DEV) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ inDevelopmentMode = true; // do not mark the arg as found so it will be passed through continue; } // look for the command to use to show the splash screen if (args[i].equalsIgnoreCase(SHOWSPLASH)) { showSplash = true; found = true; //consume optional parameter for showsplash if (i + 1 < args.length && !args[i+1].startsWith("-")) { //$NON-NLS-1$ configArgs[configArgIndex++] = i++; splashLocation = args[i]; } } // done checking for args. Remember where an arg was found if (found) { configArgs[configArgIndex++] = i; continue; } // look for the VM args arg. We have to do that before looking to see // if the next element is a -arg as the thing following -vmargs may in // fact be another -arg. if (args[i].equalsIgnoreCase(VMARGS)) { // consume the -vmargs arg itself args[i] = null; i++; vmargs = new String[args.length - i]; for (int j = 0; i < args.length; i++) { vmargs[j++] = args[i]; args[i] = null; } continue; } // check for args with parameters. If we are at the last argument or if the next one // has a '-' as the first character, then we can't have an arg with a parm so continue. if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ continue; String arg = args[++i]; // look for the development mode and class path entries. if (args[i - 1].equalsIgnoreCase(DEV)) { inDevelopmentMode = true; devClassPathProps = processDevArg(arg); if (devClassPathProps != null) { devClassPath = devClassPathProps.getProperty(OSGI); if (devClassPath == null) devClassPath = devClassPathProps.getProperty("*"); //$NON-NLS-1$ } continue; } // look for the framework to run if (args[i - 1].equalsIgnoreCase(FRAMEWORK)) { framework = arg; found = true; } if (args[i - 1].equalsIgnoreCase(OS)) { os = arg; // passed thru this arg continue; } if (args[i - 1].equalsIgnoreCase(WS)) { ws = arg; continue; } if (args[i - 1].equalsIgnoreCase(ARCH)) { arch = arg; continue; } // look for explicitly set install root // Consume the arg here to ensure that the launcher and Eclipse get the // same value as each other. if (args[i - 1].equalsIgnoreCase(INSTALL)) { System.getProperties().put(PROP_INSTALL_AREA, arg); found = true; } // look for the configuration to use. // Consume the arg here to ensure that the launcher and Eclipse get the // same value as each other. if (args[i - 1].equalsIgnoreCase(CONFIGURATION)) { System.getProperties().put(PROP_CONFIG_AREA, arg); found = true; } if (args[i - 1].equalsIgnoreCase(EXITDATA)) { exitData = arg; found = true; } // look for the name to use by the launcher if (args[i - 1].equalsIgnoreCase(NAME)) { //not doing anything with this right now, but still consume it //name = arg; found = true; } // look for the launcher location if (args[i - 1].equalsIgnoreCase(LAUNCHER)) { //not doing anything with this right now, but still consume it //launcher = arg; found = true; } if (args[i - 1].equalsIgnoreCase(LIBRARY)) { library = arg; found = true; } // look for the command to use to end the splash screen if (args[i - 1].equalsIgnoreCase(ENDSPLASH)) { endSplash = arg; found = true; } // look for the VM location arg if (args[i - 1].equalsIgnoreCase(VM)) { vm = arg; found = true; } //look for the nl setting if (args[i - 1].equalsIgnoreCase(NL)) { System.getProperties().put(PROP_NL, arg); found = true; } // done checking for args. Remember where an arg was found if (found) { configArgs[configArgIndex++] = i - 1; configArgs[configArgIndex++] = i; } } // remove all the arguments consumed by this argument parsing String[] passThruArgs = new String[args.length - configArgIndex - (vmargs == null ? 0 : vmargs.length + 1)]; configArgIndex = 0; int j = 0; for (int i = 0; i < args.length; i++) { if (i == configArgs[configArgIndex]) configArgIndex++; else if (args[i] != null) passThruArgs[j++] = args[i]; } return passThruArgs; } private Properties processDevArg(String arg) { if (arg == null) return null; try { URL location = new URL(arg); return load(location, null); } catch (MalformedURLException e) { // the arg was not a URL so use it as is. Properties result = new Properties(); result.put("*", arg); //$NON-NLS-1$ return result; } catch (IOException e) { // TODO consider logging here return null; } } private URL getConfigurationLocation() { if (configurationLocation != null) return configurationLocation; configurationLocation = buildLocation(PROP_CONFIG_AREA, null, ""); //$NON-NLS-1$ if (configurationLocation == null) { configurationLocation = buildLocation(PROP_CONFIG_AREA_DEFAULT, null, ""); //$NON-NLS-1$ if (configurationLocation == null) configurationLocation = buildURL(computeDefaultConfigurationLocation(), true); } if (configurationLocation != null) System.getProperties().put(PROP_CONFIG_AREA, configurationLocation.toExternalForm()); if (debug) System.out.println("Configuration location:\n " + configurationLocation); //$NON-NLS-1$ return configurationLocation; } private void processConfiguration() { // if the configuration area is not already defined, discover the config area by // trying to find a base config area. This is either defined in a system property or // is computed relative to the install location. // Note that the config info read here is only used to determine a value // for the user configuration area URL baseConfigurationLocation = null; Properties baseConfiguration = null; if (System.getProperty(PROP_CONFIG_AREA) == null) { String baseLocation = System.getProperty(PROP_BASE_CONFIG_AREA); if (baseLocation != null) // here the base config cannot have any symbolic (e..g, @xxx) entries. It must just // point to the config file. baseConfigurationLocation = buildURL(baseLocation, true); if (baseConfigurationLocation == null) try { // here we access the install location but this is very early. This case will only happen if // the config area is not set and the base config area is not set (or is bogus). // In this case we compute based on the install location. baseConfigurationLocation = new URL(getInstallLocation(), CONFIG_DIR); } catch (MalformedURLException e) { // leave baseConfigurationLocation null } baseConfiguration = loadConfiguration(baseConfigurationLocation); if (baseConfiguration != null) { // if the base sets the install area then use that value if the property. We know the // property is not already set. String location = baseConfiguration.getProperty(PROP_CONFIG_AREA); if (location != null) System.getProperties().put(PROP_CONFIG_AREA, location); // if the base sets the install area then use that value if the property is not already set. // This helps in selfhosting cases where you cannot easily compute the install location // from the code base. location = baseConfiguration.getProperty(PROP_INSTALL_AREA); if (location != null && System.getProperty(PROP_INSTALL_AREA) == null) System.getProperties().put(PROP_INSTALL_AREA, location); } } // Now we know where the base configuration is supposed to be. Go ahead and load // it and merge into the System properties. Then, if cascaded, read the parent configuration // Note that the parent may or may not be the same parent as we read above since the // base can define its parent. The first parent we read was either defined by the user // on the command line or was the one in the install dir. // if the config or parent we are about to read is the same as the base config we read above, // just reuse the base Properties configuration = baseConfiguration; if (configuration == null || !getConfigurationLocation().equals(baseConfigurationLocation)) configuration = loadConfiguration(getConfigurationLocation()); mergeProperties(System.getProperties(), configuration); if ("false".equalsIgnoreCase(System.getProperty(PROP_CONFIG_CASCADED))) //$NON-NLS-1$ // if we are not cascaded then remove the parent property even if it was set. System.getProperties().remove(PROP_SHARED_CONFIG_AREA); else { ensureAbsolute(PROP_SHARED_CONFIG_AREA); URL sharedConfigURL = buildLocation(PROP_SHARED_CONFIG_AREA, null, ""); //$NON-NLS-1$ if (sharedConfigURL == null) try { // there is no shared config value so compute one sharedConfigURL = new URL(getInstallLocation(), CONFIG_DIR); } catch (MalformedURLException e) { // leave sharedConfigurationLocation null } // if the parent location is different from the config location, read it too. if (sharedConfigURL != null) { if (sharedConfigURL.equals(getConfigurationLocation())) // remove the property to show that we do not have a parent. System.getProperties().remove(PROP_SHARED_CONFIG_AREA); else { // if the parent we are about to read is the same as the base config we read above, // just reuse the base configuration = baseConfiguration; if (!sharedConfigURL.equals(baseConfigurationLocation)) configuration = loadConfiguration(sharedConfigURL); mergeProperties(System.getProperties(), configuration); System.getProperties().put(PROP_SHARED_CONFIG_AREA, sharedConfigURL.toExternalForm()); if (debug) System.out.println("Shared configuration location:\n " + sharedConfigURL.toExternalForm()); //$NON-NLS-1$ } } } // setup the path to the framework String urlString = System.getProperty(PROP_FRAMEWORK, null); if (urlString != null) { URL url = buildURL(urlString, true); System.getProperties().put(PROP_FRAMEWORK, url.toExternalForm()); bootLocation = resolve(urlString); } } /** * Ensures the value for a system property is an absolute URL. Relative URLs are translated to * absolute URLs by taking the install URL as reference. * * @param locationProperty the key for a system property containing a URL */ private void ensureAbsolute(String locationProperty) { String propertyValue = System.getProperty(locationProperty); if (propertyValue == null) // property not defined return; URL locationURL = null; try { locationURL = new URL(propertyValue); } catch (MalformedURLException e) { // property is not a valid URL return; } String locationPath = locationURL.getPath(); if (locationPath.startsWith("/")) //$NON-NLS-1$ // property value is absolute return; URL installURL = getInstallLocation(); if (!locationURL.getProtocol().equals(installURL.getProtocol())) // not same protocol return; try { URL absoluteURL = new URL(installURL, locationPath); System.getProperties().put(locationProperty, absoluteURL.toExternalForm()); } catch (MalformedURLException e) { // should not happen - the relative URL is known to be valid } } /** * Returns url of the location this class was loaded from */ private URL getInstallLocation() { if (installLocation != null) return installLocation; // value is not set so compute the default and set the value String installArea = System.getProperty(PROP_INSTALL_AREA); if (installArea != null) { installLocation = buildURL(installArea, true); if (installLocation == null) throw new IllegalStateException("Install location is invalid: " + installArea); //$NON-NLS-1$ System.getProperties().put(PROP_INSTALL_AREA, installLocation.toExternalForm()); if (debug) System.out.println("Install location:\n " + installLocation); //$NON-NLS-1$ return installLocation; } ProtectionDomain domain = Main.class.getProtectionDomain(); CodeSource source = null; URL result = null; if (domain != null) source = domain.getCodeSource(); if (source == null || domain == null) { if (debug) System.out.println("CodeSource location is null. Defaulting the install location to file:startup.jar"); //$NON-NLS-1$ try { result = new URL("file:startup.jar"); //$NON-NLS-1$ } catch (MalformedURLException e2) { //Ignore } } if (source != null) result = source.getLocation(); String path = decode(result.getFile()); // normalize to not have leading / so we can check the form File file = new File(path); path = file.toString().replace('\\', '/'); // TODO need a better test for windows // If on Windows then canonicalize the drive letter to be lowercase. // remember that there may be UNC paths if (File.separatorChar == '\\') if (Character.isUpperCase(path.charAt(0))) { char[] chars = path.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); path = new String(chars); } if (path.toLowerCase().endsWith(".jar")) //$NON-NLS-1$ path = path.substring(0, path.lastIndexOf("/") + 1); //$NON-NLS-1$ if (path.toLowerCase().endsWith("/plugins/")) //$NON-NLS-1$ path = path.substring(0, path.length() - "/plugins/".length()); //$NON-NLS-1$ try { try { // create a file URL (via File) to normalize the form (e.g., put // the leading / on if necessary) path = new File(path).toURL().getFile(); } catch (MalformedURLException e1) { // will never happen. The path is straight from a URL. } installLocation = new URL(result.getProtocol(), result.getHost(), result.getPort(), path); System.getProperties().put(PROP_INSTALL_AREA, installLocation.toExternalForm()); } catch (MalformedURLException e) { // TODO Very unlikely case. log here. } if (debug) System.out.println("Install location:\n " + installLocation); //$NON-NLS-1$ return installLocation; } /* * Load the given configuration file */ private Properties loadConfiguration(URL url) { Properties result = null; try { url = new URL(url, CONFIG_FILE); } catch (MalformedURLException e) { return null; } try { if (debug) System.out.print("Configuration file:\n " + url.toString()); //$NON-NLS-1$ result = loadProperties(url); if (debug) System.out.println(" loaded"); //$NON-NLS-1$ } catch (IOException e) { if (debug) System.out.println(" not found or not read"); //$NON-NLS-1$ } return result; } private Properties loadProperties(URL url) throws IOException { // try to load saved configuration file (watch for failed prior save()) if (url == null) return null; Properties result = null; IOException originalException = null; try { result = load(url, null); // try to load config file } catch (IOException e1) { originalException = e1; try { result = load(url, CONFIG_FILE_TEMP_SUFFIX); // check for failures on save } catch (IOException e2) { try { result = load(url, CONFIG_FILE_BAK_SUFFIX); // check for failures on save } catch (IOException e3) { throw originalException; // we tried, but no config here ... } } } return result; } /* * Load the configuration */ private Properties load(URL url, String suffix) throws IOException { // figure out what we will be loading if (suffix != null && !suffix.equals("")) //$NON-NLS-1$ url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + suffix); // try to load saved configuration file Properties props = new Properties(); InputStream is = null; try { is = url.openStream(); props.load(is); } finally { if (is != null) try { is.close(); } catch (IOException e) { //ignore failure to close } } return props; } /* * Handle splash screen. * We support 2 startup scenarios: * * (1) the executable launcher put up the splash screen. In that * scenario we are invoked with -endsplash command which is * fully formed to take down the splash screen * * (2) the executable launcher did not put up the splash screen, * but invokes Eclipse with partially formed -showsplash command. * In this scenario we determine which splash to display (based on * feature information) and then call -showsplash command. * * In both scenarios we pass a handler (Runnable) to the platform. * The handler is called as a result of the launched application calling * Platform.endSplash(). In the first scenario this results in the * -endsplash command being executed. In the second scenario this * results in the process created as a result of the -showsplash command * being destroyed. * * @param defaultPath search path for the boot plugin */ private void handleSplash(URL[] defaultPath) { // run without splash if we are initializing or nosplash // was specified (splashdown = true) - if (initialize || splashDown) { + if (initialize || splashDown || bridge == null) { showSplash = false; endSplash = null; return; } if (showSplash || endSplash != null) { // Register the endSplashHandler to be run at VM shutdown. This hook will be // removed once the splash screen has been taken down. try { Runtime.getRuntime().addShutdownHook(splashHandler); } catch(Throwable ex) { // Best effort to register the handler } } // if -endsplash is specified, use it and ignore any -showsplash command if (endSplash != null) { showSplash = false; return; } // check if we are running without a splash screen if (!showSplash) return; // determine the splash location splashLocation = getSplashLocation(defaultPath); if (debug) System.out.println("Splash location:\n " + splashLocation); //$NON-NLS-1$ if (splashLocation == null) return; bridge.showSplash(splashLocation); long handle = bridge.getSplashHandle(); if(handle != 0) { System.setProperty("org.eclipse.equinox.launcher.splash.handle", String.valueOf(handle)); //$NON-NLS-1$ System.setProperty("org.eclipse.equinox.launcher.splash.location", splashLocation); //$NON-NLS-1$ bridge.updateSplash(); } } /* * Take down the splash screen. */ protected void takeDownSplash() { if (splashDown || bridge == null) // splash is already down return; splashDown = bridge.takeDownSplash(); try { Runtime.getRuntime().removeShutdownHook(splashHandler); } catch (Throwable e) { // OK to ignore this, happens when the VM is already shutting down } } /* * Return path of the splash image to use. First search the defined splash path. * If that does not work, look for a default splash. Currently the splash must be in the file system * so the return value here is the file system path. */ private String getSplashLocation(URL[] bootPath) { //check the path passed in from -showsplash first. The old launcher passed a timeout value //as the argument, so only use it if it isn't a number and the file exists. if(splashLocation != null && !Character.isDigit(splashLocation.charAt(0)) && new File(splashLocation).exists()) { System.getProperties().put(PROP_SPLASHLOCATION, splashLocation); return splashLocation; } String result = System.getProperty(PROP_SPLASHLOCATION); if (result != null) return result; String splashPath = System.getProperty(PROP_SPLASHPATH); if (splashPath != null) { String[] entries = getArrayFromList(splashPath); ArrayList path = new ArrayList(entries.length); for (int i = 0; i < entries.length; i++) { String entry = resolve(entries[i]); if (entry == null || entry.startsWith(FILE_SCHEME)) { File entryFile = new File(entry.substring(5).replace('/', File.separatorChar)); entry = searchFor(entryFile.getName(), entryFile.getParent()); if (entry != null) path.add(entry); } else log("Invalid splash path entry: " + entries[i]); //$NON-NLS-1$ } // see if we can get a splash given the splash path result = searchForSplash((String[]) path.toArray(new String[path.size()])); if (result != null) { System.getProperties().put(PROP_SPLASHLOCATION, result); return result; } } // can't find it on the splashPath so look for a default splash String temp = bootPath[0].getFile(); // take the first path element temp = temp.replace('/', File.separatorChar); int ix = temp.lastIndexOf("plugins" + File.separator); //$NON-NLS-1$ if (ix != -1) { int pix = temp.indexOf(File.separator, ix + 8); if (pix != -1) { temp = temp.substring(0, pix); result = searchForSplash(new String[] {temp}); if (result != null) System.getProperties().put(PROP_SPLASHLOCATION, result); } } return result; } /* * Do a locale-sensitive lookup of splash image */ private String searchForSplash(String[] searchPath) { if (searchPath == null) return null; // Get the splash screen for the specified locale String locale = (String) System.getProperties().get(PROP_NL); if (locale == null) locale = Locale.getDefault().toString(); String[] nlVariants = buildNLVariants(locale); for (int i=0; i<nlVariants.length; i++) { for (int j=0; j<searchPath.length; j++) { // do we have a JAR? if (isJAR(searchPath[j])) { String result = extractSplashFromJAR(searchPath[j], nlVariants[i]); if (result != null) return result; } else { // we have a file or a directory String path = searchPath[j]; if (!path.endsWith(File.separator)) path += File.separator; path += nlVariants[i]; File result = new File(path); if (result.exists()) return result.getAbsolutePath(); // return the first match found [20063] } } } // sorry, could not find splash image return null; } /** * Transfers all available bytes from the given input stream to the given output stream. * Regardless of failure, this method closes both streams. */ private static void transferStreams(InputStream source, OutputStream destination) { byte[] buffer = new byte[8096]; try { while (true) { int bytesRead = -1; try { bytesRead = source.read(buffer); } catch (IOException e) { return; } if (bytesRead == -1) break; try { destination.write(buffer, 0, bytesRead); } catch (IOException e) { return; } } } finally { try { source.close(); } catch (IOException e) { // ignore } finally { //close destination in finally in case source.close fails try { destination.close(); } catch (IOException e) { // ignore } } } } /* * Look for the specified spash file in the given JAR and extract it to the config * area for caching purposes. */ private String extractSplashFromJAR(String jarPath, String splashPath) { String configLocation = System.getProperty(PROP_CONFIG_AREA); if (configLocation == null) { log("Configuration area not set yet. Unable to extract splash from JAR'd plug-in: " + jarPath); //$NON-NLS-1$ return null; } URL configURL = buildURL(configLocation, false); if (configURL == null) return null; // cache the splash in the OSGi sub-dir in the config area File splash = new File(configURL.getPath(), OSGI); //include the name of the jar in the cache location File jarFile = new File(jarPath); String cache = jarFile.getName(); if(cache.endsWith(".jar")) //$NON-NLS-1$ cache = cache.substring(0, cache.length() - 4); splash = new File(splash, cache); splash = new File(splash, splashPath); // if we have already extracted this file before, then return if (splash.exists()) { // if we are running with -clean then delete the cached splash file boolean clean = false; for (int i=0; i<commands.length; i++) { if (CLEAN.equalsIgnoreCase(commands[i])) { clean = true; splash.delete(); break; } } if (!clean) return splash.getAbsolutePath(); } ZipFile file; try { file = new ZipFile(jarPath); } catch (IOException e) { log("Exception looking for splash in JAR file: " + jarPath); //$NON-NLS-1$ log(e); return null; } ZipEntry entry = file.getEntry(splashPath.replace(File.separatorChar, '/')); if (entry == null) return null; InputStream input = null; try { input = file.getInputStream(entry); } catch (IOException e) { log("Exception opening splash: " + entry.getName() + " in JAR file: " + jarPath); //$NON-NLS-1$ //$NON-NLS-2$ log(e); return null; } new File(splash.getParent()).mkdirs(); OutputStream output; try { output = new BufferedOutputStream(new FileOutputStream(splash)); } catch (FileNotFoundException e) { try { input.close(); } catch (IOException e1) { // ignore } return null; } transferStreams(input, output); return splash.exists() ? splash.getAbsolutePath() : null; } /* * Return a boolean value indicating whether or not the given * path represents a JAR file. */ private boolean isJAR(String path) { if (path.endsWith(File.separator)) return false; int index = path.lastIndexOf('.'); if (index == -1) return false; index++; // handle the case where we have a '.' at the end if (index >= path.length()) return false; return "JAR".equalsIgnoreCase(path.substring(index)); //$NON-NLS-1$ } /* * Build an array of path suffixes based on the given NL which is suitable * for splash path searching. The returned array contains paths in order * from most specific to most generic. So, in the FR_fr locale, it will return * "nl/fr/FR/splash.bmp", then "nl/fr/splash.bmp", and finally "splash.bmp". * (we always search the root) */ private static String[] buildNLVariants(String locale) { //build list of suffixes for loading resource bundles String nl = locale; ArrayList result = new ArrayList(4); int lastSeparator; while (true) { result.add("nl" + File.separatorChar + nl.replace('_', File.separatorChar) + File.separatorChar + SPLASH_IMAGE); //$NON-NLS-1$ lastSeparator = nl.lastIndexOf('_'); if (lastSeparator == -1) break; nl = nl.substring(0, lastSeparator); } //add the empty suffix last (most general) result.add(SPLASH_IMAGE); return (String[]) result.toArray(new String[result.size()]); } /* * resolve platform:/base/ URLs */ private String resolve(String urlString) { // handle the case where people mistakenly spec a refererence: url. if (urlString.startsWith(REFERENCE_SCHEME)) { urlString = urlString.substring(10); System.getProperties().put(PROP_FRAMEWORK, urlString); } if (urlString.startsWith(PLATFORM_URL)) { String path = urlString.substring(PLATFORM_URL.length()); return getInstallLocation() + path; } return urlString; } /* * Entry point for logging. */ protected synchronized void log(Object obj) { if (obj == null) return; try { openLogFile(); try { if (newSession) { log.write(SESSION); log.write(' '); String timestamp = new Date().toString(); log.write(timestamp); log.write(' '); for (int i = SESSION.length() + timestamp.length(); i < 78; i++) log.write('-'); log.newLine(); newSession = false; } write(obj); } finally { if (logFile == null) { if (log != null) log.flush(); } else closeLogFile(); } } catch (Exception e) { System.err.println("An exception occurred while writing to the platform log:"); //$NON-NLS-1$ e.printStackTrace(System.err); System.err.println("Logging to the console instead."); //$NON-NLS-1$ //we failed to write, so dump log entry to console instead try { log = logForStream(System.err); write(obj); log.flush(); } catch (Exception e2) { System.err.println("An exception occurred while logging to the console:"); //$NON-NLS-1$ e2.printStackTrace(System.err); } } finally { log = null; } } /* * This should only be called from #log() */ private void write(Object obj) throws IOException { if (obj == null) return; if (obj instanceof Throwable) { log.write(STACK); log.newLine(); ((Throwable) obj).printStackTrace(new PrintWriter(log)); } else { log.write(ENTRY); log.write(' '); log.write(PLUGIN_ID); log.write(' '); log.write(String.valueOf(ERROR)); log.write(' '); log.write(String.valueOf(0)); log.write(' '); log.write(getDate(new Date())); log.newLine(); log.write(MESSAGE); log.write(' '); log.write(String.valueOf(obj)); } log.newLine(); } protected String getDate(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); StringBuffer sb = new StringBuffer(); appendPaddedInt(c.get(Calendar.YEAR), 4, sb).append('-'); appendPaddedInt(c.get(Calendar.MONTH) + 1, 2, sb).append('-'); appendPaddedInt(c.get(Calendar.DAY_OF_MONTH), 2, sb).append(' '); appendPaddedInt(c.get(Calendar.HOUR_OF_DAY), 2, sb).append(':'); appendPaddedInt(c.get(Calendar.MINUTE), 2, sb).append(':'); appendPaddedInt(c.get(Calendar.SECOND), 2, sb).append('.'); appendPaddedInt(c.get(Calendar.MILLISECOND), 3, sb); return sb.toString(); } private StringBuffer appendPaddedInt(int value, int pad, StringBuffer buffer) { pad = pad - 1; if (pad == 0) return buffer.append(Integer.toString(value)); int padding = (int) Math.pow(10, pad); if (value >= padding) return buffer.append(Integer.toString(value)); while (padding > value && padding > 1) { buffer.append('0'); padding = padding / 10; } buffer.append(value); return buffer; } private void computeLogFileLocation() { String logFileProp = System.getProperty(PROP_LOGFILE); if (logFileProp != null) { if (logFile == null || !logFileProp.equals(logFile.getAbsolutePath())) { logFile = new File(logFileProp); new File(logFile.getParent()).mkdirs(); } return; } // compute the base location and then append the name of the log file URL base = buildURL(System.getProperty(PROP_CONFIG_AREA), false); if (base == null) return; logFile = new File(base.getPath(), Long.toString(System.currentTimeMillis()) + ".log"); //$NON-NLS-1$ new File(logFile.getParent()).mkdirs(); System.getProperties().put(PROP_LOGFILE, logFile.getAbsolutePath()); } /** * Converts an ASCII character representing a hexadecimal * value into its integer equivalent. */ private int hexToByte(byte b) { switch (b) { case '0' : return 0; case '1' : return 1; case '2' : return 2; case '3' : return 3; case '4' : return 4; case '5' : return 5; case '6' : return 6; case '7' : return 7; case '8' : return 8; case '9' : return 9; case 'A' : case 'a' : return 10; case 'B' : case 'b' : return 11; case 'C' : case 'c' : return 12; case 'D' : case 'd' : return 13; case 'E' : case 'e' : return 14; case 'F' : case 'f' : return 15; default : throw new IllegalArgumentException("Switch error decoding URL"); //$NON-NLS-1$ } } private void openLogFile() throws IOException { computeLogFileLocation(); try { log = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile.getAbsolutePath(), true), "UTF-8")); //$NON-NLS-1$ } catch (IOException e) { logFile = null; throw e; } } private BufferedWriter logForStream(OutputStream output) { try { return new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { return new BufferedWriter(new OutputStreamWriter(output)); } } private void closeLogFile() throws IOException { try { if (log != null) { log.flush(); log.close(); } } finally { log = null; } } private void mergeProperties(Properties destination, Properties source) { if (destination == null || source == null) return; for (Enumeration e = source.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (key.equals(PROP_CLASSPATH)) { String destinationClasspath = destination.getProperty(PROP_CLASSPATH); String sourceClasspath = source.getProperty(PROP_CLASSPATH); if (destinationClasspath == null) destinationClasspath = sourceClasspath; else destinationClasspath = destinationClasspath + sourceClasspath; destination.put(PROP_CLASSPATH, destinationClasspath); continue; } String value = source.getProperty(key); if (destination.getProperty(key) == null) destination.put(key, value); } } private void setupVMProperties() { if (vm != null) System.getProperties().put(PROP_VM, vm); setMultiValueProperty(PROP_VMARGS, vmargs); setMultiValueProperty(PROP_COMMANDS, commands); } private void setMultiValueProperty(String property, String[] value) { if (value != null) { StringBuffer result = new StringBuffer(300); for (int i = 0; i < value.length; i++) { if (value[i] != null) { result.append(value[i]); result.append('\n'); } } System.getProperties().put(property, result.toString()); } } /* * NOTE: It is ok here for EclipsePolicy to use 1.4 methods because the methods * that it calls them from don't exist in Foundation so they will never be called. A more * detailed explanation from Tom: * * They will never get called because in a pre 1.4 VM the methods * getPermissions(CodeSource) and implies(ProtectionDomain, Permission) are * undefined on the Policy class which is what EclipsePolicy extends. EclipsePolicy * implements these two methods so it can proxy them to the parent Policy. * But since these methods are not actually defined on Policy in a pre-1.4 VM * nobody will actually call them (unless they casted the policy to EclipsePolicy and * called our methods) */ private class EclipsePolicy extends Policy { // The policy that this EclipsePolicy is replacing private Policy policy; // The set of URLs to give AllPermissions to; this is the set of bootURLs private URL[] urls; // The AllPermissions collection private PermissionCollection allPermissions; // The AllPermission permission Permission allPermission = new AllPermission(); EclipsePolicy(Policy policy, URL[] urls) { this.policy = policy; this.urls = urls; allPermissions = new PermissionCollection() { private static final long serialVersionUID = 3258131349494708277L; // A simple PermissionCollection that only has AllPermission public void add(Permission permission) { //no adding to this policy } public boolean implies(Permission permission) { return true; } public Enumeration elements() { return new Enumeration() { int cur = 0; public boolean hasMoreElements() { return cur < 1; } public Object nextElement() { if (cur == 0) { cur = 1; return allPermission; } throw new NoSuchElementException(); } }; } }; } public PermissionCollection getPermissions(CodeSource codesource) { if (contains(codesource.getLocation())) return allPermissions; return policy == null ? allPermissions : policy.getPermissions(codesource); } public PermissionCollection getPermissions(ProtectionDomain domain) { if (contains(domain.getCodeSource().getLocation())) return allPermissions; return policy == null ? allPermissions : policy.getPermissions(domain); } public boolean implies(ProtectionDomain domain, Permission permission) { if (contains(domain.getCodeSource().getLocation())) return true; return policy == null ? true : policy.implies(domain, permission); } public void refresh() { if (policy != null) policy.refresh(); } private boolean contains(URL url) { // Check to see if this URL is in our set of URLs to give AllPermissions to. for (int i = 0; i < urls.length; i++) { // We do simple equals test here because we assume the URLs will be the same objects. if (urls[i] == url) return true; } return false; } } private class StartupClassLoader extends URLClassLoader { public StartupClassLoader(URL[] urls) { super(urls); } public StartupClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } public StartupClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { super(urls, parent, factory); } protected String findLibrary(String name) { if (extensionPaths == null) return super.findLibrary(name); String libName = System.mapLibraryName(name); for (int i = 0; i < extensionPaths.length; i++) { File libFile = new File(extensionPaths[i], libName); if (libFile.isFile()) return libFile.getAbsolutePath(); } return super.findLibrary(name); } } }
false
false
null
null
diff --git a/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkerButton.java b/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkerButton.java index a8f2584f..66795f61 100644 --- a/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkerButton.java +++ b/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkerButton.java @@ -1,66 +1,68 @@ /** * */ package org.cotrix.web.manage.client.codelist.codes.marker; import static org.cotrix.web.manage.client.codelist.codes.marker.MarkersResource.*; import com.google.gwt.dom.client.Style; +import com.google.gwt.dom.client.Style.Float; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FocusPanel; /** * @author "Federico De Faveri [email protected]" * */ public class MarkerButton extends Composite implements HasValueChangeHandlers<Boolean> { private FocusPanel focusPanel; private boolean down; public MarkerButton(MarkerType markerType) { focusPanel = new FocusPanel(); focusPanel.setStyleName(markerType.getHighlightStyleName()); focusPanel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onPanelClick(); } }); initWidget(focusPanel); down = false; getElement().getStyle().setProperty("borderRadius", "2px"); + getElement().getStyle().setFloat(Float.LEFT); setTitle(markerType.getName()); style(); } private void onPanelClick() { down = !down; style(); ValueChangeEvent.fire(this, down); } private void style() { Style elementStyle = getElement().getStyle(); elementStyle.setProperty("border", down?"2px solid "+style.selectedButtonColor():"none"); elementStyle.setWidth(down?12:16, Unit.PX); elementStyle.setHeight(down?12:16, Unit.PX); } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Boolean> handler) { return addHandler(handler, ValueChangeEvent.getType()); } } diff --git a/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkersToolbar.java b/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkersToolbar.java index 29803e33..285d0e35 100644 --- a/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkersToolbar.java +++ b/cotrix/cotrix-web-manage/src/main/java/org/cotrix/web/manage/client/codelist/codes/marker/MarkersToolbar.java @@ -1,58 +1,57 @@ /** * */ package org.cotrix.web.manage.client.codelist.codes.marker; import org.cotrix.web.manage.client.codelist.codes.event.MarkerHighlightEvent; import org.cotrix.web.manage.client.codelist.codes.event.MarkerHighlightEvent.Action; import org.cotrix.web.manage.client.di.CodelistBus; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.Composite; -import com.google.gwt.user.client.ui.HorizontalPanel; +import com.google.gwt.user.client.ui.FlowPanel; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import static org.cotrix.web.manage.client.codelist.codes.marker.MarkersResource.*; /** * @author "Federico De Faveri [email protected]" * */ public class MarkersToolbar extends Composite { @Inject @CodelistBus private EventBus bus; - private HorizontalPanel toolbar; + private FlowPanel toolbar; public MarkersToolbar() { - toolbar = new HorizontalPanel(); - toolbar.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); + toolbar = new FlowPanel(); initButtons(); initWidget(toolbar); } private void initButtons() { for (MarkerType marker:MarkerType.values()) addButton(marker); } private void addButton(final MarkerType marker) { MarkerButton button = new MarkerButton(marker); button.addStyleName(style.toolbarButton()); button.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { fireEvent(marker, event.getValue()); } }); toolbar.add(button); } private void fireEvent(MarkerType type, boolean buttonDown) { bus.fireEvent(new MarkerHighlightEvent(type, buttonDown?Action.ADD:Action.REMOVE)); } }
false
false
null
null
diff --git a/src/projetcodagecrypto/MoveToFront.java b/src/projetcodagecrypto/MoveToFront.java index 3df159e..36cfba0 100644 --- a/src/projetcodagecrypto/MoveToFront.java +++ b/src/projetcodagecrypto/MoveToFront.java @@ -1,71 +1,71 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projetcodagecrypto; import java.util.ArrayList; /** * * @author Benjamin */ public class MoveToFront { private int position; private Ascii ascii; private ArrayList<Integer> tableau; public MoveToFront(int pos, Ascii as) { ascii = as; initTableau(); position = pos; } public void initTableau() { tableau = new ArrayList<>(); for(int i=0 ; i<256 ; i++) tableau.add(i); } public ArrayList<Integer> compressionMTF(ArrayList<Integer> mot) { ArrayList<Integer> code = new ArrayList<Integer>(); - for(int lettre : mot) + for(Integer lettre : mot) { code.add(tableau.indexOf(lettre)); //si c'est la première lettre du tableau pas besoin de bouger sinon oui if(lettre != tableau.get(0)) { - tableau.remove(tableau.get(lettre)); + tableau.remove(lettre); tableau.add(0, lettre); } } /*System.out.println("Tableau : " + tableau); System.out.println("Code obtenu avec MVT :" + code); */ return code; } public ArrayList<Integer> decompressionMTF(ArrayList<Integer> code) { ArrayList<Integer> decode = new ArrayList<Integer>(); initTableau(); for(int chiffre : code) { Integer lettre = tableau.get(chiffre); decode.add(tableau.get(chiffre)); //si c'est la première lettre du tableau pas besoin de bouger sinon oui if(chiffre != 0) { tableau.remove(lettre); tableau.add(0, lettre); } } return decode; } }
false
false
null
null
diff --git a/src/cytoscape/CytoscapeInit.java b/src/cytoscape/CytoscapeInit.java index 77b19745a..60d3851b3 100644 --- a/src/cytoscape/CytoscapeInit.java +++ b/src/cytoscape/CytoscapeInit.java @@ -1,1053 +1,1062 @@ /* File: CytoscapeInit.java Copyright (c) 2006, The Cytoscape Consortium (www.cytoscape.org) The Cytoscape Consortium is: - Institute for Systems Biology - University of California San Diego - Memorial Sloan-Kettering Cancer Center - Institut Pasteur - Agilent Technologies This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. 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. */ package cytoscape; import cytoscape.data.readers.CytoscapeSessionReader; import cytoscape.data.readers.TextHttpReader; import cytoscape.init.CyInitParams; import cytoscape.plugin.CytoscapePlugin; import cytoscape.plugin.PluginManager; import cytoscape.util.FileUtil; import cytoscape.util.shadegrown.WindowUtilities; import cytoscape.view.CytoscapeDesktop; import java.awt.Cursor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.JarFile; import java.util.jar.Manifest; import javax.swing.ImageIcon; /** * <p> * Cytoscape Init is responsible for starting Cytoscape in a way that makes * sense. * </p> * <p> * The comments below are more hopeful than accurate. We currently do not * support a "headless" mode (meaning there is no GUI). We do, however, hope to * support this in the future. * </p> * * <p> * The two main modes of running Cytoscape are either in "headless" mode or in * "script" mode. This class will use the command-line options to figure out * which mode is desired, and run things accordingly. * </p> * * The order for doing things will be the following:<br> * <ol> * <li>deterimine script mode, or headless mode</li> * <li>get options from properties files</li> * <li>get options from command line ( these overwrite properties )</li> * <li>Load all Networks</li> * <li>Load all data</li> * <li>Load all Plugins</li> * <li>Initialize all plugins, in order if specified.</li> * <li>Start Desktop/Print Output exit.</li> * </ol> * * @since Cytoscape 1.0 * @author Cytoscape Core Team */ public class CytoscapeInit { private static Properties properties; private static Properties visualProperties; private static Set pluginURLs; private static Set loadedPlugins; private static Set resourcePlugins; static { System.out.println("CytoscapeInit static initialization"); pluginURLs = new HashSet(); resourcePlugins = new HashSet(); loadedPlugins = new HashSet(); initProperties(); } private static CyInitParams initParams; private static URLClassLoader classLoader; private static PluginManager pluginMgr; // Most-Recently-Used directories and files private static File mrud; private static File mruf; // Configuration variables private static boolean useView = true; private static boolean suppressView = false; private static int secondaryViewThreshold; // View Only Variables private static String vizmapPropertiesLocation; /** * Creates a new CytoscapeInit object. */ public CytoscapeInit() { } /** * Cytoscape Init must be initialized using the command line arguments. * * @param args * the arguments from the command line * @return false, if we fail to initialize for some reason */ public boolean init(CyInitParams params) { long begintime = System.currentTimeMillis(); try { initParams = params; // setup properties initProperties(); properties.putAll(initParams.getProps()); visualProperties.putAll(initParams.getVizProps()); // Build the OntologyServer. Cytoscape.buildOntologyServer(); // see if we are in headless mode // show splash screen, if appropriate System.out.println("init mode: " + initParams.getMode()); if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { final ImageIcon image = new ImageIcon(this.getClass() .getResource("/cytoscape/images/CytoscapeSplashScreen.png")); WindowUtilities.showSplash(image, 8000); // creates the desktop Cytoscape.getDesktop(); // set the wait cursor Cytoscape.getDesktop().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); setUpAttributesChangedListener(); } loadPlugins(); System.out.println("loading session..."); if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) loadSessionFile(); System.out.println("loading networks..."); loadNetworks(); System.out.println("loading attributes..."); loadAttributes(); System.out.println("loading expression files..."); loadExpressionFiles(); } finally { // Always restore the cursor and hide the splash, even there is // exception if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { WindowUtilities.hideSplash(); Cytoscape.getDesktop().setCursor(Cursor.getDefaultCursor()); // to clean up anything that the plugins have messed up Cytoscape.getDesktop().repaint(); } } long endtime = System.currentTimeMillis() - begintime; System.out.println(""); System.out.println("Cytoscape initialized successfully in: " + endtime + " ms"); Cytoscape.firePropertyChange(Cytoscape.CYTOSCAPE_INITIALIZED, null, null); return true; } /** * Returns the CyInitParams object used to initialize Cytoscape. */ public static CyInitParams getCyInitParams() { return initParams; } /** * Returns the properties used by Cytoscape, the result of cytoscape.props * and command line options. */ public static Properties getProperties() { return properties; } /** * @deprecated Use getProperties().setProperty( ) instead. Since this method * never made it into a release, it will be removed Summer 2006. */ public static void setProperty(String key, String value) { properties.setProperty(key, value); } /** * @deprecated Use getProperties().getProperty( ) instead. Since this method * never made it into a release, it will be removed Summer 2006. */ public static String getProperty(String key) { return properties.getProperty(key); } /** * @return The PluginManager object responsible for tracking/installing/deleting plugins */ public static PluginManager getPluginManager() { return pluginMgr; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static URLClassLoader getClassLoader() { return classLoader; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Set getPluginURLs() { return pluginURLs; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Set getResourcePlugins() { return resourcePlugins; } /** * @deprecated This method will be removed April 2007. No one appears to use * this method, so don't start. */ public String getHelp() { return "Help! - you shouldn't be using this method"; } /** * @deprecated This method will be removed April 2007. Use getMode() * instead. */ public static boolean isHeadless() { return !useView; } /** * @deprecated This method will be removed April 2007. Use getMode() * instead. */ public static boolean useView() { return useView; } /** * @deprecated This method will be removed April 2007. No one appears to use * this method, so don't start. */ public static boolean suppressView() { return suppressView; } /** * @deprecated Use Properties (getProperties()) instead of args for * accessing initialization information. This method will be * removed April 2007. */ public static String[] getArgs() { return initParams.getArgs(); } /** * @deprecated This method will be removed April 2007. */ public static String getPropertiesLocation() { return ""; } /** * @deprecated This method will be removed April 2007. Use * getProperty("bioDataServer") instead. */ public static String getBioDataServer() { return properties.getProperty("bioDataServer"); } /** * @deprecated Will be removed April 2007. Use getProperty( * "canonicalizeNames" ) instead. */ public static boolean noCanonicalization() { return properties.getProperty("canonicalizeNames").equals("true"); } /** * @deprecated Will be removed April 2007. No one appears to be using this * method, so don't start. */ public static Set getExpressionFiles() { return new HashSet(initParams.getExpressionFiles()); } /** * @deprecated Will be removed April 2007. No one appears to be using this * method, so don't start. */ public static Set getGraphFiles() { return new HashSet(initParams.getGraphFiles()); } /** * @deprecated Will be removed April 2007. No one appears to be using this * method, so don't start. */ public static Set getEdgeAttributes() { return new HashSet(initParams.getEdgeAttributeFiles()); } /** * @deprecated Will be removed April 2007. No one appears to be using this * method, so don't start. */ public static Set getNodeAttributes() { return new HashSet(initParams.getNodeAttributeFiles()); } /** * @deprecated Will be removed April 2007. Use getProperty( * "defaultSpeciesName" ) instead. */ public static String getDefaultSpeciesName() { return properties.getProperty("defaultSpeciesName", "unknown"); } /** * @deprecated Will be removed April 2007. Use * CytoscapeDesktop.parseViewType(CytoscapeInit.getProperties().getProperty("viewType")); */ public static int getViewType() { return CytoscapeDesktop.parseViewType(properties.getProperty("viewType")); } /** * Gets the ViewThreshold. Networks with number of nodes below this * threshold will automatically have network views created. * * @return view threshold. * @deprecated Will be removed April 2007. Use getProperty( "viewThreshold" ) * instead. */ public static int getViewThreshold() { return Integer.parseInt(properties.getProperty("viewThreshold")); } /** * Sets the ViewThreshold. Networks with number of nodes below this * threshold will automatically have network views created. * * @param threshold * view threshold. * @deprecated Will be removed April 2007. Use setProperty( "viewThreshold", * thresh ) instead. */ public static void setViewThreshold(int threshold) { properties.setProperty("viewThreshold", Integer.toString(threshold)); } /** * Gets the Secondary View Threshold. This value is a secondary check on * rendering very large networks. It is primarily checked when a user wishes * to create a view for a large network. * * @return threshold value, indicating number of nodes. * @deprecated Will be removed April 2007. Use getProperty( * "secondaryViewThreshold" ) instead. */ public static int getSecondaryViewThreshold() { return secondaryViewThreshold; } /** * Sets the Secondary View Threshold. This value is a secondary check on * rendering very large networks. It is primarily checked when a user wishes * to create a view for a large network. * * @param threshold * value, indicating number of nodes. * @deprecated Will be removed April 2007. Use getProperties().setProperty( * "secondaryViewThreshold", thresh ) instead. */ public static void setSecondaryViewThreshold(int threshold) { secondaryViewThreshold = threshold; } // View Only Variables /** * @deprecated Will be removed April 2007. Use getProperties().getProperty( * "TODO" ) instead. */ public static String getVizmapPropertiesLocation() { return vizmapPropertiesLocation; } /** * @deprecated Will be removed April 2007. Use getProperties().getProperty( * "defaultVisualStyle" ) instead. */ public static String getDefaultVisualStyle() { return properties.getProperty("defaultVisualStyle"); } /** * Parses the plugin input strings and transforms them into the appropriate * URLs or resource names. The method first checks to see if the */ private void loadPlugins() { pluginMgr = new PluginManager(); try { Set plugins = new HashSet(); List p = initParams.getPlugins(); if (p != null) plugins.addAll(p); // Parse the plugin strings and determine whether they're urls, // files, // directories, class names, or manifest file names. for (Iterator iter = plugins.iterator(); iter.hasNext();) { String plugin = (String) iter.next(); File f = new File(plugin); // If the file name ends with .jar add it to the list as a url. if (plugin.endsWith(".jar")) { // If the name doesn't match a url, turn it into one. if (!plugin.matches(FileUtil.urlPattern)) { System.out.println(" - file: " + f.getAbsolutePath()); pluginURLs.add(jarURL(f.getAbsolutePath())); } else { System.out.println(" - url: " + f.getAbsolutePath()); pluginURLs.add(jarURL(plugin)); } // If the file doesn't exists, assume that it's a // resource plugin. } else if (!f.exists()) { System.out.println(" - classpath: " + f.getAbsolutePath()); resourcePlugins.add(plugin); // If the file is a directory, load all of the jars // in the directory. } else if (f.isDirectory()) { System.out.println(" - directory: " + f.getAbsolutePath()); String[] fileList = f.list(); for (int j = 0; j < fileList.length; j++) { if (!fileList[j].endsWith(".jar")) continue; pluginURLs.add(jarURL(f.getAbsolutePath() + System.getProperty("file.separator") + fileList[j])); } // Assume the file is a manifest (i.e. list of jar names) // and make urls out of them. } else { System.out.println(" - file manifest: " + f.getAbsolutePath()); try { TextHttpReader reader = new TextHttpReader(plugin); reader.read(); String text = reader.getText(); String lineSep = System.getProperty("line.separator"); String[] allLines = text.split(lineSep); for (int j = 0; j < allLines.length; j++) { String pluginLoc = allLines[j]; if (pluginLoc.endsWith(".jar")) { if (pluginLoc.matches(FileUtil.urlPattern)) pluginURLs.add(pluginLoc); else System.err.println("Plugin location specified in " + plugin + " is not a valid url: " + pluginLoc + " -- NOT adding it."); } } } catch (Exception exp) { exp.printStackTrace(); System.err.println("error reading plugin manifest file " + plugin); } } } // now load the plugins in the appropriate manner loadURLPlugins(pluginURLs); loadResourcePlugins(resourcePlugins); } catch (Exception e) { System.out.println("failed loading plugin!"); e.printStackTrace(); } //System.out.println(pluginMgr.getPluginTracker().getInstalledPlugins().size() + " installed plugins registered"); } /** * Load all plugins by using the given URLs loading them all on one * URLClassLoader, then interating through each Jar file looking for classes * that are CytoscapePlugins */ private void loadURLPlugins(Set plugin_urls) { URL[] urls = new URL[plugin_urls.size()]; int count = 0; for (Iterator iter = plugin_urls.iterator(); iter.hasNext();) { urls[count] = (URL) iter.next(); count++; } // the creation of the class loader automatically loads the plugins classLoader = new URLClassLoader(urls, Cytoscape.class.getClassLoader()); // iterate through the given jar files and find classes that are // assignable from CytoscapePlugin for (int i = 0; i < urls.length; ++i) { System.out.println(""); System.out.println("attempting to load plugin url: "); System.out.println(urls[i]); try { JarURLConnection jc = (JarURLConnection) urls[i].openConnection(); JarFile jar = jc.getJarFile(); // if the jar file is null, do nothing if (jar == null) { continue; } // try the new school way of loading plugins Manifest m = jar.getManifest(); if (m != null) { String className = m.getMainAttributes().getValue("Cytoscape-Plugin"); if (className != null) { Class pc = getPluginClass(className); if (pc != null) { System.out.println("Loading from manifest"); loadPlugin(pc); continue; } } } // new-school failed, so revert to old school Enumeration entries = jar.entries(); if (entries == null) { continue; } int totalPlugins = 0; while (entries.hasMoreElements()) { // get the entry String entry = entries.nextElement().toString(); if (entry.endsWith("class")) { // convert the entry to an assignable class name entry = entry.replaceAll("\\.class$", ""); // A regex to match the two known types of file // separators. We can't use File.separator because // the system the jar was created on is not // necessarily the same is the one it is running on. entry = entry.replaceAll("/|\\\\", "."); Class pc = getPluginClass(entry); if (pc == null) continue; totalPlugins++; loadPlugin(pc); break; } } if (totalPlugins == 0) System.out.println("No plugin found in specified jar - assuming it's a library."); } catch (Exception e) { System.out.println("Couldn't load plugin url!"); System.err.println("Error: " + e.getMessage()); } } System.out.println(""); } private void loadResourcePlugins(Set rp) { // attempt to load resource plugins for (Iterator rpi = rp.iterator(); rpi.hasNext();) { String resource = (String) rpi.next(); System.out.println(""); System.out.println("attempting to load plugin resourse: " + resource); // try to get the class Class rclass = null; try { rclass = Class.forName(resource); } catch (Exception exc) { System.out.println("Getting class: " + resource + " failed"); exc.printStackTrace(); return; } loadPlugin(rclass); } System.out.println(""); } /** * DOCUMENT ME! * * @param plugin DOCUMENT ME! */ /* TODO add warning to user that another plugin with the same namespace as a previously loaded plugin has been found and will not be * loaded */ public void loadPlugin(Class plugin) { System.out.println("Plugin class: " + plugin.getName()); if (CytoscapePlugin.class.isAssignableFrom(plugin) && !loadedPlugins.contains(plugin.getName())) { try { CytoscapePlugin.loadPlugin(plugin); loadedPlugins.add(plugin.getName()); } catch (Exception e) { e.printStackTrace(); } } else if (loadedPlugins.contains(plugin.getName())) { // TODO warn user class of this name has already been loaded and can't be loaded again } } /** * Determines whether the class with a particular name extends * CytoscapePlugin. * * @param name * the name of the putative plugin class */ protected Class getPluginClass(String name) { Class c = null; try { c = classLoader.loadClass(name); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (NoClassDefFoundError e) { e.printStackTrace(); return null; } if (CytoscapePlugin.class.isAssignableFrom(c)) return c; else return null; } /** * @return the most recently used directory */ public static File getMRUD() { if (mrud == null) mrud = new File(properties.getProperty("mrud", System.getProperty("user.dir"))); return mrud; } /** * @return the most recently used file */ public static File getMRUF() { return mruf; } /** * @param mrud * the most recently used directory */ public static void setMRUD(File mrud_new) { mrud = mrud_new; } /** * @param mruf * the most recently used file */ public static void setMRUF(File mruf_new) { mruf = mruf_new; } /** * @deprecated Will be removed April 2007. This doesn't do anything. To set * the default species name use * getProperties().setProperty("defaultSpeciesName", newName), * which you were presumably doing already. */ public static void setDefaultSpeciesName() { // Update defaultSpeciesName using current properties. // This is necessary to reflect changes in the Preference Editor // immediately } /** * @deprecated This method is only deprecated because it is misspelled. Just * use the correctly spelled method: getConfigDirectory(). This * method will be removed 12/2006. */ public static File getConfigDirectoy() { return getConfigDirectory(); } /** * If .cytoscape directory does not exist, it creates it and returns it * * @return the directory ".cytoscape" in the users home directory. */ public static File getConfigDirectory() { File dir = null; try { String dirName = properties.getProperty("alternative.config.dir", System.getProperty("user.home")); File parent_dir = new File(dirName, ".cytoscape"); if (parent_dir.mkdir()) System.err.println("Parent_Dir: " + parent_dir + " created."); return parent_dir; } catch (Exception e) { System.err.println("error getting config directory"); } return null; } /** * DOCUMENT ME! * * @param file_name DOCUMENT ME! * * @return DOCUMENT ME! */ public static File getConfigFile(String file_name) { try { File parent_dir = getConfigDirectory(); File file = new File(parent_dir, file_name); if (file.createNewFile()) System.err.println("Config file: " + file + " created."); return file; } catch (Exception e) { System.err.println("error getting config file:" + file_name); } return null; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Properties getVisualProperties() { return visualProperties; } private static void loadStaticProperties(String defaultName, Properties props) { if (props == null) { System.out.println("input props is null"); props = new Properties(); } String tryName = ""; try { // load the props from the jar file tryName = "cytoscape.jar"; // This somewhat unusual way of getting the ClassLoader is because // other methods don't work from WebStart. ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL vmu = null; if (cl != null) vmu = cl.getResource(defaultName); else System.out.println("ClassLoader for reading cytoscape.jar is null"); if (vmu != null) props.load(vmu.openStream()); else System.out.println("couldn't read " + defaultName + " from " + tryName); // load the props file from $HOME/.cytoscape tryName = "$HOME/.cytoscape"; File vmp = CytoscapeInit.getConfigFile(defaultName); if (vmp != null) props.load(new FileInputStream(vmp)); else System.out.println("couldn't read " + defaultName + " from " + tryName); } catch (IOException ioe) { System.err.println("couldn't open " + tryName + " " + defaultName + " file - creating a hardcoded default"); ioe.printStackTrace(); } } private static void loadExpressionFiles() { // load expression data if specified List ef = initParams.getExpressionFiles(); if ((ef != null) && (ef.size() > 0)) { for (Iterator iter = ef.iterator(); iter.hasNext();) { String expDataFilename = (String) iter.next(); if (expDataFilename != null) { try { Cytoscape.loadExpressionData(expDataFilename, true); } catch (Exception e) { e.printStackTrace(); } } } } } private static URL jarURL(String urlString) { URL url = null; try { String uString; if (urlString.matches(FileUtil.urlPattern)) uString = "jar:" + urlString + "!/"; else uString = "jar:file:" + urlString + "!/"; url = new URL(uString); } catch (MalformedURLException mue) { mue.printStackTrace(); System.out.println("couldn't create jar url from '" + urlString + "'"); } return url; } private boolean loadSessionFile() { String sessionFile = initParams.getSessionFile(); // Turn off the network panel (for loading speed) Cytoscape.getDesktop().getNetworkPanel().getTreeTable().setVisible(false); try { String sessionName = ""; if (sessionFile != null) { Cytoscape.setSessionState(Cytoscape.SESSION_OPENED); Cytoscape.createNewSession(); Cytoscape.setSessionState(Cytoscape.SESSION_NEW); CytoscapeSessionReader reader = null; if (sessionFile.matches(FileUtil.urlPattern)) { URL u = new URL(sessionFile); reader = new CytoscapeSessionReader(u); sessionName = u.getFile(); } else { Cytoscape.setCurrentSessionFileName(sessionFile); File shortName = new File(sessionFile); URL sessionURL = shortName.toURL(); reader = new CytoscapeSessionReader(sessionURL); sessionName = shortName.getName(); } if (reader != null) { reader.read(); Cytoscape.getDesktop() .setTitle("Cytoscape Desktop (Session Name: " + sessionName + ")"); return true; } } } catch (Exception e) { e.printStackTrace(); System.out.println("couldn't create session from file: '" + sessionFile + "'"); } finally { Cytoscape.getDesktop().getNetworkPanel().getTreeTable().setVisible(true); } return false; } private static void initProperties() { if (properties == null) { properties = new Properties(); loadStaticProperties("cytoscape.props", properties); } if (visualProperties == null) { visualProperties = new Properties(); loadStaticProperties("vizmap.props", visualProperties); } } private void setUpAttributesChangedListener() { /* * This cannot be done in CytoscapeDesktop construction (like the other * menus) because we need CytoscapeDesktop created first. This is * because CytoPanel menu item listeners need to register for CytoPanel * events via a CytoPanel reference, and the only way to get a CytoPanel * reference is via CytoscapeDeskop: * Cytoscape.getDesktop().getCytoPanel(...) * Cytoscape.getDesktop().getCyMenus().initCytoPanelMenus(); Add a * listener that will apply vizmaps every time attributes change */ PropertyChangeListener attsChangeListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals(Cytoscape.ATTRIBUTES_CHANGED)) { // apply vizmaps Cytoscape.getCurrentNetworkView().redrawGraph(false, true); } } }; Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener(attsChangeListener); } // Load all requested networks private void loadNetworks() { for (Iterator i = initParams.getGraphFiles().iterator(); i.hasNext();) { String net = (String) i.next(); System.out.println("Load: " + net); CyNetwork network = null; - - // be careful not to assume that a view has been created + + boolean createView = false; if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) + createView = true; + + if ( net.matches(FileUtil.urlPattern) ) { + try { + network = Cytoscape.createNetworkFromURL(new URL(net), true); + } catch ( MalformedURLException mue ) { + mue.printStackTrace(); + System.out.println("Couldn't load network. Bad URL!"); + } + } else { network = Cytoscape.createNetworkFromFile(net, true); - else - network = Cytoscape.createNetworkFromFile(net, false); + } // This is for browser and other plugins. Object[] ret_val = new Object[3]; ret_val[0] = network; ret_val[1] = net; ret_val[2] = new Integer(0); Cytoscape.firePropertyChange(Cytoscape.NETWORK_LOADED, null, ret_val); } } // load any specified data attribute files private void loadAttributes() { try { Cytoscape.loadAttributes((String[]) initParams.getNodeAttributeFiles() .toArray(new String[] { }), (String[]) initParams.getEdgeAttributeFiles() .toArray(new String[] { })); } catch (Exception ex) { ex.printStackTrace(); System.out.println("failure loading specified attributes"); } } }
false
false
null
null
diff --git a/src/br/com/vinigodoy/raytracer/gui/WorldMaker.java b/src/br/com/vinigodoy/raytracer/gui/WorldMaker.java index 2f87946..93d047b 100644 --- a/src/br/com/vinigodoy/raytracer/gui/WorldMaker.java +++ b/src/br/com/vinigodoy/raytracer/gui/WorldMaker.java @@ -1,271 +1,292 @@ /*=========================================================================== COPYRIGHT 2013 Vinícius G. Mendonça ALL RIGHTS RESERVED. This software cannot be copied, stored, distributed without Vinícius G. Mendonça prior authorization. This file was made available on https://github.com/ViniGodoy and it is free to be redistributed or used under Creative Commons license 2.5 br: http://creativecommons.org/licenses/by-sa/2.5/br/ ============================================================================*/ package br.com.vinigodoy.raytracer.gui; import br.com.vinigodoy.raytracer.camera.PinholeCamera; import br.com.vinigodoy.raytracer.camera.ThinLensCamera; import br.com.vinigodoy.raytracer.light.AmbientOccludedLight; import br.com.vinigodoy.raytracer.light.AreaLight; import br.com.vinigodoy.raytracer.light.PointLight; import br.com.vinigodoy.raytracer.material.Emissive; import br.com.vinigodoy.raytracer.material.Matte; import br.com.vinigodoy.raytracer.material.Phong; import br.com.vinigodoy.raytracer.math.Vector3; +import br.com.vinigodoy.raytracer.math.geometry.Instance; import br.com.vinigodoy.raytracer.math.geometry.part.ConvexPartSphere; import br.com.vinigodoy.raytracer.math.geometry.primitive.*; import br.com.vinigodoy.raytracer.sampler.Sampler; import br.com.vinigodoy.raytracer.scene.World; import br.com.vinigodoy.raytracer.scene.WorldListener; import br.com.vinigodoy.raytracer.tracer.AreaLightTracer; import br.com.vinigodoy.raytracer.tracer.Raycasting; public enum WorldMaker { BALLS { @Override public World createScene(int numSamples, float zoom, WorldListener listener) { PinholeCamera camera = new PinholeCamera( new Vector3(0, 0, 800), new Vector3(0, 0, 0), new Vector3(0, 1, 0), 2000); camera.setZoom(zoom); World world = new World(toString(), new Raycasting(), new Vector3(), camera); world.setAmbientLight(new AmbientOccludedLight(1.5f, new Vector3(1.0f, 1.0f, 1.0f), 0.4f, Sampler.newDefault(numSamples))); world.addListener(listener); //Lights world.add(new PointLight(3.0f, new Vector3(1.0f, 1.0f, 1.0f), new Vector3(100.0f, 100.0f, 200.0f))); // colors Vector3 lightGreen = new Vector3(0.65f, 1.0f, 0.30f); Vector3 green = new Vector3(0.0f, 0.6f, 0.3f); Vector3 darkGreen = new Vector3(0.0f, 0.41f, 0.41f); Vector3 yellow = new Vector3(1.0f, 1.0f, 0.0f); Vector3 darkYellow = new Vector3(0.61f, 0.61f, 0.0f); Vector3 lightPurple = new Vector3(0.65f, 0.3f, 1.0f); Vector3 darkPurple = new Vector3(0.5f, 0.0f, 1.0f); Vector3 brown = new Vector3(0.71f, 0.40f, 0.16f); Vector3 orange = new Vector3(1.0f, 0.75f, 0.0f); // spheres world.add(new Plane(new Vector3(0, -85, 0), new Vector3(0, 1, 0), new Matte(0.2f, 0.5f, new Vector3(1, 1, 1)))); world.add(new Sphere(new Vector3(5, 3, 0), 30, yellow)); world.add(new Sphere(new Vector3(45, -7, -60), 20, brown)); world.add(new Sphere(new Vector3(40, 43, -100), 17, darkGreen)); world.add(new Sphere(new Vector3(-20, 28, -15), 20, orange)); world.add(new Sphere(new Vector3(-25, -7, -35), 27, green)); world.add(new Sphere(new Vector3(20, -27, -35), 25, lightGreen)); world.add(new Sphere(new Vector3(35, 18, -35), 22, green)); world.add(new Sphere(new Vector3(-57, -17, -50), 15, brown)); world.add(new Sphere(new Vector3(-47, 16, -80), 23, lightGreen)); world.add(new Sphere(new Vector3(-15, -32, -60), 22, darkGreen)); world.add(new Sphere(new Vector3(-35, -37, -80), 22, darkYellow)); world.add(new Sphere(new Vector3(10, 43, -80), 22, darkYellow)); world.add(new Sphere(new Vector3(30, -7, -80), 10, darkYellow)); //(hidden) world.add(new Sphere(new Vector3(-40, 48, -110), 18, darkGreen)); world.add(new Sphere(new Vector3(-10, 53, -120), 18, brown)); world.add(new Sphere(new Vector3(-55, -52, -100), 10, lightPurple)); world.add(new Sphere(new Vector3(5, -52, -100), 15, brown)); world.add(new Sphere(new Vector3(-20, -57, -120), 15, darkPurple)); world.add(new Sphere(new Vector3(55, -27, -100), 17, darkGreen)); world.add(new Sphere(new Vector3(50, -47, -120), 15, brown)); world.add(new Sphere(new Vector3(70, -42, -150), 10, lightPurple)); world.add(new Sphere(new Vector3(5, 73, -130), 12, lightPurple)); world.add(new Sphere(new Vector3(66, 21, -130), 13, darkPurple)); world.add(new Sphere(new Vector3(72, -12, -140), 12, lightPurple)); world.add(new Sphere(new Vector3(64, 5, -160), 11, green)); world.add(new Sphere(new Vector3(55, 38, -160), 12, lightPurple)); world.add(new Sphere(new Vector3(-73, -2, -160), 12, lightPurple)); world.add(new Sphere(new Vector3(30, -62, -140), 15, darkPurple)); world.add(new Sphere(new Vector3(25, 63, -140), 15, darkPurple)); world.add(new Sphere(new Vector3(-60, 46, -140), 15, darkPurple)); world.add(new Sphere(new Vector3(-30, 68, -130), 12, lightPurple)); world.add(new Sphere(new Vector3(58, 56, -180), 11, green)); world.add(new Sphere(new Vector3(-63, -39, -180), 11, green)); world.add(new Sphere(new Vector3(46, 68, -200), 10, lightPurple)); world.add(new Sphere(new Vector3(-3, -72, -130), 12, lightPurple)); return world; } }, BILLIARD { private static final float BALL_CM = 5.715f / 2.0f; private Sphere createCarom(float x, float z) { float caromCm = 6.15f / 2.0f; return new Sphere(new Vector3(x, caromCm, z), caromCm, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1, 1, 1))); } private Sphere createBall(float x, float z, Vector3 color) { Phong material = new Phong(0.2f, 0.65f, 0.4f, 64.00f, color); material.setCs(new Vector3(1, 1, 1)); return new Sphere(new Vector3(x, BALL_CM, z), BALL_CM, material); } private void createLamp(World world, float w, float y, float z, int numSamples) { float hw = w / 2.0f; Rectangle shape = new Rectangle( new Vector3(-hw, y, -hw + z), new Vector3(w, 0, 0), new Vector3(0, 0, w), new Vector3(0, -1, 0), new Emissive(40000, new Vector3(1, 1, 1)), Sampler.newDefault(numSamples)); world.add(new AreaLight(shape)); world.add(shape); } @Override public World createScene(int numSamples, float zoom, WorldListener listener) { ThinLensCamera camera = new ThinLensCamera( new Vector3(10, 10, 190), new Vector3(0, 0, 0), new Vector3(0, 1, 0), 2000, 190 + 86, 0.25f, Sampler.newDefault(numSamples)); /* Camera over the table ThinLensCamera camera = new ThinLensCamera( new Vector3(0, 760, 0), new Vector3(0, 0, 0), new Vector3(0, 1, 0), 2000, 700, 0.6f, Sampler.newDefault(numSamples));*/ camera.setZoom(zoom); World world = new World(toString(), new AreaLightTracer(), new Vector3(0f, 0f, 0f), camera); world.setAmbientLight(new AmbientOccludedLight(1.5f, new Vector3(1.0f, 1.0f, 1.0f), 0.4f, Sampler.newDefault(numSamples))); world.addListener(listener); //Lights createLamp(world, 20, 100, -60, numSamples); createLamp(world, 20, 100, 60, numSamples); // colors Vector3 one = new Vector3(1.0f, 1.0f, 0.0f); //Yellow Vector3 two = new Vector3(0.0f, 0.0f, 1.0f); //Blue Vector3 three = new Vector3(1.0f, 0.0f, 0.0f); //Red Vector3 four = new Vector3(0.29f, 0.0f, 0.5f); //Purple Vector3 five = new Vector3(1.0f, 0.5f, 0.0f); //Orange Vector3 six = new Vector3(0.0f, 0.41f, 0.41f); //Green Vector3 seven = new Vector3(0.545f, 0.27f, 0.074f); //Brown Vector3 eight = new Vector3(0.1f, 0.1f, 0.1f); //Black Vector3 nine = new Vector3(1.0f, 1.0f, 0.0f); //Yellow and White Vector3 ten = new Vector3(0.0f, 0.0f, 1.0f); //Blue and white Vector3 eleven = new Vector3(1.0f, 0.0f, 0.0f); //Red and white Vector3 twelve = new Vector3(0.29f, 0.0f, 0.5f); //Purple and white Vector3 thirteen = new Vector3(1.0f, 0.5f, 0.0f); //Orange and white Vector3 fourteen = new Vector3(0.0f, 0.41f, 0.41f); //Green and white Vector3 fifteen = new Vector3(0.545f, 0.27f, 0.074f); //Brown and white //Vector3 table = new Vector3(0.188f, 0.5f, 0.14f); //Green Vector3 table = Vector3.fromRGB(10, 108, 3); // Table world.add(new Rectangle(new Vector3(-71, 0, -142), new Vector3(142, 0, 0), new Vector3(0, 0, 284), new Vector3(0, 1, 0), new Matte(0.2f, 0.5f, table))); // Balls world.add(createCarom(0, 122)); world.add(createBall(0, -86, one)); world.add(createBall(-3, -92.0f, two)); world.add(createBall(3, -92.0f, three)); world.add(createBall(-6, -98.0f, four)); world.add(createBall(0, -98.0f, five)); world.add(createBall(6, -98.0f, six)); world.add(createBall(-9, -104.0f, seven)); world.add(createBall(-3, -104.0f, eight)); world.add(createBall(3, -104.0f, nine)); world.add(createBall(9, -104.0f, ten)); world.add(createBall(-12, -110.0f, eleven)); world.add(createBall(-6, -110.0f, twelve)); world.add(createBall(0, -110.0f, thirteen)); world.add(createBall(6, -110.0f, fourteen)); world.add(createBall(12, -110.0f, fifteen)); return world; } }, OBJECTS { @Override public World createScene(int numSamples, float zoom, WorldListener listener) { PinholeCamera camera = new PinholeCamera( new Vector3(-30, 50, 110), new Vector3(0, 0, 0), new Vector3(0, 1, 0), 200); camera.setZoom(zoom); World world = new World(toString(), new Raycasting(), new Vector3(), camera); world.addListener(listener); //Lights - world.setAmbientLight(new AmbientOccludedLight(1.0f, new Vector3(1.0f, 1.0f, 1.0f), 0.4f, + world.setAmbientLight(new AmbientOccludedLight(1.5f, new Vector3(1.0f, 1.0f, 1.0f), 0.4f, Sampler.newDefault(numSamples))); - world.add(new PointLight(3.0f, new Vector3(1.0f, 1.0f, 1.0f), new Vector3(20.0f, 70.0f, 100.0f))); - + world.add(new PointLight(4.0f, new Vector3(1.0f, 1.0f, 1.0f), new Vector3(50.0f, 80.0f, 150.0f))); + world.getBackgroundColor().set(1, 1, 1); + Phong blue = new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(0.0f, 0.0f, 1.0f)); + Phong yellow = new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 1.0f, 0.0f)); + Phong black = new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(0.1f, 0.1f, 0.1f)); + Phong green = new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(0.0f, 1.0f, 0.0f)); + Phong red = new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.0f, 0.0f)); + + Torus torus = new Torus(15, 3f, blue); + float angle1 = (float) Math.toRadians(90); + float angle2 = (float) Math.toRadians(80); + + Instance arc1 = new Instance(torus).rotateX(angle1).translate(-40, 60, 0); + Instance arc2 = new Instance(torus, yellow).rotateX(angle2).translate(-20, 50, 0); + Instance arc3 = new Instance(torus, black).rotateX(angle1).translate(-0, 60, 0); + Instance arc4 = new Instance(torus, green).rotateX(angle2).translate(20, 50, 0); + Instance arc5 = new Instance(torus, red).rotateX(angle1).translate(40, 60, 0); + + Instance box = new Instance(new Box(-30, 30, -30, 30, -30, 30, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(0.3f, 0.3f, 1.0f)))); + box.translate(230, -50, 30); //Objects + world.addAll(arc1, arc2, arc3, arc4, arc5); + world.add(new Torus(45, 6f, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.8f, 0.3f)))); world.add(new Disk(new Vector3(0, -20, 0), new Vector3(0, 1, 0), 60, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.3f, 0.3f)))); world.add(new OpenCylinder(-20, 10, 60, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.3f, 0.3f)))); - world.add(new Box(-15, 15, -15, 15, -15, 15, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(0.3f, 0.3f, 1.0f)))); + world.add(box); world.add(ConvexPartSphere.withDegrees(new Vector3(0, 0, 0), 80, 0f, 360, 90, 180, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.6f, 0.2f)))); world.add(ConvexPartSphere.withDegrees(new Vector3(0, 0, 0), 75, 0f, 360, 90, 180, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.6f, 0.2f)))); world.add(new Annulus(new Vector3(0, 0, 0), new Vector3(0, 1, 0), 80, 75, new Phong(0.2f, 0.65f, 0.4f, 64.00f, new Vector3(1.0f, 0.6f, 0.2f)))); world.add(new Plane(new Vector3(0, -80, 0), new Vector3(0, 1, 0), new Matte(0.2f, 0.5f, new Vector3(1, 1, 1)))); return world; } }; public abstract World createScene(int numSamples, float zoom, WorldListener listener); @Override public String toString() { String name = super.toString(); return name.charAt(0) + name.substring(1).toLowerCase(); } }
false
false
null
null
diff --git a/src/com/fsck/k9/activity/MessageView.java b/src/com/fsck/k9/activity/MessageView.java index 40c64519..fef66ebf 100644 --- a/src/com/fsck/k9/activity/MessageView.java +++ b/src/com/fsck/k9/activity/MessageView.java @@ -1,1242 +1,1249 @@ package com.fsck.k9.activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Config; import android.util.Log; import android.view.*; import android.view.View.OnClickListener; import android.widget.*; import com.fsck.k9.*; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.crypto.PgpData; import com.fsck.k9.helper.FileBrowserHelper; import com.fsck.k9.helper.FileBrowserHelper.FileBrowserFailOverCallback; import com.fsck.k9.mail.*; import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.view.AttachmentView; import com.fsck.k9.view.ToggleScrollView; import com.fsck.k9.view.SingleMessageView; import com.fsck.k9.view.AttachmentView.AttachmentFileDownloadCallback; import java.io.File; import java.util.*; public class MessageView extends K9Activity implements OnClickListener { private static final String EXTRA_MESSAGE_REFERENCE = "com.fsck.k9.MessageView_messageReference"; private static final String EXTRA_MESSAGE_REFERENCES = "com.fsck.k9.MessageView_messageReferences"; private static final String EXTRA_NEXT = "com.fsck.k9.MessageView_next"; private static final String EXTRA_SCROLL_PERCENTAGE = "com.fsck.k9.MessageView_scrollPercentage"; private static final String SHOW_PICTURES = "showPictures"; private static final String STATE_PGP_DATA = "pgpData"; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final int ACTIVITY_CHOOSE_DIRECTORY = 3; private SingleMessageView mMessageView; private PgpData mPgpData; private View mNext; private View mPrevious; private View mDelete; private View mArchive; private View mMove; private View mSpam; private Account mAccount; private MessageReference mMessageReference; private ArrayList<MessageReference> mMessageReferences; private Message mMessage; private static final int PREVIOUS = 1; private static final int NEXT = 2; private int mLastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS; private MessagingController mController = MessagingController.getInstance(getApplication()); private MessageReference mNextMessage = null; private MessageReference mPreviousMessage = null; private Listener mListener = new Listener(); private MessageViewHandler mHandler = new MessageViewHandler(); private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); /** this variable is used to save the calling AttachmentView * until the onActivityResult is called. * => with this reference we can identity the caller */ private AttachmentView attachmentTmpStore; /** * Used to temporarily store the destination folder for refile operations if a confirmation * dialog is shown. */ private String mDstFolder; private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (!providerId.equals(mAccount.getLocalStorageProviderId())) { return; } runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } @Override public void onMount(String providerId) { /* no-op */ } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_UP) { // Text selection is finished. Allow scrolling again. mTopView.setScrolling(true); } else if (K9.zoomControlsEnabled()) { // If we have system zoom controls enabled, disable scrolling so the screen isn't wiggling around while // trying to zoom. if (ev.getAction() == MotionEvent.ACTION_POINTER_2_DOWN) { mTopView.setScrolling(false); } else if (ev.getAction() == MotionEvent.ACTION_POINTER_2_UP) { mTopView.setScrolling(true); } } return super.dispatchTouchEvent(ev); } @Override public boolean dispatchKeyEvent(KeyEvent event) { boolean ret = false; if (KeyEvent.ACTION_DOWN == event.getAction()) { - ret = onKeyDown(event.getKeyCode(), event); + ret = onCustomKeyDown(event.getKeyCode(), event); } if (!ret) { ret = super.dispatchKeyEvent(event); } return ret; } - @Override - public boolean onKeyDown(final int keyCode, final KeyEvent event) { - if ( - // XXX TODO - when we go to android 2.0, uncomment this - // android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && - keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { - // Take care of calling this method on earlier versions of - // the platform where it doesn't exist. - onBackPressed(); - return true; - } + /** + * Handle hotkeys + * + * <p> + * This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance + * to consume this key event. + * </p> + * + * @param keyCode + * The value in {@code event.getKeyCode()}. + * @param event + * Description of the key event. + * + * @return {@code true} if this event was consumed. + */ + public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { if (K9.useVolumeKeysForNavigationEnabled()) { onNext(); return true; } + break; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (K9.useVolumeKeysForNavigationEnabled()) { onPrevious(); return true; } + break; } case KeyEvent.KEYCODE_SHIFT_LEFT: case KeyEvent.KEYCODE_SHIFT_RIGHT: { /* * Selecting text started via shift key. Disable scrolling as * this causes problems when selecting text. */ mTopView.setScrolling(false); break; } case KeyEvent.KEYCODE_DEL: { onDelete(); return true; } case KeyEvent.KEYCODE_D: { onDelete(); return true; } case KeyEvent.KEYCODE_F: { onForward(); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(); return true; } case KeyEvent.KEYCODE_R: { onReply(); return true; } case KeyEvent.KEYCODE_G: { onFlag(); return true; } case KeyEvent.KEYCODE_M: { onMove(); return true; } case KeyEvent.KEYCODE_S: { onRefile(mAccount.getSpamFolderName()); return true; } case KeyEvent.KEYCODE_V: { onRefile(mAccount.getArchiveFolderName()); return true; } case KeyEvent.KEYCODE_Y: { onCopy(); return true; } case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_P: { onPrevious(); return true; } case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_K: { onNext(); return true; } case KeyEvent.KEYCODE_Z: { mHandler.post(new Runnable() { public void run() { mMessageView.zoom(event); } }); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } - return super.onKeyDown(keyCode, event); + return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } @Override public void onBackPressed() { if (K9.manageBack()) { String folder = (mMessage != null) ? mMessage.getFolder().getName() : null; MessageList.actionHandleFolder(this, mAccount, folder); finish(); } else { super.onBackPressed(); } } class MessageViewHandler extends Handler { public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { setProgressBarIndeterminateVisibility(progress); } }); } public void addAttachment(final View attachmentView) { runOnUiThread(new Runnable() { public void run() { mMessageView.addAttachment(attachmentView); } }); } /* A helper for a set of "show a toast" methods */ private void showToast(final String message, final int toastLength) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(MessageView.this, message, toastLength).show(); } }); } public void networkError() { showToast(getString(R.string.status_network_error), Toast.LENGTH_LONG); } public void invalidIdError() { showToast(getString(R.string.status_invalid_id_error), Toast.LENGTH_LONG); } public void fetchingAttachment() { showToast(getString(R.string.message_view_fetching_attachment_toast), Toast.LENGTH_SHORT); } public void setHeaders(final Message message, final Account account) { runOnUiThread(new Runnable() { public void run() { mMessageView.setHeaders(message, account); } }); } } public static void actionView(Context context, MessageReference messRef, ArrayList<MessageReference> messReferences) { Intent i = new Intent(context, MessageView.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, messRef); i.putParcelableArrayListExtra(EXTRA_MESSAGE_REFERENCES, messReferences); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle, false); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.message_view); mTopView = (ToggleScrollView) findViewById(R.id.top_view); mMessageView = (SingleMessageView) findViewById(R.id.message_view); //set a callback for the attachment view. With this callback the attachmentview //request the start of a filebrowser activity. mMessageView.setAttachmentCallback(new AttachmentFileDownloadCallback() { @Override public void showFileBrowser(final AttachmentView caller) { FileBrowserHelper.getInstance() .showFileBrowserActivity(MessageView.this, null, MessageView.ACTIVITY_CHOOSE_DIRECTORY, callback); attachmentTmpStore = caller; } FileBrowserFailOverCallback callback = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { attachmentTmpStore.writeFile(new File(path)); } @Override public void onCancel() { // canceled, do nothing } }; }); mMessageView.initialize(this); // Register the ScrollView's listener to handle scrolling to last known location on resume. mController.addListener(mTopView.getListener()); mMessageView.setListeners(mController.getListeners()); setTitle(""); final Intent intent = getIntent(); Uri uri = intent.getData(); if (icicle != null) { // TODO This code seems unnecessary since the icicle should already be thawed in onRestoreInstanceState(). mMessageReference = icicle.getParcelable(EXTRA_MESSAGE_REFERENCE); mMessageReferences = icicle.getParcelableArrayList(EXTRA_MESSAGE_REFERENCES); mPgpData = (PgpData) icicle.getSerializable(STATE_PGP_DATA); } else { if (uri == null) { mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); mMessageReferences = intent.getParcelableArrayListExtra(EXTRA_MESSAGE_REFERENCES); } else { List<String> segmentList = uri.getPathSegments(); if (segmentList.size() != 3) { //TODO: Use resource to externalize message Toast.makeText(this, "Invalid intent uri: " + uri.toString(), Toast.LENGTH_LONG).show(); return; } String accountId = segmentList.get(0); Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts(); boolean found = false; for (Account account : accounts) { if (String.valueOf(account.getAccountNumber()).equals(accountId)) { mAccount = account; found = true; break; } } if (!found) { //TODO: Use resource to externalize message Toast.makeText(this, "Invalid account id: " + accountId, Toast.LENGTH_LONG).show(); return; } mMessageReference = new MessageReference(); mMessageReference.accountUuid = mAccount.getUuid(); mMessageReference.folderName = segmentList.get(1); mMessageReference.uid = segmentList.get(2); mMessageReferences = new ArrayList<MessageReference>(); } } mAccount = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); if (K9.DEBUG) Log.d(K9.LOG_TAG, "MessageView got message " + mMessageReference); if (intent.getBooleanExtra(EXTRA_NEXT, false)) { mNext.requestFocus(); } setupButtonViews(); displayMessage(mMessageReference); } private void setupButtonViews() { setOnClickListener(R.id.from); setOnClickListener(R.id.reply); setOnClickListener(R.id.reply_all); setOnClickListener(R.id.delete); setOnClickListener(R.id.forward); setOnClickListener(R.id.next); setOnClickListener(R.id.previous); setOnClickListener(R.id.archive); setOnClickListener(R.id.move); setOnClickListener(R.id.spam); // To show full header setOnClickListener(R.id.header_container); setOnClickListener(R.id.reply_scrolling); // setOnClickListener(R.id.reply_all_scrolling); setOnClickListener(R.id.delete_scrolling); setOnClickListener(R.id.forward_scrolling); setOnClickListener(R.id.next_scrolling); setOnClickListener(R.id.previous_scrolling); setOnClickListener(R.id.archive_scrolling); setOnClickListener(R.id.move_scrolling); setOnClickListener(R.id.spam_scrolling); setOnClickListener(R.id.show_pictures); setOnClickListener(R.id.download_remainder); // Perhaps the ScrollButtons should be global, instead of account-specific Account.ScrollButtons scrollButtons = mAccount.getScrollMessageViewButtons(); if ((Account.ScrollButtons.ALWAYS == scrollButtons) || (Account.ScrollButtons.KEYBOARD_AVAILABLE == scrollButtons && (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) { scrollButtons(); } else { // never or the keyboard is open staticButtons(); } Account.ScrollButtons scrollMoveButtons = mAccount.getScrollMessageViewMoveButtons(); if ((Account.ScrollButtons.ALWAYS == scrollMoveButtons) || (Account.ScrollButtons.KEYBOARD_AVAILABLE == scrollMoveButtons && (this.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO))) { scrollMoveButtons(); } else { staticMoveButtons(); } if (!mAccount.getEnableMoveButtons()) { View buttons = findViewById(R.id.move_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } buttons = findViewById(R.id.scrolling_move_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable(EXTRA_MESSAGE_REFERENCE, mMessageReference); outState.putParcelableArrayList(EXTRA_MESSAGE_REFERENCES, mMessageReferences); outState.putSerializable(STATE_PGP_DATA, mPgpData); outState.putBoolean(SHOW_PICTURES, mMessageView.showPictures()); outState.putDouble(EXTRA_SCROLL_PERCENTAGE, mTopView.getScrollPercentage()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA); mMessageView.updateCryptoLayout(mAccount.getCryptoProvider(), mPgpData, mMessage); mMessageView.setLoadPictures(savedInstanceState.getBoolean(SHOW_PICTURES)); mTopView.setScrollPercentage(savedInstanceState.getDouble(EXTRA_SCROLL_PERCENTAGE)); } private void displayMessage(MessageReference ref) { mMessageReference = ref; if (K9.DEBUG) Log.d(K9.LOG_TAG, "MessageView displaying message " + mMessageReference); mAccount = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); clearMessageDisplay(); findSurroundingMessagesUid(); // start with fresh, empty PGP data mPgpData = new PgpData(); mTopView.setVisibility(View.VISIBLE); mController.loadMessageForView(mAccount, mMessageReference.folderName, mMessageReference.uid, mListener); setupDisplayMessageButtons(); } private void clearMessageDisplay() { mTopView.setVisibility(View.GONE); mTopView.scrollTo(0, 0); mMessageView.resetView(); } private void setupDisplayMessageButtons() { mDelete.setEnabled(true); mNext.setEnabled(mNextMessage != null); mPrevious.setEnabled(mPreviousMessage != null); // If moving isn't support at all, then all of them must be disabled anyway. if (mController.isMoveCapable(mAccount)) { // Only enable the button if the Archive folder is not the current folder and not NONE. mArchive.setEnabled(!mMessageReference.folderName.equals(mAccount.getArchiveFolderName()) && !K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())); // Only enable the button if the Spam folder is not the current folder and not NONE. mSpam.setEnabled(!mMessageReference.folderName.equals(mAccount.getSpamFolderName()) && !K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())); mMove.setEnabled(true); } else { disableMoveButtons(); } } private void staticButtons() { View buttons = findViewById(R.id.scrolling_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } mNext = findViewById(R.id.next); mPrevious = findViewById(R.id.previous); mDelete = findViewById(R.id.delete); } private void scrollButtons() { View buttons = findViewById(R.id.bottom_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } mNext = findViewById(R.id.next_scrolling); mPrevious = findViewById(R.id.previous_scrolling); mDelete = findViewById(R.id.delete_scrolling); } private void staticMoveButtons() { View buttons = findViewById(R.id.scrolling_move_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } mArchive = findViewById(R.id.archive); mMove = findViewById(R.id.move); mSpam = findViewById(R.id.spam); } private void scrollMoveButtons() { View buttons = findViewById(R.id.move_buttons); if (buttons != null) { buttons.setVisibility(View.GONE); } mArchive = findViewById(R.id.archive_scrolling); mMove = findViewById(R.id.move_scrolling); mSpam = findViewById(R.id.spam_scrolling); } private void disableButtons() { mMessageView.setLoadPictures(false); disableMoveButtons(); mNext.setEnabled(false); mPrevious.setEnabled(false); mDelete.setEnabled(false); } private void disableMoveButtons() { mArchive.setEnabled(false); mMove.setEnabled(false); mSpam.setEnabled(false); } private void setOnClickListener(int viewCode) { View thisView = findViewById(viewCode); if (thisView != null) { thisView.setOnClickListener(this); } } private void findSurroundingMessagesUid() { mNextMessage = mPreviousMessage = null; int i = mMessageReferences.indexOf(mMessageReference); if (i < 0) return; if (i != 0) mNextMessage = mMessageReferences.get(i - 1); if (i != (mMessageReferences.size() - 1)) mPreviousMessage = mMessageReferences.get(i + 1); } @Override public void onResume() { super.onResume(); if (!mAccount.isAvailable(this)) { onAccountUnavailable(); return; } mController.addListener(mTopView.getListener()); StorageManager.getInstance(getApplication()).addListener(mStorageListener); } @Override protected void onPause() { mController.removeListener(mTopView.getListener()); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); super.onPause(); } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } /** * Called from UI thread when user select Delete */ private void onDelete() { if (K9.confirmDelete() || (K9.confirmDeleteStarred() && mMessage.isSet(Flag.FLAGGED))) { showDialog(R.id.dialog_confirm_delete); } else { delete(); } } private void delete() { if (mMessage != null) { // Disable the delete button after it's tapped (to try to prevent // accidental clicks) disableButtons(); Message messageToDelete = mMessage; showNextMessageOrReturn(); mController.deleteMessages(new Message[] {messageToDelete}, null); } } private void onRefile(String dstFolder) { if (!mController.isMoveCapable(mAccount)) { return; } if (!mController.isMoveCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) { return; } if (mAccount.getSpamFolderName().equals(dstFolder) && K9.confirmSpam()) { mDstFolder = dstFolder; showDialog(R.id.dialog_confirm_spam); } else { refileMessage(dstFolder); } } private void refileMessage(String dstFolder) { String srcFolder = mMessageReference.folderName; Message messageToMove = mMessage; showNextMessageOrReturn(); mController.moveMessage(mAccount, srcFolder, messageToMove, dstFolder, null); } private void showNextMessageOrReturn() { if (K9.messageViewReturnToList()) { finish(); } else { showNextMessage(); } } private void showNextMessage() { findSurroundingMessagesUid(); mMessageReferences.remove(mMessageReference); if (mLastDirection == NEXT && mNextMessage != null) { onNext(); } else if (mLastDirection == PREVIOUS && mPreviousMessage != null) { onPrevious(); } else if (mNextMessage != null) { onNext(); } else if (mPreviousMessage != null) { onPrevious(); } else { finish(); } } private void onReply() { if (mMessage != null) { MessageCompose.actionReply(this, mAccount, mMessage, false, mPgpData.getDecryptedData()); finish(); } } private void onReplyAll() { if (mMessage != null) { MessageCompose.actionReply(this, mAccount, mMessage, true, mPgpData.getDecryptedData()); finish(); } } private void onForward() { if (mMessage != null) { MessageCompose.actionForward(this, mAccount, mMessage, mPgpData.getDecryptedData()); finish(); } } private void onFlag() { if (mMessage != null) { mController.setFlag(mAccount, mMessage.getFolder().getName(), new String[] {mMessage.getUid()}, Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED)); try { mMessage.setFlag(Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED)); mMessageView.setHeaders(mMessage, mAccount); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set flag on local message", me); } } } private void onMove() { if ((!mController.isMoveCapable(mAccount)) || (mMessage == null)) { return; } if (!mController.isMoveCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } startRefileActivity(ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onCopy() { if ((!mController.isCopyCapable(mAccount)) || (mMessage == null)) { return; } if (!mController.isCopyCapable(mMessage)) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } startRefileActivity(ACTIVITY_CHOOSE_FOLDER_COPY); } private void startRefileActivity(int activity) { Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.folderName); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, mAccount.getLastSelectedFolderName()); intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference); startActivityForResult(intent, activity); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) { return; } if (resultCode != RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_DIRECTORY: if (resultCode == RESULT_OK && data != null) { // obtain the filename Uri fileUri = data.getData(); if (fileUri != null) { String filePath = fileUri.getPath(); if (filePath != null) { attachmentTmpStore.writeFile(new File(filePath)); } } } break; case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: if (data == null) return; String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); String srcFolderName = data.getStringExtra(ChooseFolder.EXTRA_CUR_FOLDER); MessageReference ref = data.getParcelableExtra(ChooseFolder.EXTRA_MESSAGE); if (mMessageReference.equals(ref)) { mAccount.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: Message messageToMove = mMessage; showNextMessageOrReturn(); mController.moveMessage(mAccount, srcFolderName, messageToMove, destFolderName, null); break; case ACTIVITY_CHOOSE_FOLDER_COPY: mController.copyMessage(mAccount, srcFolderName, mMessage, destFolderName, null); break; } } break; } } private void onSendAlternate() { if (mMessage != null) { mController.sendAlternate(this, mAccount, mMessage); } } /** * Handle a right-to-left swipe as "move to next message." */ @Override protected void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) { onNext(); } /** * Handle a left-to-right swipe as "move to previous message." */ @Override protected void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) { onPrevious(); } protected void onNext() { // Reset scroll percentage when we change messages mTopView.setScrollPercentage(0); if (mNextMessage == null) { Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show(); return; } mLastDirection = NEXT; disableButtons(); if (K9.showAnimations()) { mTopView.startAnimation(outToLeftAnimation()); } displayMessage(mNextMessage); mNext.requestFocus(); } protected void onPrevious() { // Reset scroll percentage when we change messages mTopView.setScrollPercentage(0); if (mPreviousMessage == null) { Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show(); return; } mLastDirection = PREVIOUS; disableButtons(); if (K9.showAnimations()) { mTopView.startAnimation(inFromRightAnimation()); } displayMessage(mPreviousMessage); mPrevious.requestFocus(); } private void onMarkAsUnread() { if (mMessage != null) { // (Issue 3319) mController.setFlag(mAccount, mMessageReference.folderName, new String[] { mMessage.getUid() }, Flag.SEEN, false); try { mMessage.setFlag(Flag.SEEN, false); mMessageView.setHeaders(mMessage, mAccount); String subject = mMessage.getSubject(); setTitle(subject); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to unset SEEN flag on message", e); } } } private void onDownloadRemainder() { if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) { return; } mMessageView.downloadRemainderButton().setEnabled(false); mController.loadMessageForViewRemote(mAccount, mMessageReference.folderName, mMessageReference.uid, mListener); } public void onClick(View view) { switch (view.getId()) { case R.id.reply: case R.id.reply_scrolling: onReply(); break; case R.id.reply_all: onReplyAll(); break; case R.id.delete: case R.id.delete_scrolling: onDelete(); break; case R.id.forward: case R.id.forward_scrolling: onForward(); break; case R.id.archive: case R.id.archive_scrolling: onRefile(mAccount.getArchiveFolderName()); break; case R.id.spam: case R.id.spam_scrolling: onRefile(mAccount.getSpamFolderName()); break; case R.id.move: case R.id.move_scrolling: onMove(); break; case R.id.next: case R.id.next_scrolling: onNext(); break; case R.id.previous: case R.id.previous_scrolling: onPrevious(); break; case R.id.download: ((AttachmentView)view).saveFile(); break; case R.id.show_pictures: mMessageView.setLoadPictures(true); break; case R.id.download_remainder: onDownloadRemainder(); break; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete: onDelete(); break; case R.id.reply: onReply(); break; case R.id.reply_all: onReplyAll(); break; case R.id.forward: onForward(); break; case R.id.send_alternate: onSendAlternate(); break; case R.id.mark_as_unread: onMarkAsUnread(); break; case R.id.flag: onFlag(); break; case R.id.archive: onRefile(mAccount.getArchiveFolderName()); break; case R.id.spam: onRefile(mAccount.getSpamFolderName()); break; case R.id.move: onMove(); break; case R.id.copy: onCopy(); break; case R.id.show_full_header: runOnUiThread(new Runnable() { @Override public void run() { mMessageView.showAllHeaders(); } }); break; case R.id.select_text: mTopView.setScrolling(false); mMessageView.beginSelectingText(); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_view_option, menu); if (!mController.isCopyCapable(mAccount)) { menu.findItem(R.id.copy).setVisible(false); } if (!mController.isMoveCapable(mAccount)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getArchiveFolderName())) { menu.findItem(R.id.archive).setVisible(false); } if (K9.FOLDER_NONE.equalsIgnoreCase(mAccount.getSpamFolderName())) { menu.findItem(R.id.spam).setVisible(false); } return true; } // TODO: when switching to API version 8, override onCreateDialog(int, Bundle) /** * @param id The id of the dialog. * @return The dialog. If you return null, the dialog will not be created. * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(final int id) { switch (id) { case R.id.dialog_confirm_delete: return ConfirmationDialog.create(this, id, R.string.dialog_confirm_delete_title, R.string.dialog_confirm_delete_message, R.string.dialog_confirm_delete_confirm_button, R.string.dialog_confirm_delete_cancel_button, new Runnable() { @Override public void run() { delete(); } }); case R.id.dialog_confirm_spam: return ConfirmationDialog.create(this, id, R.string.dialog_confirm_spam_title, getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, 1), R.string.dialog_confirm_spam_confirm_button, R.string.dialog_confirm_spam_cancel_button, new Runnable() { @Override public void run() { refileMessage(mDstFolder); mDstFolder = null; } }); case R.id.dialog_attachment_progress: ProgressDialog d = new ProgressDialog(this); d.setIndeterminate(true); d.setTitle(R.string.dialog_attachment_progress_title); return d; } return super.onCreateDialog(id); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (menu != null) { MenuItem flagItem = menu.findItem(R.id.flag); if (flagItem != null && mMessage != null) { flagItem.setTitle((mMessage.isSet(Flag.FLAGGED) ? R.string.unflag_action : R.string.flag_action)); } MenuItem additionalHeadersItem = menu.findItem(R.id.show_full_header); if (additionalHeadersItem != null) { additionalHeadersItem.setTitle(mMessageView.additionalHeadersVisible() ? R.string.hide_full_header_action : R.string.show_full_header_action); } } return super.onPrepareOptionsMenu(menu); } public void displayMessageBody(final Account account, final String folder, final String uid, final Message message) { runOnUiThread(new Runnable() { public void run() { mTopView.scrollTo(0, 0); try { if (MessageView.this.mMessage != null && MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL) && message.isSet(Flag.X_DOWNLOADED_FULL)) { mMessageView.setHeaders(message, account); } MessageView.this.mMessage = message; mMessageView.displayMessageBody(account, folder, uid, message, mPgpData); mMessageView.renderAttachments(mMessage, 0, mMessage, mAccount, mController, mListener); } catch (MessagingException e) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "loadMessageForViewBodyAvailable", e); } } } }); } class Listener extends MessagingListener { @Override public void loadMessageForViewHeadersAvailable(final Account account, String folder, String uid, final Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } MessageView.this.mMessage = message; runOnUiThread(new Runnable() { public void run() { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { mMessageView.loadBodyFromUrl("file:///android_asset/downloading.html"); } mMessageView.setHeaders(message, account); mMessageView.setOnFlagListener(new OnClickListener() { @Override public void onClick(View v) { onFlag(); } }); } }); } @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } displayMessageBody(account, folder, uid, message); }//loadMessageForViewBodyAvailable @Override public void loadMessageForViewFailed(Account account, String folder, String uid, final Throwable t) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } mHandler.post(new Runnable() { public void run() { setProgressBarIndeterminateVisibility(false); if (t instanceof IllegalArgumentException) { mHandler.invalidIdError(); } else { mHandler.networkError(); } if ((MessageView.this.mMessage == null) || !MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { mMessageView.loadBodyFromUrl("file:///android_asset/empty.html"); } } }); } @Override public void loadMessageForViewFinished(Account account, String folder, String uid, final Message message) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } mHandler.post(new Runnable() { public void run() { setProgressBarIndeterminateVisibility(false); mMessageView.setShowDownloadButton(message); } }); } @Override public void loadMessageForViewStarted(Account account, String folder, String uid) { if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder) || !mMessageReference.accountUuid.equals(account.getUuid())) { return; } mHandler.post(new Runnable() { public void run() { setProgressBarIndeterminateVisibility(true); } }); } @Override public void loadAttachmentStarted(Account account, Message message, Part part, Object tag, final boolean requiresDownload) { if (mMessage != message) { return; } mHandler.post(new Runnable() { public void run() { mMessageView.setAttachmentsEnabled(false); showDialog(R.id.dialog_attachment_progress); if (requiresDownload) { mHandler.fetchingAttachment(); } } }); } @Override public void loadAttachmentFinished(Account account, Message message, Part part, final Object tag) { if (mMessage != message) { return; } mHandler.post(new Runnable() { public void run() { mMessageView.setAttachmentsEnabled(true); removeDialog(R.id.dialog_attachment_progress); Object[] params = (Object[]) tag; boolean download = (Boolean) params[0]; AttachmentView attachment = (AttachmentView) params[1]; if (download) { attachment.writeFile(); } else { attachment.showFile(); } } }); } @Override public void loadAttachmentFailed(Account account, Message message, Part part, Object tag, String reason) { if (mMessage != message) { return; } mHandler.post(new Runnable() { public void run() { mMessageView.setAttachmentsEnabled(true); removeDialog(R.id.dialog_attachment_progress); mHandler.networkError(); } }); } } // This REALLY should be in MessageCryptoView public void onDecryptDone(PgpData pgpData) { // TODO: this might not be enough if the orientation was changed while in APG, // sometimes shows the original encrypted content mMessageView.loadBodyFromText(mAccount.getCryptoProvider(), mPgpData, mMessage, mPgpData.getDecryptedData(), "text/plain"); } }
false
false
null
null
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/lang/CollationTest.java b/java/testing/org/apache/derbyTesting/functionTests/tests/lang/CollationTest.java index c96deef0a..f7807273e 100644 --- a/java/testing/org/apache/derbyTesting/functionTests/tests/lang/CollationTest.java +++ b/java/testing/org/apache/derbyTesting/functionTests/tests/lang/CollationTest.java @@ -1,1354 +1,1357 @@ /** * Derby - Class org.apache.derbyTesting.functionTests.tests.lang.CollationTest * * 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.derbyTesting.functionTests.tests.lang; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.text.Collator; import java.util.Locale; import javax.sql.DataSource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.derbyTesting.functionTests.tests.jdbcapi.BatchUpdateTest; import org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest; import org.apache.derbyTesting.functionTests.tests.nist.NistScripts; import org.apache.derbyTesting.junit.XML; //import org.apache.derby.iapi.types.XML; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.CleanDatabaseTestSetup; import org.apache.derbyTesting.junit.Decorator; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.JDBCDataSource; import org.apache.derbyTesting.junit.TestConfiguration; +import org.apache.derbyTesting.functionTests.util.TestUtil; public class CollationTest extends BaseJDBCTestCase { public CollationTest(String name) { super(name); } private static final String[] NAMES = { // Just Smith, Zebra, Acorn with alternate A,S and Z "Smith", "Zebra", "\u0104corn", "\u017Bebra", "Acorn", "\u015Amith", "aacorn", }; /** * Test order by with default collation * * @throws SQLException */ public void testDefaultCollation() throws SQLException { Connection conn = getConnection(); conn.setAutoCommit(false); Statement s = createStatement(); PreparedStatement ps; ResultSet rs; setUpTable(s); //The collation should be UCS_BASIC for this database checkLangBasedQuery(s, "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.database.collation')", new String[][] {{"UCS_BASIC"}}); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY NAME", new String[][] {{"4","Acorn"},{"0","Smith"},{"1","Zebra"}, {"6","aacorn"}, {"2","\u0104corn"},{"5","\u015Amith"},{"3","\u017Bebra"} }); // Order by expresssion s.executeUpdate("CREATE FUNCTION mimic(val VARCHAR(32000)) RETURNS VARCHAR(32000) EXTERNAL NAME 'org.apache.derbyTesting.functionTests.tests.lang.CollationTest.mimic' LANGUAGE JAVA PARAMETER STYLE JAVA"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY MIMIC(NAME)", new String[][] {{"4","Acorn"},{"0","Smith"},{"1","Zebra"}, {"6","aacorn"}, {"2","\u0104corn"},{"5","\u015Amith"},{"3","\u017Bebra"} }); s.executeUpdate("DROP FUNCTION mimic"); //COMPARISONS INVOLVING CONSTANTS //In default JVM territory, 'aacorn' is != 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' = 'Acorn' ", null); //In default JVM territory, 'aacorn' is not < 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' < 'Acorn' ", null); //COMPARISONS INVOLVING CONSTANT and PERSISTENT COLUMN checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME <= 'Smith' ", new String[][] {{"0","Smith"}, {"4","Acorn"} }); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME between 'Acorn' and 'Zebra' ", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"4","Acorn"} }); //After index creation, the query above will return same data but in //different order /*s.executeUpdate("CREATE INDEX CUSTOMER_INDEX1 ON CUSTOMER(NAME)"); s.executeUpdate("INSERT INTO CUSTOMER VALUES (NULL, NULL)"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME between 'Acorn' and " + " 'Zebra' ORDER BY NAME", new String[][] {{"4","Acorn"}, {"0","Smith"}, {"1","Zebra"} }); */ //For non-collated databases, COMPARISONS OF USER PERSISTENT CHARACTER //COLUMN AND CHARACTER CONSTANT WILL not FAIL IN SYSTEM SCHEMA. s.executeUpdate("set schema SYS"); checkLangBasedQuery(s, "SELECT ID, NAME FROM APP.CUSTOMER WHERE NAME <= 'Smith' ", new String[][] {{"0","Smith"}, {"4","Acorn"} }); s.executeUpdate("set schema APP"); //Following sql will not fail in a database which uses UCS_BASIC for //user schemas. Since the collation of user schemas match that of system //schema, the following comparison will not fail. It will fail in a //database with territory based collation for user schemas. checkLangBasedQuery(s, "SELECT 1 FROM SYS.SYSTABLES WHERE " + " TABLENAME = 'CUSTOMER' ", new String[][] {{"1"} }); //Using cast for persistent character column from system table in the //query above won't affect the above sql in any ways. checkLangBasedQuery(s, "SELECT 1 FROM SYS.SYSTABLES WHERE CAST " + " (TABLENAME AS CHAR(15)) = 'CUSTOMER' ", new String[][] {{"1"} }); //Do some testing using CASE WHEN THEN ELSE //following will work with no problem for a database with UCS_BASIC //collation for system and user schemas checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE CASE " + " WHEN 1=1 THEN TABLENAME ELSE 'c' END = 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Using cast for result of CASE expression in the query above would not //affect the sql in any ways. checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE CAST " + " ((CASE WHEN 1=1 THEN TABLENAME ELSE 'c' END) AS CHAR(12)) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Do some testing using CONCATENATION //following will work with no problem for a database with UCS_BASIC //collation for system and user schemas checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TABLENAME || ' ' = 'SYSCOLUMNS '", new String[][] {{"SYSCOLUMNS"} }); //Using cast for result of CAST expression in the query above would not //affect the sql in any ways. checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST (TABLENAME || ' ' AS CHAR(12)) = " + " 'SYSCOLUMNS '", new String[][] {{"SYSCOLUMNS"} }); //Do some testing using COALESCE //following will work with no problem for a database with UCS_BASIC //collation for system and user schemas checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " COALESCE(TABLENAME, 'c') = 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Using cast for result of COALESCE expression in the query above would not //affect the sql in any ways. checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST (COALESCE (TABLENAME, 'c') AS CHAR(12)) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Do some testing using NULLIF //following will work with no problem for a database with UCS_BASIC //collation for system and user schemas checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " NULLIF(TABLENAME, 'c') = 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Using cast for result of NULLIF expression in the query above would not //affect the sql in any ways. checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST (NULLIF (TABLENAME, 'c') AS CHAR(12)) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Test USER/CURRENT_USER/SESSION_USER checkLangBasedQuery(s, "SELECT count(*) FROM CUSTOMER WHERE "+ "CURRENT_USER = 'APP'", new String[][] {{"7"}}); //Do some testing with MAX/MIN operators checkLangBasedQuery(s, "SELECT MAX(NAME) maxName FROM CUSTOMER ORDER BY maxName ", new String[][] {{"\u017Bebra"}}); checkLangBasedQuery(s, "SELECT MIN(NAME) minName FROM CUSTOMER ORDER BY minName ", new String[][] {{"Acorn"}}); //Do some testing with CHAR/VARCHAR functions s.executeUpdate("set schema SYS"); checkLangBasedQuery(s, "SELECT CHAR(ID) FROM APP.CUSTOMER WHERE " + " CHAR(ID)='0'", new String[] [] {{"0"}}); s.executeUpdate("set schema APP"); if (XML.classpathMeetsXMLReqs()) checkLangBasedQuery(s, "SELECT XMLSERIALIZE(x as CHAR(10)) " + " FROM xmlTable, SYS.SYSTABLES WHERE " + " XMLSERIALIZE(x as CHAR(10)) = TABLENAME", null); //Start of parameter testing //Start with simple ? param in a string comparison //Since all schemas (ie user and system) have the same collation, the //following test won't fail. s.executeUpdate("set schema APP"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " ? = TABLENAME"); ps.setString(1, "SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Since all schemas (ie user and system) have the same collation, the //following test won't fail. ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " SUBSTR(?,2) = TABLENAME"); ps.setString(1, " SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Since all schemas (ie user and system) have the same collation, the //following test won't fail. ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " LTRIM(?) = TABLENAME"); ps.setString(1, " SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " RTRIM(?) = TABLENAME"); ps.setString(1, "SYSCOLUMNS "); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Since all schemas (ie user and system) have the same collation, the //following test won't fail. ps = prepareStatement("SELECT COUNT(*) FROM CUSTOMER WHERE " + " ? IN (SELECT TABLENAME FROM SYS.SYSTABLES)"); ps.setString(1, "SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"7"}}); //End of parameter testing s.close(); compareAgrave(1,1); } public void testFrenchCollation() throws SQLException { compareAgrave(2,1); } /** * For a TERRITORY_BASED collation french database, differences between pre-composed accents such * as "\u00C0" (A-grave) and combining accents such as "A\u0300" (A, combining-grave) should match * for = and like. But they do not match for UCS_BASIC. We insert both into a table and search * based on equal and like. * * @param expectedMatchCountForEqual number of rows we expect back for =. * 2 for French, 1 for English * @param expectedMatchCountForLike number of rows we expect back for LIKE. * 1 for French and English * @throws SQLException */ private void compareAgrave(int expectedMatchCountForEqual, int expectedMatchCountForLike) throws SQLException { String agrave = "\u00C0"; String agraveCombined ="A\u0300"; Statement s = createStatement(); try { s.executeUpdate("DROP TABLE T"); }catch (SQLException se) {} s.executeUpdate("CREATE TABLE T (vc varchar(30))"); PreparedStatement ps = prepareStatement("INSERT INTO T VALUES (?)"); ps.setString(1,agrave); ps.executeUpdate(); ps.setString(1,agraveCombined); ps.executeUpdate(); ps = prepareStatement("SELECT COUNT(*) FROM T WHERE VC = ?"); ps.setString(1, agrave); ResultSet rs = ps.executeQuery(); JDBC.assertSingleValueResultSet(rs, Integer.toString(expectedMatchCountForEqual)); ps = prepareStatement("SELECT COUNT(*) FROM T WHERE VC LIKE ?"); ps.setString(1, agrave); rs = ps.executeQuery(); JDBC.assertSingleValueResultSet(rs, Integer.toString(expectedMatchCountForLike)); } /** * Test order by with polish collation * @throws SQLException */ public void testPolishCollation() throws SQLException { getConnection().setAutoCommit(false); Statement s = createStatement(); setUpTable(s); //The collation should be TERRITORY_BASED for this database checkLangBasedQuery(s, "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.database.collation')", new String[][] {{"TERRITORY_BASED"}}); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY NAME", new String[][] {{"6","aacorn"}, {"4","Acorn"}, {"2","\u0104corn"}, {"0","Smith"},{"5","\u015Amith"}, {"1","Zebra"},{"3","\u017Bebra"} }); // Order by expresssion s.executeUpdate("CREATE FUNCTION mimic(val VARCHAR(32000)) RETURNS VARCHAR(32000) EXTERNAL NAME 'org.apache.derbyTesting.functionTests.tests.lang.CollationTest.mimic' LANGUAGE JAVA PARAMETER STYLE JAVA"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY MIMIC(NAME)", new String[][] {{"6","aacorn"}, {"4","Acorn"}, {"2","\u0104corn"}, {"0","Smith"},{"5","\u015Amith"}, {"1","Zebra"},{"3","\u017Bebra"} }); s.executeUpdate("DROP FUNCTION mimic"); //COMPARISONS INVOLVING CONSTANTS //In Polish, 'aacorn' is != 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' = 'Acorn' ", null); //In Polish, 'aacorn' is < 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' < 'Acorn'", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"2","\u0104corn"}, {"3","\u017Bebra"}, {"4","Acorn"}, {"5","\u015Amith"}, {"6","aacorn"} }); //COMPARISONS INVOLVING CONSTANT and PERSISTENT COLUMN checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME <= 'Smith' ", new String[][] {{"0","Smith"}, {"2","\u0104corn"}, {"4","Acorn"}, {"6","aacorn"} }); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME between 'Acorn' and 'Zebra' ", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"2","\u0104corn"}, {"4","Acorn"}, {"5","\u015Amith"} }); //After index creation, the query above will return same data but in //different order /*s.executeUpdate("CREATE INDEX CUSTOMER_INDEX1 ON CUSTOMER(NAME)"); s.executeUpdate("INSERT INTO CUSTOMER VALUES (NULL, NULL)"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER -- derby-properties index=customer_index1 \r WHERE NAME between 'Acorn' and " + " 'Zebra'", //ORDER BY NAME", new String[][] {{"4","Acorn"}, {"2","\u0104corn"}, {"0","Smith"}, {"5","\u015Amith"}, {"1","Zebra"} }); */ //For collated databases, COMPARISONS OF USER PERSISTENT CHARACTER //COLUMN AND CHARACTER CONSTANT WILL FAIL IN SYSTEM SCHEMA. s.executeUpdate("set schema SYS"); assertStatementError("42818", s, "SELECT ID, NAME FROM APP.CUSTOMER WHERE NAME <= 'Smith' "); //Do some testing with MAX/MIN operators s.executeUpdate("set schema APP"); checkLangBasedQuery(s, "SELECT MAX(NAME) maxName FROM CUSTOMER ORDER BY maxName ", new String[][] {{"\u017Bebra"}}); checkLangBasedQuery(s, "SELECT MIN(NAME) minName FROM CUSTOMER ORDER BY minName ", new String[][] {{"aacorn"}}); commonTestingForTerritoryBasedDB(s); } /** * Test order by with Norwegian collation * * @throws SQLException */ public void testNorwayCollation() throws SQLException { getConnection().setAutoCommit(false); Statement s = createStatement(); setUpTable(s); //The collation should be TERRITORY_BASED for this database checkLangBasedQuery(s, "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.database.collation')", new String[][] {{"TERRITORY_BASED"}}); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY NAME", new String[][] {{"4","Acorn"}, {"2","\u0104corn"},{"0","Smith"}, {"5","\u015Amith"}, {"1","Zebra"},{"3","\u017Bebra"}, {"6","aacorn"} }); // Order by expresssion s.executeUpdate("CREATE FUNCTION mimic(val VARCHAR(32000)) RETURNS VARCHAR(32000) EXTERNAL NAME 'org.apache.derbyTesting.functionTests.tests.lang.CollationTest.mimic' LANGUAGE JAVA PARAMETER STYLE JAVA"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY MIMIC(NAME)", new String[][] {{"4","Acorn"}, {"2","\u0104corn"},{"0","Smith"}, {"5","\u015Amith"}, {"1","Zebra"},{"3","\u017Bebra"}, {"6","aacorn"} }); s.executeUpdate("DROP FUNCTION mimic"); //COMPARISONS INVOLVING CONSTANTS //In Norway, 'aacorn' is != 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' = 'Acorn' ", null); //In Norway, 'aacorn' is not < 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' < 'Acorn' ", null); //COMPARISONS INVOLVING CONSTANT and PERSISTENT COLUMN checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME <= 'Smith' ", new String[][] {{"0","Smith"}, {"2","\u0104corn"}, {"4","Acorn"} }); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME between 'Acorn' and 'Zebra' ", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"2","\u0104corn"}, {"4","Acorn"}, {"5","\u015Amith"} }); //After index creation, the query above will return same data but in //different order /*s.executeUpdate("CREATE INDEX CUSTOMER_INDEX1 ON CUSTOMER(NAME)"); s.executeUpdate("INSERT INTO CUSTOMER VALUES (NULL, NULL)"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER -- derby-properties index=customer_index1 \r WHERE NAME between 'Acorn' and " + " 'Zebra'", //ORDER BY NAME", new String[][] {{"4","Acorn"}, {"2","\u0104corn"}, {"0","Smith"}, {"5","\u015Amith"}, {"1","Zebra"} }); */ //For collated databases, COMPARISONS OF USER PERSISTENT CHARACTER //COLUMN AND CHARACTER CONSTANT WILL FAIL IN SYSTEM SCHEMA. s.executeUpdate("set schema SYS"); assertStatementError("42818", s, "SELECT ID, NAME FROM APP.CUSTOMER WHERE NAME <= 'Smith' "); //Do some testing with MAX/MIN operators s.executeUpdate("set schema APP"); checkLangBasedQuery(s, "SELECT MAX(NAME) maxName FROM CUSTOMER ORDER BY maxName ", new String[][] {{"aacorn"}}); checkLangBasedQuery(s, "SELECT MIN(NAME) minName FROM CUSTOMER ORDER BY minName ", new String[][] {{"Acorn"}}); commonTestingForTerritoryBasedDB(s); s.close(); } /** * Test order by with English collation * * @throws SQLException */ public void testEnglishCollation() throws SQLException { getConnection().setAutoCommit(false); Statement s = createStatement(); setUpTable(s); //The collation should be TERRITORY_BASED for this database checkLangBasedQuery(s, "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.database.collation')", new String[][] {{"TERRITORY_BASED"}}); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER ORDER BY NAME", new String[][] {{"6","aacorn"},{"4","Acorn"},{"2","\u0104corn"},{"0","Smith"}, {"5","\u015Amith"},{"1","Zebra"},{"3","\u017Bebra"} }); //COMPARISONS INVOLVING CONSTANTS //In English, 'aacorn' != 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' = 'Acorn' ", null); //In English, 'aacorn' is < 'Acorn' checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER where 'aacorn' < 'Acorn'", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"2","\u0104corn"}, {"3","\u017Bebra"}, {"4","Acorn"}, {"5","\u015Amith"}, {"6","aacorn"} }); //COMPARISONS INVOLVING CONSTANT and PERSISTENT COLUMN checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME <= 'Smith' ", new String[][] {{"0","Smith"}, {"2","\u0104corn"}, {"4","Acorn"}, {"6","aacorn"} }); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER WHERE NAME between 'Acorn' and 'Zebra' ", new String[][] {{"0","Smith"}, {"1","Zebra"}, {"2","\u0104corn"}, {"4","Acorn"}, {"5","\u015Amith"} }); //After index creation, the query above will return same data but in //different order /*s.executeUpdate("CREATE INDEX CUSTOMER_INDEX1 ON CUSTOMER(NAME)"); s.executeUpdate("INSERT INTO CUSTOMER VALUES (NULL, NULL)"); checkLangBasedQuery(s, "SELECT ID, NAME FROM CUSTOMER -- derby-properties index=customer_index1 \r WHERE NAME between 'Acorn' and " + " 'Zebra'", //ORDER BY NAME", new String[][] {{"4","Acorn"}, {"2","\u0104corn"}, {"0","Smith"}, {"5","\u015Amith"}, {"1","Zebra"} }); */ //For collated databases, COMPARISONS OF USER PERSISTENT CHARACTER //COLUMN AND CHARACTER CONSTANT WILL FAIL IN SYSTEM SCHEMA. s.executeUpdate("set schema SYS"); assertStatementError("42818", s, "SELECT ID, NAME FROM APP.CUSTOMER WHERE NAME <= 'Smith' "); //Do some testing with MAX/MIN operators s.executeUpdate("set schema APP"); checkLangBasedQuery(s, "SELECT MAX(NAME) maxName FROM CUSTOMER ORDER BY maxName ", new String[][] {{"\u017Bebra"}}); checkLangBasedQuery(s, "SELECT MIN(NAME) minName FROM CUSTOMER ORDER BY minName ", new String[][] {{"aacorn"}}); commonTestingForTerritoryBasedDB(s); s.close(); } private void commonTestingForTerritoryBasedDB(Statement s) throws SQLException{ PreparedStatement ps; ResultSet rs; Connection conn = s.getConnection(); s.executeUpdate("set schema APP"); //Following sql will fail because the compilation schema is user schema //and hence the character constant "CUSTOMER" will pickup the collation //of user schema, which is territory based for this database. But the //persistent character columns from sys schema, which is TABLENAME in //following query will have the UCS_BASIC collation. Since the 2 //collation types don't match, the following comparison will fail assertStatementError("42818", s, "SELECT 1 FROM SYS.SYSTABLES WHERE " + " TABLENAME = 'CUSTOMER' "); //To get around the problem in the query above, use cast for persistent //character column from system table and then compare it against a //character constant. Do this when the compilation schema is a user //schema and not system schema. This will ensure that the result //of the casting will pick up the collation of the user schema. And //constant character string will also pick up the collation of user //schema and hence the comparison between the 2 will not fail checkLangBasedQuery(s, "SELECT 1 FROM SYS.SYSTABLES WHERE CAST " + " (TABLENAME AS CHAR(15)) = 'CUSTOMER' ", new String[][] {{"1"} }); //Do some testing using CASE WHEN THEN ELSE //following sql will not work for a database with territory based //collation for user schemas. This is because the resultant string type //from the CASE expression below will have collation derivation of NONE. //The reason for collation derivation of NONE is that the CASE's 2 //operands have different collation types and as per SQL standards, if an //aggregate method has operands with different collations, then the //result will have collation derivation of NONE. The right side of = //operation has collation type of territory based and hence the following //sql fails. DERBY-2678 This query should not fail because even though //left hand side of = has collation derivation of NONE, the right hand //side has collation derivation of IMPLICIT, and so we should just pick the //collation of the rhs as per SQL standard. Once DERBY-2678 is fixed, we //don't need to use the CAST on this query to make it work (we are doing //that in the next test). assertStatementError("42818", s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE CASE " + " WHEN 1=1 THEN TABLENAME ELSE 'c' END = 'SYSCOLUMNS'"); //CASTing the result of the CASE expression will solve the problem in the //query above. Now both the operands around = operation will have //collation type of territory based and hence the sql won't fail checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE CAST " + " ((CASE WHEN 1=1 THEN TABLENAME ELSE 'c' END) AS CHAR(12)) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Another test for CASE WHEN THEN ELSE DERBY-2776 //The data type for THEN is not same as the data type for ELSE. //THEN is of type CHAR and ELSE is of type VARCHAR. VARCHAR has higher //precedence hence the type associated with the return type of CASE will //be VARCHAR. Also, since the collation type of THEN and ELSE match, //which is TERRITORY BASED, the return type of CASE will have the collation //of TERRITORY BASED. This collation is same as the rhs of the = operation //and hence following sql will pass. checkLangBasedQuery(s, "SELECT count(*) FROM CUSTOMER WHERE CASE WHEN " + " 1=1 THEN NAMECHAR ELSE NAME END = NAMECHAR", new String[][] {{"7"} }); //The query below will work for the same reason. checkLangBasedQuery(s, "SELECT count(*) FROM SYS.SYSTABLES WHERE CASE " + " WHEN 1=1 THEN TABLENAME ELSE TABLEID END = TABLENAME", new String[][] {{"23"} }); //Do some testing using CONCATENATION //following will fail because result string of concatenation has //collation derivation of NONE. That is because it's 2 operands have //different collation types. TABLENAME has collation type of UCS_BASIC //but constant character string ' ' has collation type of territory based //So the left hand side of = operator has collation derivation of NONE //and right hand side has collation derivation of territory based and //that causes the = comparison to fail. DERBY-2678 This query should not //fail because even though left hand side of = has collation derivation of //NONE, the right hand side has collation derivation of IMPLICIT, and so we //should just pick the collation of the rhs as per SQL standard. Once //DERBY-2678 is fixed, we don't need to use the CAST on this query to make //it work (we are doing that in the next test). assertStatementError("42818", s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TABLENAME || ' ' = 'SYSCOLUMNS '"); //CASTing the result of the concat expression will solve the problem in //the query above. Now both the operands around = operation will have //collation type of territory based and hence the sql won't fail checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST (TABLENAME || ' ' AS CHAR(12)) = " + " 'SYSCOLUMNS '", new String[][] {{"SYSCOLUMNS"} }); //Following will fail because both sides of the = operator have collation //derivation of NONE. DERBY-2725 assertStatementError("42818", s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TABLENAME || ' ' = TABLENAME || 'SYSCOLUMNS '"); //Do some testing using COALESCE //following will fail because result string of COALESCE has //collation derivation of NONE. That is because it's 2 operands have //different collation types. TABLENAME has collation type of UCS_BASIC //but constant character string 'c' has collation type of territory based //So the left hand side of = operator has collation derivation of NONE //and right hand side has collation derivation of territory based and //that causes the = comparison to fail. DERBY-2678 This query should not //fail because even though left hand side of = has collation derivation of //NONE, the right hand side has collation derivation of IMPLICIT, and so we //should just pick the collation of the rhs as per SQL standard. Once //DERBY-2678 is fixed, we don't need to use the CAST on this query to make //it work (we are doing that in the next test). assertStatementError("42818", s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " COALESCE(TABLENAME, 'c') = 'SYSCOLUMNS'"); //CASTing the result of the COALESCE expression will solve the problem in //the query above. Now both the operands around = operation will have //collation type of territory based and hence the sql won't fail checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST (COALESCE (TABLENAME, 'c') AS CHAR(12)) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Do some testing using NULLIF //following will fail because result string of NULLIF has //collation derivation of NONE. That is because it's 2 operands have //different collation types. TABLENAME has collation type of UCS_BASIC //but constant character string 'c' has collation type of territory based //So the left hand side of = operator has collation derivation of NONE //and right hand side has collation derivation of territory based and //that causes the = comparison to fail. DERBY-2678 This query should not //fail because even though left hand side of = has collation derivation of //NONE, the right hand side has collation derivation of IMPLICIT, and so //we should just pick the collation of the rhs as per SQL standard. Once //DERBY-2678 is fixed, we don't need to use the CAST on this query to make //it work (we are doing that in the next test). assertStatementError("42818", s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " NULLIF(TABLENAME, 'c') = 'SYSCOLUMNS'"); //CASTing the result of the NULLIF expression will solve the problem in //the query above. Now both the operands around = operation will have //collation type of territory based and hence the sql won't fail checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " NULLIF (CAST (TABLENAME AS CHAR(12)), 'c' ) = " + " 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Do some testing with CHAR/VARCHAR functions s.executeUpdate("set schema SYS"); //Following will work because both operands are = have the collation type //of UCS_BASIC checkLangBasedQuery(s, "SELECT CHAR(ID) FROM APP.CUSTOMER WHERE " + " CHAR(ID)='0'", new String[] [] {{"0"}}); //Derby does not allow VARCHAR function on numeric columns and hence //this VARCHAR test looks little different than the CHAR test above. checkLangBasedQuery(s, "SELECT ID FROM APP.CUSTOMER WHERE " + " VARCHAR(NAME)='Smith'", new String[] [] {{"0"}}); //Now try a negative test s.executeUpdate("set schema APP"); //following will fail because CHAR(TABLENAME)= TABLENAME is causing compare //between 2 character string types with different collation types. The lhs //operand has collation of territory based but rhs operand has collation of //UCS_BASIC assertStatementError("42818", s, "SELECT CHAR(TABLENAME) FROM " + " SYS.SYSTABLES WHERE CHAR(TABLENAME)= TABLENAME AND " + " VARCHAR(TABLENAME) = 'SYSCOLUMNS'"); //To resolve the problem above, we need to use CAST around TABLENAME checkLangBasedQuery(s, "SELECT CHAR(TABLENAME) FROM SYS.SYSTABLES WHERE " + " CHAR(TABLENAME)= (CAST (TABLENAME AS CHAR(12))) AND " + " VARCHAR(TABLENAME) = 'SYSCOLUMNS'", new String[][] {{"SYSCOLUMNS"} }); //Test USER/CURRENT_USER/SESSION_USER/CURRENT SCHMEA/ CURRENT ISOLATION //following will fail because we are trying to compare UCS_BASIC //(CURRENT_USER) with territory based ("APP" taking it's collation from //compilation schema which is user schema at this time). assertStatementError("42818", s, "SELECT count(*) FROM CUSTOMER WHERE "+ "CURRENT_USER = 'APP'"); //The problem above can be fixed by CASTing CURRENT_USER so that the //collation type will be picked up from compilation schema which is user //schema at this point. checkLangBasedQuery(s, "SELECT count(*) FROM CUSTOMER WHERE "+ "CAST(CURRENT_USER AS CHAR(12)) = 'APP'", new String[][] {{"7"}}); //following comparison will not cause compilation error because both the //operands around = have collation type of UCS_BASIC checkLangBasedQuery(s, "SELECT count(*) FROM CUSTOMER WHERE "+ "SESSION_USER = USER", new String[][] {{"7"}}); //following will fail because we are trying to compare UCS_BASIC //(CURRENT ISOLATION) with territory based ("CS" taking it's collation from //compilation schema which is user schema at this time). assertStatementError("42818", s, "SELECT count(*) FROM CUSTOMER WHERE "+ "CURRENT ISOLATION = 'CS'"); //Following will not give compilation error because both sides in = have //the same collation type checkLangBasedQuery(s, "SELECT count(*) FROM CUSTOMER WHERE "+ "CAST(CURRENT ISOLATION AS CHAR(12)) = 'CS'", new String[][] {{"7"}}); //Following will not cause compilation error because both the operands //around the = have collation type of UCS_BASIC. We are in the SYS //schema and hence character string constant 'APP' has picked the collation //type of SYS schema which is UCS_BASIC s.executeUpdate("set schema SYS"); checkLangBasedQuery(s, "SELECT count(*) FROM APP.CUSTOMER WHERE "+ "CURRENT SCHEMA = 'SYS'", new String[][] {{"7"}}); s.executeUpdate("set schema APP"); if (XML.classpathMeetsXMLReqs()) { assertStatementError("42818", s, "SELECT XMLSERIALIZE(x as CHAR(10)) " + " FROM xmlTable, SYS.SYSTABLES WHERE " + " XMLSERIALIZE(x as CHAR(10)) = TABLENAME"); checkLangBasedQuery(s, "SELECT XMLSERIALIZE(x as CHAR(10)) FROM " + " xmlTable, SYS.SYSTABLES WHERE XMLSERIALIZE(x as CHAR(10)) = " + " CAST(TABLENAME AS CHAR(10))", null); //Do some parameter testing for XMLSERIALIZE. ? is not supported inside //the XMLSERIALIZE function and hence following will result in errors. assertCompileError("42Z70", "SELECT XMLSERIALIZE(x as CHAR(10)) " + " FROM xmlTable, SYS.SYSTABLES WHERE " + " XMLSERIALIZE(? as CHAR(10)) = TABLENAME"); assertCompileError("42Z70", "SELECT XMLSERIALIZE(x as CHAR(10)) FROM " + " xmlTable, SYS.SYSTABLES WHERE XMLSERIALIZE(? as CHAR(10)) = " + " CAST(TABLENAME AS CHAR(10))"); } //Start of user defined function testing //At this point, just create a function which involves character strings //in it's definition. In subsequent checkin, there will be collation //related testing using this function's return value s.executeUpdate("set schema APP"); s.executeUpdate("CREATE FUNCTION CONCAT_NOCALL(VARCHAR(10), VARCHAR(10)) "+ " RETURNS VARCHAR(20) RETURNS NULL ON NULL INPUT EXTERNAL NAME " + "'org.apache.derbyTesting.functionTests.tests.lang.RoutineTest.concat' "+ " LANGUAGE JAVA PARAMETER STYLE JAVA"); //DERBY-2831 Creating a function inside a non-existent schema should not //fail when it's return type is of character string type. Following is a //simple test case copied from DERBY-2831 s.executeUpdate("CREATE FUNCTION AA.B() RETURNS VARCHAR(10) NO SQL " + "PARAMETER STYLE JAVA LANGUAGE JAVA EXTERNAL NAME 'aaa.bbb.ccc' "); //following fails as expected because aaa.bbb.ccc doesn't exist assertStatementError("XJ001", s, "SELECT AA.B() FROM CUSTOMER "); //Start of parameter testing //Start with simple ? param in a string comparison //Following will work fine because ? is supposed to take it's collation //from the context which in this case is from TABLENAME and TABLENAME //has collation type of UCS_BASIC s.executeUpdate("set schema APP"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " ? = TABLENAME"); ps.setString(1, "SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Do parameter testing with SUBSTR //Won't work in territory based database because in //SUBSTR(?, int) = TABLENAME //? will get the collation of the current schema which is a user //schema and hence the collation type of result of SUBSTR will also be //territory based since the result of SUBSTR always picks up the //collation of it's first operand. So the comparison between left hand //side with terriotry based and right hand side with UCS_BASIC will fail. assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " SUBSTR(?,2) = TABLENAME"); //To fix the problem above, we need to CAST TABLENAME so that the result //of CAST will pick up the collation of the current schema and this will //cause both the operands of SUBSTR(?,2) = CAST(TABLENAME AS CHAR(10)) //to have same collation ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " SUBSTR(?,2) = CAST(TABLENAME AS CHAR(10))"); ps.setString(1, "aSYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Do parameter testing with CONCATENATION operator //Following will fail because the result of concatenation will have //collation type of UCS_BASIC whereas the right hand side of = operator //will have collation type current schema which is territory based. //The reason CONCAT will have collation type of UCS_BASIC is because ? will //take collation from context which here will be TABLENAME and hence the //result of concatenation will have collation type of it's 2 operands, //namely UCS_BASIC assertCompileError("42ZA2", "SELECT TABLENAME FROM SYS.SYSTABLES " + " WHERE TABLENAME || ? LIKE 'SYSCOLUMNS '"); //The query above can be made to work if we are in SYS schema or if we use //CAST while we are trying to run the query is user schema //Let's try CAST first ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST((TABLENAME || ?) AS CHAR(20)) LIKE 'SYSCOLUMNS'"); //try switching to SYS schema and then run the original query without CAST s.executeUpdate("set schema SYS"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES " + " WHERE TABLENAME || ? LIKE 'SYSCOLUMNS'"); s.executeUpdate("set schema APP"); //The following will fail because the left hand side of LIKE has collation //derivation of NONE where as the right hand side has collation derivation //of IMPLICIT assertStatementError("42ZA2", s, "SELECT TABLENAME FROM SYS.SYSTABLES " + " WHERE TABLENAME || 'AA' LIKE 'SYSCOLUMNS '"); //To fix the problem, we can use CAST on the left hand side so it's //collation will be picked up from the compilation schema which is same as //what happens for the right hand operand. checkLangBasedQuery(s, "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST ((TABLENAME || 'AA') AS CHAR(12)) LIKE 'SYSCOLUMNS '", null ); //Do parameter testing for IS NULL //Following query will pass because it doesn't matter what the collation of //? is when doing a NULL check ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " ? IS NULL"); ps.setString(1, " "); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Now do the testing for IS NOT NULL ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " ? IS NOT NULL"); ps.setNull(1, java.sql.Types.VARCHAR); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Do parameter testing for LENGTH //Following query will fail because LENGTH operator is not allowed to take //a parameter. I just wanted to have a test case out for the changes that //are going into engine code (ie LengthOperatorNode) assertCompileError("42X36", "SELECT COUNT(*) FROM CUSTOMER WHERE " + " LENGTH(?) != 0"); //Do parameter testing for BETWEEN //Following should pass for ? will take the collation from the context and //hence, it will be UCS_BASIC ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TABLENAME NOT BETWEEN ? AND TABLENAME"); ps.setString(1, " "); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Following will fail because ? will take collation of territory based but //the left hand side has collation of UCS_BASIC assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TABLENAME NOT BETWEEN ? AND 'SYSCOLUMNS'"); //Do parameter testing with COALESCE //following will pass because the ? inside the COALESCE will take the //collation type of the other operand which is TABLENAME. The result of //COALESCE will have collation type of UCS_BASIC and that is the same //collation that the ? on rhs of = will get. ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " COALESCE(TABLENAME, ?) = ?"); ps.setString(1, " "); ps.setString(2, "SYSCOLUMNS "); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Do parameter testing with LTRIM //Won't work in territory based database because in //LTRIM(?) = TABLENAME //? will get the collation of the current schema which is a user //schema and hence the collation type of result of LTRIM will also be //territory based since the result of LTRIM always picks up the //collation of it's operand. So the comparison between left hand //side with terriotry based and right hand side with UCS_BASIC will fail. assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " LTRIM(?) = TABLENAME"); //To fix the problem above, we need to CAST TABLENAME so that the result //of CAST will pick up the collation of the current schema and this will //cause both the operands of LTRIM(?) = CAST(TABLENAME AS CHAR(10)) //to have same collation ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " LTRIM(?) = CAST(TABLENAME AS CHAR(10))"); ps.setString(1, " SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Similar testing for RTRIM assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " RTRIM(?) = TABLENAME"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " RTRIM(?) = CAST(TABLENAME AS CHAR(10))"); ps.setString(1, "SYSCOLUMNS "); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Similar testing for TRIM //Following won't work because the character string constant 'a' is //picking up the collation of the current schema which is territory based. //And the ? in TRIM will pick up it's collation from 'a' and hence the //comparison between territory based character string returned from TRIM //function will fail against UCS_BASIC based TABLENAME on the right assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TRIM('a' FROM ?) = TABLENAME"); //The problem can be fixed by using CAST on TABLENAME so the resultant of //CAST string will compare fine with the output of TRIM. Note CAST always //picks up the collation of the compilation schema. ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TRIM('a' FROM ?) = CAST(TABLENAME AS CHAR(10))"); ps.setString(1, "aSYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Another test for TRIM //Following will not fail because the ? in TRIM will pick up collation //from it's first parameter which is a SUBSTR on TABLENAME and hence the //result of TRIM will have UCS_BASIC collation which matches the collation //on the right. ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " TRIM(LEADING SUBSTR(TABLENAME, LENGTH(TABLENAME)) FROM ?) = TABLENAME"); ps.setString(1, "SYSCOLUMNS"); rs = ps.executeQuery(); //No rows returned because the result of TRIM is going to be 'YSCOLUMNS' JDBC.assertEmpty(rs); //Do parameter testing for LOCATE //Following will fail because 'LOOKFORME' has collation of territory based //but TABLENAME has collation of UCS_BASIC and hence LOCATE will fail //because the collation types of it's two operands do not match ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " LOCATE(?, TABLENAME) != 0"); ps.setString(1, "ABC"); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Just switch the parameter position and try the sql again ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " LOCATE(TABLENAME, ?) != 0"); ps.setString(1, "ABC"); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Do parameter testing with IN and subquery //Following will work just fine because ? will take it's collation from the //context which in this case will be collation of TABLENAME which has //collation type of UCS_BASIC. ps = prepareStatement("SELECT COUNT(*) FROM CUSTOMER WHERE ? IN " + " (SELECT TABLENAME FROM SYS.SYSTABLES)"); ps.setString(1, "SYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"7"}}); //Testing for NOT IN. Following won't work becuase ? is taking the //collation type from context which will be from the character string //literal 'SYSCOLUMNS'. That literal will have the collation type of the //current schema which is the user schema and hence it's collation type //will be territory based. But that collation does not match the left hand //side on IN clause and hence it results in compliation error. assertCompileError("42818", "SELECT TABLENAME FROM SYS.SYSTABLES " + " WHERE TABLENAME NOT IN (?, ' SYSCOLUMNS ') AND " + " CAST(TABLENAME AS CHAR(10)) = 'SYSCOLUMNS' "); //We can make the query work in 2 ways //1)Be in the SYS schema and then ? will take the collation of UCS_BASIC //because that is what the character string literal ' SYSCOLUMNS ' has. s.executeUpdate("set schema SYS"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES " + " WHERE TABLENAME NOT IN (?, ' SYSCOLUMNS ') AND " + " CAST(TABLENAME AS CHAR(10)) = 'SYSCOLUMNS' "); ps.setString(1, "aSYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //2)The other way to fix the query would be to do a CAST on TABLENAME so //it will have the collation of current schema which is APP s.executeUpdate("set schema APP"); ps = prepareStatement("SELECT TABLENAME FROM SYS.SYSTABLES WHERE " + " CAST(TABLENAME AS CHAR(10)) NOT IN (?, ' SYSCOLUMNS ') AND " + " CAST(TABLENAME AS CHAR(10)) = 'SYSCOLUMNS' "); ps.setString(1, "aSYSCOLUMNS"); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"SYSCOLUMNS"}}); //Following will not fail because collation of ? here does not matter //since we are not doing a collation related method s.executeUpdate("set schema SYS"); ps = prepareStatement("INSERT INTO APP.CUSTOMER(NAME) VALUES(?)"); ps.setString(1, "SYSCOLUMNS"); ps.executeUpdate(); ps.close(); s.executeUpdate("INSERT INTO APP.CUSTOMER(NAME) VALUES('abc')"); rs = s.executeQuery("SELECT COUNT(*) FROM APP.CUSTOMER "); JDBC.assertFullResultSet(rs,new String[][] {{"9"}}); //following will fail because NAME has collation type of territory based //but 'abc' has collation type of UCS_BASIC assertStatementError("42818", s, "DELETE FROM APP.CUSTOMER WHERE NAME = 'abc'"); //changing to APP schema will fix the problem s.executeUpdate("set schema APP"); s.executeUpdate("DELETE FROM APP.CUSTOMER WHERE NAME = 'abc'"); rs = s.executeQuery("SELECT COUNT(*) FROM APP.CUSTOMER "); JDBC.assertFullResultSet(rs,new String[][] {{"8"}}); //End of parameter testing //The user table has to adhere to the collation type of the schema in which //it resides. If the table creation breaks that rule, then an exception //will be thrown. DERBY-2879 s.executeUpdate("set schema APP"); //following fails as expected because otherwise character types in T will //have collation type of UCS_BASIC but the APP schema has collation of //territory based assertStatementError("42ZA3", s, "CREATE TABLE T AS SELECT TABLENAME " + " FROM SYS.SYSTABLES WITH NO DATA"); //But following will work because there is no character string type //involved. (DERBY-2959) s.executeUpdate("CREATE TABLE T AS SELECT COLUMNNUMBER FROM " + " SYS.SYSCOLUMNS WITH NO DATA"); //DERBY-2951 //Following was giving Assert failure in store code because we were not //writing and reading the collation information from the disk. s.execute("create table assoc (x char(10) not null primary key, "+ " y char(100))"); s.execute("create table assocout(x char(10))"); ps = prepareStatement("insert into assoc values (?, 'hello')"); ps.setString(1, new Integer(10).toString()); ps.executeUpdate(); //DERBY-2955 //We should set the collation type in the bind phase of create table rather //than in code generation phase. Otherwise, following sql will give //incorrect exception about collation mismatch for the LIKE clause s.execute("CREATE TABLE DERBY_2955 (EMPNAME CHAR(20), CONSTRAINT " + " STAFF9_EMPNAME CHECK (EMPNAME NOT LIKE 'T%'))"); //DERBY-2960 //Following group by was failing earlier because we were generating //SQLVarchar rather than CollatorSQLVarchar in territory based db s.execute("CREATE TABLE DERBY_2960 (C CHAR(10), V VARCHAR(50))"); s.execute("INSERT INTO DERBY_2960 VALUES ('duplicate', 'is duplicated')"); rs = s.executeQuery("SELECT SUBSTR(c||v, 1, 4), COUNT(*) FROM DERBY_2960" + " GROUP BY SUBSTR(c||v, 1, 4)"); JDBC.assertFullResultSet(rs,new String[][] {{"dupl","1"}}); //DERBY-2966 //Moving to insert row in a territory based db should not cause exception ps = conn.prepareStatement("SELECT * FROM CUSTOMER FOR UPDATE", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = ps.executeQuery(); rs.moveToInsertRow(); rs.close(); ps.close(); //DERBY-2973 //alter table modify column should not give an error s.execute("CREATE TABLE DERBY_2973 (V VARCHAR(40))"); s.execute("CREATE INDEX DERBY_2973_I1 ON DERBY_2973 (V)"); s.execute("ALTER TABLE DERBY_2973 ALTER V SET DATA TYPE VARCHAR(4096)"); s.execute("INSERT INTO DERBY_2973 VALUES('hello')"); //DERBY-2967 //The special character _ should match one character and not just advance //by number of collation elements that special character _ represents s.executeUpdate("create table DERBY_2967(c11 int)"); s.executeUpdate("insert into DERBY_2967 values 1"); ps = prepareStatement("select 1 from DERBY_2967 where '\uFA2D' like ?"); String[] match = { "%", "_", "\uFA2D" }; for (int i = 0; i < match.length; i++) { ps.setString(1, match[i]); rs = ps.executeQuery(); JDBC.assertFullResultSet(rs,new String[][] {{"1"}}); } //DERBY-2961 //Should generate collation sensitive data type when working with something //like V AS CLOB insdie XMLSERIALIZE as shown below //SELECT ID, XMLSERIALIZE(V AS CLOB), XMLSERIALIZE(V AS CLOB) FROM // DERBY_2961 ORDER BY 1 s.executeUpdate("set schema APP"); if (XML.classpathMeetsXMLReqs()) { checkLangBasedQuery(s, "SELECT ID, XMLSERIALIZE(V AS CLOB) " + " FROM DERBY_2961 ORDER BY 1", new String[][] {{"1",null}}); } // Test Collation for functions DERBY-2972 s.executeUpdate("CREATE FUNCTION HELLO () RETURNS VARCHAR(32000) EXTERNAL NAME 'org.apache.derbyTesting.functionTests.tests.lang.CollationTest.hello' LANGUAGE JAVA PARAMETER STYLE JAVA"); s.executeUpdate("create table testing (a varchar(2024))"); s.executeUpdate("insert into testing values('hello')"); rs = s.executeQuery("select * from testing where a = HELLO()"); JDBC.assertSingleValueResultSet(rs, "hello"); s.executeUpdate("DROP FUNCTION hello"); s.executeUpdate("DROP TABLE testing"); // Test system functions. Should have UCS_BASIC collation // so a statement like this won't work, we need to cast the function. assertStatementError("42818",s,"VALUES case WHEN SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.stream.error.logSeverityLevel') = '50000' THEN 'LOGSHUTDOWN ERRORS' ELSE 'DONT KNOW' END"); // cast function output and we it will match the compilation schema and run rs = s.executeQuery("VALUES case WHEN CAST(SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.stream.error.logSeverityLevel') AS VARCHAR(30000)) = '50000' THEN 'LOGSHUTDOWN ERRORS' ELSE 'DONT KNOW' END"); JDBC.assertSingleValueResultSet(rs,"DONT KNOW"); // Test system table function. Should have UCS_BASIC collation s.executeUpdate("create table lockfunctesttable (i int)"); conn.setAutoCommit(false); s.executeUpdate("insert into lockfunctesttable values(1)"); // This statement should error because of collation mismatch assertStatementError("42818",s,"select * from SYSCS_DIAG.LOCK_TABLE where tablename = 'LOCKFUNCTESTTABLE'"); // we have to use parameter markers for it to work. ps = prepareStatement("select * from SYSCS_DIAG.LOCK_TABLE where tablename = ?"); ps.setString(1,"LOCKFUNCTESTTABLE"); rs = ps.executeQuery(); JDBC.assertDrainResults(rs,2); s.executeUpdate("drop table lockfunctesttable"); //DERBY-2910 // Test proper collation is set for implicit cast with // UPPER(CURRENT_DATE) and concatonation. s.executeUpdate("create table a (vc varchar(30))"); s.executeUpdate("insert into a values(CURRENT_DATE)"); rs = s.executeQuery("select vc from a where vc <= CURRENT_DATE"); assertEquals(1,JDBC.assertDrainResults(rs)); rs = s.executeQuery("select vc from a where vc <= UPPER(CURRENT_DATE)"); JDBC.assertDrainResults(rs,1); rs = s.executeQuery("select vc from a where vc <= LOWER(CURRENT_DATE)"); JDBC.assertDrainResults(rs,1); rs = s.executeQuery("select vc from a where vc <= '' || CURRENT_DATE"); JDBC.assertDrainResults(rs,1); rs = s.executeQuery("select vc from a where '' || CURRENT_DATE >= vc"); JDBC.assertDrainResults(rs,1); assertStatementError("42818",s,"select TABLENAME FROM SYS.SYSTABLES WHERE UPPER(CURRENT_DATE) = TABLENAME"); //Use a parameter as cast operand and cast that to character type. The // * resultant type should get it's collation from the compilation schema ps = prepareStatement("select vc from a where CAST (? AS VARCHAR(30)) = vc"); ps.setString(1,"hello"); rs = ps.executeQuery(); JDBC.assertEmpty(rs); //Binary arithmetic operators do casting if one of the operands is //string and other is numeric. Test that combination rs = s.executeQuery("select vc from a where '1.2' + 1.2 = 2.4"); JDBC.assertDrainResults(rs,1); //Do testing with UNION and use the results of UNION in collation //comparison s.executeUpdate("create table t1 (vc varchar(30))"); s.executeUpdate("create table t2 (vc varchar(30))"); s.executeUpdate("insert into t2 values('hello2')"); rs = s.executeQuery("select vc from t2 where vc = (select vc from t2 union select vc from t)"); JDBC.assertFullResultSet(rs, new String[][] {{"hello2"}}); s.executeUpdate("drop table t1"); s.executeUpdate("drop table t2"); // Cast in escape in like // Get Current date for use in query rs = s.executeQuery("VALUES CURRENT_DATE"); rs.next(); java.sql.Date d = rs.getDate(1); s.executeUpdate("create table t1 (vc varchar(30))"); s.executeUpdate("insert into t1 values(CURRENT_DATE)"); ps = prepareStatement("select vc from t1 where vc like ? escape '%'"); ps.setDate(1,d); rs = ps.executeQuery(); JDBC.assertDrainResults(rs); s.executeUpdate("drop table t1"); s.close(); } // methods used for function testing. /** * Name says it all * @return hello */ public static String hello() { return "hello"; } /** * Just return the value as passed in. Used to make sure * order by works properly with collation with order by expression * @param val value to return * @return string passed in */ public static String mimic(String val) { return val; } private void setUpTable(Statement s) throws SQLException { s.execute("CREATE TABLE CUSTOMER(ID INT, NAME VARCHAR(40), NAMECHAR CHAR(40))"); Connection conn = s.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO CUSTOMER VALUES(?,?,?)"); for (int i = 0; i < NAMES.length; i++) { ps.setInt(1, i); ps.setString(2, NAMES[i]); ps.setString(3, NAMES[i]); ps.executeUpdate(); } s.execute("create table xmlTable (x xml)"); s.executeUpdate("insert into xmlTable values(null)"); s.execute("create table DERBY_2961 (ID INT GENERATED ALWAYS AS " + " IDENTITY PRIMARY KEY, V XML)"); s.executeUpdate("insert into DERBY_2961(V) values(null)"); conn.commit(); ps.close(); } private void dropTable(Statement s) throws SQLException { s.execute("DROP TABLE APP.CUSTOMER"); s.getConnection().commit(); } /** * Execute the passed statement and compare the results against the * expectedResult * * @param s statement object to use to execute the query * @param query string with the query to execute. * @param expectedResult Null for this means that the passed query is * expected to return an empty resultset. If not empty, then the resultset * from the query should match this paramter * * @throws SQLException */ private void checkLangBasedQuery(Statement s, String query, String[][] expectedResult) throws SQLException { ResultSet rs = s.executeQuery(query); if (expectedResult == null) //expecting empty resultset from the query JDBC.assertEmpty(rs); else JDBC.assertFullResultSet(rs,expectedResult); } /** * We should get a locale unavailable message because there is no support for * locale xx. */ public void testMissingCollatorSupport() throws SQLException { - String url = TestConfiguration.getCurrent().getJDBCUrl("localeXXdb"); - - loadDriver(); - String defaultdburl = url + ";create=true;territory=xx;collation=TERRITORY_BASED"; + String createDBurl = ";create=true;territory=xx;collation=TERRITORY_BASED"; try { - DriverManager.getConnection(defaultdburl); + //Use following utility method rather than + //DriverManager.getConnection because the following utility method + //will use DataSource or DriverManager depending on the VM that is + //being used. Use of DriverManager to get a Connection will faile + //on JSR169 VMs. DERBY-3052 + TestUtil.getConnection("missingCollatorDB", createDBurl); } catch (SQLException sqle) { //Database can't be created because Collator support does not exist //for the requested locale BaseJDBCTestCase.assertSQLState("Unexpected error when connecting to database ", "XBM04", sqle); } } /** * Tests only need to run in embedded since collation * is a server side operation. */ public static Test suite() { TestSuite suite = new TestSuite("CollationTest"); //Add the test case for a locale which does not exist. We have asked for //locale as 'xx' and since there is not support Collator support for such //a locale, we will get an exception during database create time. TestCase missingCollatorDbTest = new CollationTest( "testMissingCollatorSupport"); suite.addTest(missingCollatorDbTest); suite.addTest(new CleanDatabaseTestSetup( new CollationTest("testDefaultCollation"))); suite.addTest(collatedSuite("en", "testEnglishCollation")); // Only add tests for other locales if they are in fact supported // by the jvm. Locale[] availableLocales = Collator.getAvailableLocales(); boolean norwegian = false; boolean polish = false; boolean french = false; for (int i=0; i<availableLocales.length ; i++) { if("no".equals(availableLocales[i].getLanguage())) { norwegian = true; } if("pl".equals(availableLocales[i].getLanguage())) { polish = true; } if("fr".equals(availableLocales[i].getLanguage())) { french = true; } } if(norwegian) { suite.addTest(collatedSuite("no", "testNorwayCollation")); } if(polish) { suite.addTest(collatedSuite("pl", "testPolishCollation")); } if(french) { suite.addTest(collatedSuite("fr", "testFrenchCollation")); } return suite; } /** Load the appropriate driver for the current framework */ private static void loadDriver() { String driverClass = TestConfiguration.getCurrent().getJDBCClient().getJDBCDriverName(); try { Class.forName(driverClass).newInstance(); } catch (Exception e) { fail ("could not instantiate driver"); } } /** * Return a suite that uses a single use database with * a primary fixture from this test plus potentially other * fixtures. * @param locale Locale to use for the database * @param baseFixture Base fixture from this test. * @return suite of tests to run for the given locale */ private static Test collatedSuite(String locale, String baseFixture) { TestSuite suite = new TestSuite("CollationTest:territory=" + locale); suite.addTest(new CollationTest(baseFixture)); // DMD.getTables() should not fail after the fix to DERBY-2896 /* * The following check condition was added because it would be * sufficient forthese testsuites to run with a single locale * and would save some time running tests. * Related To: JIRA DERBY-3554 */ if ("en".equals(locale)) { suite.addTest(DatabaseMetaDataTest.suite()); suite.addTest(BatchUpdateTest.embeddedSuite()); suite.addTest(GroupByExpressionTest.suite()); suite.addTest(UpdatableResultSetTest.suite()); } return Decorator.territoryCollatedDatabase(suite, locale); } }
false
false
null
null
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/LinkedResourceTest.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/LinkedResourceTest.java index 6e9147726..7617728d5 100644 --- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/LinkedResourceTest.java +++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/LinkedResourceTest.java @@ -1,1584 +1,1618 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.tests.resources; import java.io.*; import java.net.URI; +import java.util.HashMap; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.filesystem.*; -import org.eclipse.core.internal.resources.Workspace; +import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.utils.FileUtil; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.tests.harness.CancelingProgressMonitor; import org.eclipse.core.tests.harness.FussyProgressMonitor; /** * Tests the following API methods: * IFile#createLink * IFolder#createLink * * This test supports both variable-based and non-variable-based locations. * Although the method used for creating random locations * <code>ResourceTest#getRandomLocation()</code> never returns variable- * based paths, this method is overwritten in the derived class * <code>LinkedResourceWithPathVariable</code> to always return variable-based * paths. * * To support variable-based paths wherever a file system location is used, it * is mandatory first to resolve it and only then using it, except in calls to * <code>IFile#createLink</code> and <code>IFolder#createLink</code> and when * the location is obtained using <code>IResource#getLocation()</code>. */ public class LinkedResourceTest extends ResourceTest { protected String childName = "File.txt"; protected IProject closedProject; protected IFile existingFileInExistingProject; protected IFolder existingFolderInExistingFolder; protected IFolder existingFolderInExistingProject; protected IProject existingProject; protected IPath localFile; protected IPath localFolder; protected IFile nonExistingFileInExistingFolder; protected IFile nonExistingFileInExistingProject; protected IFile nonExistingFileInOtherExistingProject; protected IFolder nonExistingFolderInExistingFolder; protected IFolder nonExistingFolderInExistingProject; protected IFolder nonExistingFolderInNonExistingFolder; protected IFolder nonExistingFolderInNonExistingProject; protected IFolder nonExistingFolderInOtherExistingProject; protected IPath nonExistingLocation; protected IProject nonExistingProject; protected IProject otherExistingProject; public static Test suite() { return new TestSuite(LinkedResourceTest.class); // TestSuite suite = new TestSuite(); // suite.addTest(new LinkedResourceTest("testFindFilesForLocationCaseVariant")); // return suite; } public LinkedResourceTest() { super(); } public LinkedResourceTest(String name) { super(name); } protected void doCleanup() throws Exception { ensureExistsInWorkspace(new IResource[] {existingProject, otherExistingProject, closedProject, existingFolderInExistingProject, existingFolderInExistingFolder, existingFileInExistingProject}, true); closedProject.close(getMonitor()); ensureDoesNotExistInWorkspace(new IResource[] {nonExistingProject, nonExistingFolderInExistingProject, nonExistingFolderInExistingFolder, nonExistingFolderInOtherExistingProject, nonExistingFolderInNonExistingProject, nonExistingFolderInNonExistingFolder, nonExistingFileInExistingProject, nonExistingFileInOtherExistingProject, nonExistingFileInExistingFolder}); ensureDoesNotExistInFileSystem(resolve(nonExistingLocation).toFile()); resolve(localFolder).toFile().mkdirs(); createFileInFileSystem(resolve(localFile), getRandomContents()); } private byte[] getFileContents(IFile file) throws CoreException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); transferData(new BufferedInputStream(file.getContents()), bout); return bout.toByteArray(); } /** * Maybe overridden in subclasses that use path variables. */ protected IPath resolve(IPath path) { return path; } /** * Maybe overridden in subclasses that use path variables. */ protected URI resolve(URI uri) { return uri; } protected void setUp() throws Exception { super.setUp(); existingProject = getWorkspace().getRoot().getProject("ExistingProject"); otherExistingProject = getWorkspace().getRoot().getProject("OtherExistingProject"); closedProject = getWorkspace().getRoot().getProject("ClosedProject"); existingFolderInExistingProject = existingProject.getFolder("existingFolderInExistingProject"); existingFolderInExistingFolder = existingFolderInExistingProject.getFolder("existingFolderInExistingFolder"); nonExistingFolderInExistingProject = existingProject.getFolder("nonExistingFolderInExistingProject"); nonExistingFolderInOtherExistingProject = otherExistingProject.getFolder("nonExistingFolderInOtherExistingProject"); nonExistingFolderInNonExistingFolder = nonExistingFolderInExistingProject.getFolder("nonExistingFolderInNonExistingFolder"); nonExistingFolderInExistingFolder = existingFolderInExistingProject.getFolder("nonExistingFolderInExistingFolder"); nonExistingProject = getWorkspace().getRoot().getProject("NonProject"); nonExistingFolderInNonExistingProject = nonExistingProject.getFolder("nonExistingFolderInNonExistingProject"); existingFileInExistingProject = existingProject.getFile("existingFileInExistingProject"); nonExistingFileInExistingProject = existingProject.getFile("nonExistingFileInExistingProject"); nonExistingFileInOtherExistingProject = otherExistingProject.getFile("nonExistingFileInOtherExistingProject"); nonExistingFileInExistingFolder = existingFolderInExistingProject.getFile("nonExistingFileInExistingFolder"); localFolder = getRandomLocation(); nonExistingLocation = getRandomLocation(); localFile = localFolder.append(childName); doCleanup(); } protected void tearDown() throws Exception { super.tearDown(); Workspace.clear(resolve(localFolder).toFile()); Workspace.clear(resolve(nonExistingLocation).toFile()); } /** * Tests creation of a linked resource whose corresponding file system * path does not exist. This should succeed but no operations will be * available on the resulting resource. */ public void testAllowMissingLocal() { //get a non-existing location IPath location = getRandomLocation(); IFolder folder = nonExistingFolderInExistingProject; //try to create without the flag (should fail) try { folder.createLink(location, IResource.NONE, getMonitor()); fail("1.0"); } catch (CoreException e) { //should fail } //now try to create with the flag (should succeed) try { folder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.1", e); } assertEquals("1.2", resolve(location), folder.getLocation()); assertTrue("1.3", !resolve(location).toFile().exists()); //getting children should succeed (and be empty) try { assertEquals("1.4", 0, folder.members().length); } catch (CoreException e) { fail("1.5", e); } //delete should succeed try { folder.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.6", e); } //try to create with local path that can never exist if (isWindows()) location = new Path("b:\\does\\not\\exist"); else location = new Path("/dev/null/does/not/exist"); location = FileUtil.canonicalPath(location); try { folder.createLink(location, IResource.NONE, getMonitor()); fail("2.1"); } catch (CoreException e) { //should fail } try { folder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("2.2", e); } assertEquals("2.3", location, folder.getLocation()); assertTrue("2.4", !location.toFile().exists()); // creating child should fail try { folder.getFile("abc.txt").create(getRandomContents(), IResource.NONE, getMonitor()); fail("2.5"); } catch (CoreException e) { //should fail } } /** * Tests case where a resource in the file system cannot be added to the workspace * because it is blocked by a linked resource of the same name. */ public void testBlockedFolder() { //create local folder that will be blocked ensureExistsInFileSystem(nonExistingFolderInExistingProject); IFile blockedFile = nonExistingFolderInExistingProject.getFile("BlockedFile"); createFileInFileSystem(blockedFile.getLocation(), getRandomContents()); try { //link the folder elsewhere nonExistingFolderInExistingProject.createLink(localFolder, IResource.NONE, getMonitor()); //refresh the project existingProject.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("1.1", e); } //the blocked file should not exist in the workspace assertTrue("1.2", !blockedFile.exists()); assertTrue("1.3", nonExistingFolderInExistingProject.exists()); assertTrue("1.4", nonExistingFolderInExistingProject.getFile(childName).exists()); assertEquals("1.5", nonExistingFolderInExistingProject.getLocation(), resolve(localFolder)); //now delete the link try { nonExistingFolderInExistingProject.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } //the blocked file and the linked folder should not exist in the workspace assertTrue("2.0", !blockedFile.exists()); assertTrue("2.1", !nonExistingFolderInExistingProject.exists()); assertTrue("2.2", !nonExistingFolderInExistingProject.getFile(childName).exists()); assertEquals("2.3", nonExistingFolderInExistingProject.getLocation(), existingProject.getLocation().append(nonExistingFolderInExistingProject.getName())); //now refresh again to discover the blocked resource try { existingProject.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("2.99", e); } //the blocked file should now exist assertTrue("3.0", blockedFile.exists()); assertTrue("3.1", nonExistingFolderInExistingProject.exists()); assertTrue("3.2", !nonExistingFolderInExistingProject.getFile(childName).exists()); assertEquals("3.3", nonExistingFolderInExistingProject.getLocation(), existingProject.getLocation().append(nonExistingFolderInExistingProject.getName())); //attempting to link again will fail because the folder exists in the workspace try { nonExistingFolderInExistingProject.createLink(localFolder, IResource.NONE, getMonitor()); fail("3.4"); } catch (CoreException e) { //expected } } /** * This test creates a linked folder resource, then changes the directory in * the file system to be a file. On refresh, the linked resource should * still exist, should have the correct gender, and still be a linked * resource. */ public void testChangeLinkGender() { IFolder folder = nonExistingFolderInExistingProject; IFile file = folder.getProject().getFile(folder.getProjectRelativePath()); IPath resolvedLocation = resolve(localFolder); try { folder.createLink(localFolder, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("0.99", e); } ensureDoesNotExistInFileSystem(resolvedLocation.toFile()); createFileInFileSystem(resolvedLocation, getRandomContents()); try { folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("2.99", e); } assertTrue("3.0", !folder.exists()); assertTrue("3.1", file.exists()); assertTrue("3.2", file.isLinked()); assertEquals("3.3", resolvedLocation, file.getLocation()); //change back to folder ensureDoesNotExistInFileSystem(resolvedLocation.toFile()); resolvedLocation.toFile().mkdirs(); try { folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("3.99", e); } assertTrue("4.0", folder.exists()); assertTrue("4.1", !file.exists()); assertTrue("4.2", folder.isLinked()); assertEquals("4.3", resolvedLocation, folder.getLocation()); } public void testCopyFile() { IResource[] sources = new IResource[] {nonExistingFileInExistingProject, nonExistingFileInExistingFolder}; IResource[] destinationResources = new IResource[] {existingProject, closedProject, nonExistingFileInOtherExistingProject, nonExistingFileInExistingFolder}; Boolean[] deepCopy = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {sources, destinationResources, deepCopy, monitors}; new TestPerformer("LinkedResourceTest.testCopyFile") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFile source = (IFile) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { source.createLink(localFile, IResource.NONE, null); source.copy(destination.getFullPath(), isDeep ? IResource.NONE : IResource.SHALLOW, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IFile source = (IFile) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof CancelingProgressMonitor) return false; if (source.equals(destination)) return true; IResource parent = destination.getParent(); if (!isDeep && parent == null) return true; if (!parent.isAccessible()) return true; if (destination.exists()) return true; //passed all failure cases so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IFile source = (IFile) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; if (!destination.exists()) return false; //destination should only be linked for a shallow copy if (isDeep) { if (destination.isLinked()) return false; if (source.getLocation().equals(destination.getLocation())) return false; if (!destination.getProject().getLocation().isPrefixOf(destination.getLocation())) return false; } else { if (!destination.isLinked()) return false; if (!source.getLocation().equals(destination.getLocation())) return false; if (!source.getRawLocation().equals(destination.getRawLocation())) return false; if (!source.getLocationURI().equals(destination.getLocationURI())) return false; } return true; } }.performTest(inputs); } public void testCopyFolder() { IFolder[] sources = new IFolder[] {nonExistingFolderInExistingProject, nonExistingFolderInExistingFolder}; IResource[] destinations = new IResource[] {existingProject, closedProject, nonExistingProject, existingFolderInExistingProject, nonExistingFolderInOtherExistingProject, nonExistingFolderInExistingFolder}; Boolean[] deepCopy = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {sources, destinations, deepCopy, monitors}; new TestPerformer("LinkedResourceTest.testCopyFolder") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFolder source = (IFolder) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { source.createLink(localFolder, IResource.NONE, null); source.copy(destination.getFullPath(), isDeep ? IResource.NONE : IResource.SHALLOW, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IFolder source = (IFolder) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof CancelingProgressMonitor) return false; IResource parent = destination.getParent(); if (destination.getType() == IResource.PROJECT) return true; if (source.equals(destination)) return true; if (!isDeep && parent == null) return true; if (!parent.isAccessible()) return true; if (destination.exists()) return true; //passed all failure case so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IFolder source = (IFolder) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; if (!destination.exists()) return false; //destination should only be linked for a shallow copy if (isDeep) { if (destination.isLinked()) return false; if (source.getLocation().equals(destination.getLocation())) return false; if (!destination.getProject().getLocation().isPrefixOf(destination.getLocation())) return false; } else { if (!destination.isLinked()) return false; if (!source.getLocation().equals(destination.getLocation())) return false; if (!source.getLocationURI().equals(destination.getLocationURI())) return false; if (!source.getRawLocation().equals(destination.getRawLocation())) return false; } return true; } }.performTest(inputs); } /** * Tests copying a linked file resource that doesn't exist in the file system */ public void testCopyMissingFile() { IPath location = getRandomLocation(); IFile linkedFile = nonExistingFileInExistingProject; try { linkedFile.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IFile dest = existingProject.getFile("FailedCopyDest"); try { linkedFile.copy(dest.getFullPath(), IResource.NONE, getMonitor()); fail("2.0"); } catch (CoreException e1) { //should fail } assertTrue("2.1", !dest.exists()); try { linkedFile.copy(dest.getFullPath(), IResource.FORCE, getMonitor()); fail("2.2"); } catch (CoreException e1) { //should fail } assertTrue("2.3", !dest.exists()); } /** * Tests copying a linked folder that doesn't exist in the file system */ public void testCopyMissingFolder() { IPath location = getRandomLocation(); IFolder linkedFolder = nonExistingFolderInExistingProject; try { linkedFolder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IFolder dest = existingProject.getFolder("FailedCopyDest"); try { linkedFolder.copy(dest.getFullPath(), IResource.NONE, getMonitor()); fail("2.0"); } catch (CoreException e1) { //should fail } assertTrue("2.1", !dest.exists()); try { linkedFolder.copy(dest.getFullPath(), IResource.FORCE, getMonitor()); fail("2.2"); } catch (CoreException e1) { //should fail } assertTrue("2.3", !dest.exists()); } public void testCopyProjectWithLinks() { IPath fileLocation = getRandomLocation(); IFile linkedFile = nonExistingFileInExistingProject; IFolder linkedFolder = nonExistingFolderInExistingProject; try { try { createFileInFileSystem(resolve(fileLocation), getRandomContents()); linkedFolder.createLink(localFolder, IResource.NONE, getMonitor()); linkedFile.createLink(fileLocation, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } //copy the project IProject destination = getWorkspace().getRoot().getProject("CopyTargetProject"); try { existingProject.copy(destination.getFullPath(), IResource.SHALLOW, getMonitor()); } catch (CoreException e) { fail("2.0", e); } IFile newFile = destination.getFile(linkedFile.getProjectRelativePath()); assertTrue("3.0", newFile.isLinked()); assertEquals("3.1", linkedFile.getLocation(), newFile.getLocation()); IFolder newFolder = destination.getFolder(linkedFolder.getProjectRelativePath()); assertTrue("4.0", newFolder.isLinked()); assertEquals("4.1", linkedFolder.getLocation(), newFolder.getLocation()); //test project deep copy try { destination.delete(IResource.NONE, getMonitor()); existingProject.copy(destination.getFullPath(), IResource.NONE, getMonitor()); } catch (CoreException e) { fail("5.0", e); } assertTrue("5.1", !newFile.isLinked()); assertEquals("5.2", destination.getLocation().append(newFile.getProjectRelativePath()), newFile.getLocation()); assertTrue("5.3", !newFolder.isLinked()); assertEquals("5.4", destination.getLocation().append(newFolder.getProjectRelativePath()), newFolder.getLocation()); //test copy project when linked resources don't exist with force=false try { destination.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("5.99", e); } assertTrue("6.0", resolve(fileLocation).toFile().delete()); try { existingProject.copy(destination.getFullPath(), IResource.NONE, getMonitor()); fail("6.1"); } catch (CoreException e) { //should fail } //all members except the missing link should have been copied assertTrue("6.2", destination.exists()); assertTrue("6.2.1", !destination.getFile(linkedFile.getName()).exists()); try { IResource[] srcChildren = existingProject.members(); for (int i = 0; i < srcChildren.length; i++) { if (!srcChildren[i].equals(linkedFile)) assertNotNull("6.3." + i, destination.findMember(srcChildren[i].getProjectRelativePath())); } } catch (CoreException e) { fail("6.4", e); } //test copy project when linked resources don't exist with force=true //this should mostly succeed, but still throw an exception indicating //a resource could not be copied because its location was missing try { destination.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("6.5", e); } try { existingProject.copy(destination.getFullPath(), IResource.FORCE, getMonitor()); fail("6.6"); } catch (CoreException e) { //should fail } assertTrue("6.7", destination.exists()); assertTrue("6.7.1", !destination.getFile(linkedFile.getName()).exists()); //all members except the missing link should have been copied try { IResource[] srcChildren = existingProject.members(); for (int i = 0; i < srcChildren.length; i++) { if (!srcChildren[i].equals(linkedFile)) assertNotNull("6.8." + i, destination.findMember(srcChildren[i].getProjectRelativePath())); } } catch (CoreException e) { fail("6.99", e); } } finally { Workspace.clear(resolve(fileLocation).toFile()); } } /** * Tests creating a linked folder and performing refresh in the background */ public void testCreateFolderInBackground() throws CoreException { final IFileStore rootStore = getTempStore(); rootStore.mkdir(IResource.NONE, getMonitor()); IFileStore childStore = rootStore.getChild("file.txt"); createFileInFileSystem(childStore); IFolder link = nonExistingFolderInExistingProject; link.createLink(rootStore.toURI(), IResource.BACKGROUND_REFRESH, getMonitor()); waitForRefresh(); IFile linkChild = link.getFile(childStore.getName()); assertTrue("1.0", link.exists()); assertTrue("1.1", link.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("1.2", linkChild.exists()); assertTrue("1.3", linkChild.isSynchronized(IResource.DEPTH_INFINITE)); } /** * Tests creating a linked resource with the same name but different * case as an existing resource. On case insensitive platforms this should fail. */ public void testCreateLinkCaseVariant() { IFolder link = nonExistingFolderInExistingProject; IFolder variant = link.getParent().getFolder(new Path(link.getName().toUpperCase())); ensureExistsInWorkspace(variant, true); try { link.createLink(localFolder, IResource.NONE, getMonitor()); //should fail on case insensitive platforms if (!isCaseSensitive(variant)) fail("1.0"); } catch (CoreException e) { //should not fail on case sensitive platforms if (isCaseSensitive(variant)) fail("1.1", e); } } /** * Tests creating a linked resource by modifying the .project file directly. * This is a regression test for bug 63331. */ public void testCreateLinkInDotProject() { final IFile dotProject = existingProject.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); IFile link = nonExistingFileInExistingProject; byte[] oldContents = null; try { //create a linked file link.createLink(localFile, IResource.NONE, getMonitor()); //copy the .project file contents oldContents = getFileContents(dotProject); //delete linked file link.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } final byte[] finalContents = oldContents; try { //recreate the link in a workspace runnable with create scheduling rule getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { dotProject.setContents(new ByteArrayInputStream(finalContents), IResource.NONE, getMonitor()); } }, getWorkspace().getRuleFactory().modifyRule(dotProject), IResource.NONE, getMonitor()); } catch (CoreException e1) { fail("2.99", e1); } } /** * Tests creating a project whose .project file already defines links at * depth greater than one. See bug 121322. */ public void testCreateProjectWithDeepLinks() { IProject project = existingProject; IFolder parent = existingFolderInExistingProject; IFolder folder = nonExistingFolderInExistingFolder; try { folder.createLink(localFolder, IResource.NONE, getMonitor()); //delete and recreate the project project.delete(IResource.NEVER_DELETE_PROJECT_CONTENT, getMonitor()); project.create(getMonitor()); project.open(IResource.BACKGROUND_REFRESH, getMonitor()); assertTrue("1.0", folder.exists()); assertTrue("1.1", parent.exists()); assertTrue("1.2", parent.isLocal(IResource.DEPTH_INFINITE)); } catch (CoreException e) { fail("1.99", e); } } public void testDeepMoveProjectWithLinks() { IPath fileLocation = getRandomLocation(); IFile file = nonExistingFileInExistingProject; IFolder folder = nonExistingFolderInExistingProject; IFile childFile = folder.getFile(childName); IResource[] oldResources = new IResource[] {file, folder, existingProject, childFile}; try { try { createFileInFileSystem(resolve(fileLocation)); folder.createLink(localFolder, IResource.NONE, getMonitor()); file.createLink(fileLocation, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } //move the project IProject destination = getWorkspace().getRoot().getProject("MoveTargetProject"); IFile newFile = destination.getFile(file.getProjectRelativePath()); IFolder newFolder = destination.getFolder(folder.getProjectRelativePath()); IFile newChildFile = newFolder.getFile(childName); IResource[] newResources = new IResource[] {destination, newFile, newFolder, newChildFile}; assertDoesNotExistInWorkspace("2.0", destination); try { existingProject.move(destination.getFullPath(), IResource.NONE, getMonitor()); } catch (CoreException e) { fail("2.1", e); } assertExistsInWorkspace("3.0", newResources); assertDoesNotExistInWorkspace("3.1", oldResources); assertTrue("3.2", existingProject.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("3.3", destination.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("3.4", !newFile.isLinked()); assertEquals("3.5", destination.getLocation().append(newFile.getProjectRelativePath()), newFile.getLocation()); assertTrue("3.6", !newFolder.isLinked()); assertEquals("3.7", destination.getLocation().append(newFolder.getProjectRelativePath()), newFolder.getLocation()); assertTrue("3.8", destination.isSynchronized(IResource.DEPTH_INFINITE)); } finally { Workspace.clear(resolve(fileLocation).toFile()); } } /** * Tests deleting the parent of a linked resource. */ public void testDeleteLinkParent() { IFolder link = nonExistingFolderInExistingFolder; IFolder linkParent = existingFolderInExistingProject; IFile linkChild = link.getFile("child.txt"); IFileStore childStore = null; try { link.createLink(localFolder, IResource.NONE, getMonitor()); ensureExistsInWorkspace(linkChild, true); childStore = EFS.getStore(linkChild.getLocationURI()); } catch (CoreException e) { fail("0.99", e); return; } //everything should exist at this point assertTrue("1.0", linkParent.exists()); assertTrue("1.1", link.exists()); assertTrue("1.2", linkChild.exists()); //delete the parent of the link try { linkParent.delete(IResource.KEEP_HISTORY, getMonitor()); } catch (CoreException e) { fail("1.99", e); } //resources should not exist, but link content should exist on disk assertTrue("2.0", !linkParent.exists()); assertTrue("2.1", !link.exists()); assertTrue("2.2", !linkChild.exists()); assertTrue("2.3", childStore.fetchInfo().exists()); } /** * Tests deleting and then recreating a project */ public void testDeleteProjectWithLinks() { IFolder link = nonExistingFolderInExistingProject; try { link.createLink(localFolder, IResource.NONE, getMonitor()); existingProject.delete(IResource.NEVER_DELETE_PROJECT_CONTENT, getMonitor()); existingProject.create(getMonitor()); } catch (CoreException e) { fail("0.99", e); } //link should not exist until the project is open assertTrue("1.0", !link.exists()); try { existingProject.open(getMonitor()); } catch (CoreException e) { fail("1.99", e); } //link should now exist assertTrue("2.0", link.exists()); assertTrue("2.1", link.isLinked()); assertEquals("2.2", resolve(localFolder), link.getLocation()); } - + + /** + * Tests bug 209175. + */ + public void testDeleteFolderWithLinks() { + IProject project = existingProject; + IFolder folder = existingFolderInExistingProject; + IFile file1 = folder.getFile(getUniqueString()); + IFile file2 = project.getFile(getUniqueString()); + try { + file1.createLink(localFile, IResource.NONE, getMonitor()); + file2.createLink(localFile, IResource.NONE, getMonitor()); + + HashMap links = ((Project) project).internalGetDescription().getLinks(); + LinkDescription linkDescription1 = (LinkDescription)links.get(file1.getProjectRelativePath()); + assertNotNull("1.0", linkDescription1); + assertEquals("1.1", URIUtil.toURI(localFile), linkDescription1.getLocationURI()); + LinkDescription linkDescription2 = (LinkDescription)links.get(file2.getProjectRelativePath()); + assertNotNull("2.0", linkDescription2); + assertEquals("2.1", URIUtil.toURI(localFile), linkDescription2.getLocationURI()); + + folder.delete(true, getMonitor()); + + links = ((Project) project).internalGetDescription().getLinks(); + linkDescription1 = (LinkDescription)links.get(file1.getProjectRelativePath()); + assertNull("3.0", linkDescription1); + linkDescription2 = (LinkDescription)links.get(file2.getProjectRelativePath()); + assertNotNull("4.0", linkDescription2); + assertEquals("4.1", URIUtil.toURI(localFile), linkDescription2.getLocationURI()); + } catch (CoreException e) { + fail("5.0", e); + } + } + /** * Tests that IWorkspaceRoot.findFilesForLocation works correctly * in presence of a linked resource that does not match the case in the file system */ public void testFindFilesForLocationCaseVariant() { //this test only applies to file systems with a device in the path if (!isWindows()) return; IFolder link = nonExistingFolderInExistingProject; IPath localLocation = resolve(localFolder); IPath upperCase = localLocation.setDevice(localLocation.getDevice().toUpperCase()); IPath lowerCase = localLocation.setDevice(localLocation.getDevice().toLowerCase()); try { link.createLink(upperCase, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IPath lowerCaseFilePath = lowerCase.append("file.txt"); IFile[] files = getWorkspace().getRoot().findFilesForLocation(lowerCaseFilePath); assertEquals("1.0", 1, files.length); } /** * Tests the {@link org.eclipse.core.resources.IResource#isLinked(int)} method. */ public void testIsLinked() { //initially nothing is linked IResource[] toTest = new IResource[] {closedProject, existingFileInExistingProject, existingFolderInExistingFolder, existingFolderInExistingProject, existingProject, nonExistingFileInExistingFolder, nonExistingFileInExistingProject, nonExistingFileInOtherExistingProject, nonExistingFolderInExistingFolder, nonExistingFolderInExistingProject, nonExistingFolderInNonExistingFolder, nonExistingFolderInNonExistingProject, nonExistingFolderInOtherExistingProject, nonExistingProject, otherExistingProject}; for (int i = 0; i < toTest.length; i++) { assertTrue("1.0 " + toTest[i], !toTest[i].isLinked()); assertTrue("1.1 " + toTest[i], !toTest[i].isLinked(IResource.NONE)); assertTrue("1.2 " + toTest[i], !toTest[i].isLinked(IResource.CHECK_ANCESTORS)); } //create a link IFolder link = nonExistingFolderInExistingProject; try { link.createLink(localFolder, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IFile child = link.getFile(childName); assertTrue("2.0", child.exists()); assertTrue("2.1", link.isLinked()); assertTrue("2.2", link.isLinked(IResource.NONE)); assertTrue("2.3", link.isLinked(IResource.CHECK_ANCESTORS)); assertTrue("2.1", !child.isLinked()); assertTrue("2.2", !child.isLinked(IResource.NONE)); assertTrue("2.3", child.isLinked(IResource.CHECK_ANCESTORS)); } /** * Specific testing of links within links. */ public void testLinkedFileInLinkedFolder() { //setup handles IProject project = existingProject; IFolder top = project.getFolder("topFolder"); IFolder linkedFolder = top.getFolder("linkedFolder"); IFolder subFolder = linkedFolder.getFolder("subFolder"); IFile linkedFile = subFolder.getFile("Link.txt"); IFileStore folderStore = getTempStore(); IFileStore subFolderStore = folderStore.getChild(subFolder.getName()); IFileStore fileStore = getTempStore(); IPath folderLocation = URIUtil.toPath(folderStore.toURI()); IPath fileLocation = URIUtil.toPath(fileStore.toURI()); try { //create the structure on disk subFolderStore.mkdir(EFS.NONE, getMonitor()); fileStore.openOutputStream(EFS.NONE, getMonitor()).close(); //create the structure in the workspace ensureExistsInWorkspace(top, true); linkedFolder.createLink(folderStore.toURI(), IResource.NONE, getMonitor()); linkedFile.createLink(fileStore.toURI(), IResource.NONE, getMonitor()); } catch (CoreException e) { fail("4.99", e); } catch (IOException e) { fail("4.99", e); } //assert locations assertEquals("1.0", folderLocation, linkedFolder.getLocation()); assertEquals("1.1", folderLocation.append(subFolder.getName()), subFolder.getLocation()); assertEquals("1.2", fileLocation, linkedFile.getLocation()); //assert URIs assertEquals("1.0", folderStore.toURI(), linkedFolder.getLocationURI()); assertEquals("1.1", subFolderStore.toURI(), subFolder.getLocationURI()); assertEquals("1.2", fileStore.toURI(), linkedFile.getLocationURI()); } /** * Automated test of IFile#createLink */ public void testLinkFile() { IResource[] interestingResources = new IResource[] {existingFileInExistingProject, nonExistingFileInExistingProject, nonExistingFileInExistingFolder}; IPath[] interestingLocations = new IPath[] {localFile, localFolder, nonExistingLocation}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {interestingResources, interestingLocations, monitors}; new TestPerformer("LinkedResourceTest.testLinkFile") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFile file = (IFile) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { file.createLink(location, IResource.NONE, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IResource resource = (IResource) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof CancelingProgressMonitor) return false; //This resource already exists in the workspace if (resource.exists()) return true; IPath resolvedLocation = resolve(location); //The corresponding location in the local file system does not exist. if (!resolvedLocation.toFile().exists()) return true; //The workspace contains a resource of a different type at the same path as this resource if (getWorkspace().getRoot().findMember(resource.getFullPath()) != null) return true; //The parent of this resource does not exist. if (!resource.getParent().isAccessible()) return true; //The name of this resource is not valid (according to IWorkspace.validateName) if (!getWorkspace().validateName(resource.getName(), IResource.FOLDER).isOK()) return true; //The corresponding location in the local file system is occupied by a directory (as opposed to a file) if (resolvedLocation.toFile().isDirectory()) return true; //passed all failure case so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IFile resource = (IFile) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; IPath resolvedLocation = resolve(location); if (!resource.exists() || !resolvedLocation.toFile().exists()) return false; if (!resource.getLocation().equals(resolvedLocation)) return false; if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) return false; return true; } }.performTest(inputs); } /** * Automated test of IFolder#createLink */ public void testLinkFolder() { IResource[] interestingResources = new IResource[] {existingFolderInExistingProject, existingFolderInExistingFolder, nonExistingFolderInExistingProject, nonExistingFolderInNonExistingProject, nonExistingFolderInNonExistingFolder, nonExistingFolderInExistingFolder}; IPath[] interestingLocations = new IPath[] {localFile, localFolder, nonExistingLocation}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {interestingResources, interestingLocations, monitors}; new TestPerformer("LinkedResourceTest.testLinkFolder") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFolder folder = (IFolder) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { folder.createLink(location, IResource.NONE, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IResource resource = (IResource) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof CancelingProgressMonitor) return false; //This resource already exists in the workspace if (resource.exists()) return true; //The corresponding location in the local file system does not exist. if (!resolve(location).toFile().exists()) return true; //The workspace contains a resource of a different type at the same path as this resource if (getWorkspace().getRoot().findMember(resource.getFullPath()) != null) return true; //The parent of this resource does not exist. if (!resource.getParent().isAccessible()) return true; //The name of this resource is not valid (according to IWorkspace.validateName) if (!getWorkspace().validateName(resource.getName(), IResource.FOLDER).isOK()) return true; //The corresponding location in the local file system is occupied by a file (as opposed to a directory) if (resolve(location).toFile().isFile()) return true; //passed all failure case so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IFolder resource = (IFolder) args[0]; IPath location = (IPath) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; IPath resolvedLocation = resolve(location); if (!resource.exists() || !resolvedLocation.toFile().exists()) return false; if (!resource.getLocation().equals(resolvedLocation)) return false; //ensure child exists if (!resource.getFile(childName).exists()) return false; return true; } }.performTest(inputs); } /** * Tests creating a linked resource whose location contains a colon character. */ public void testLocationWithColon() { //windows does not allow a location with colon in the name if (isWindows()) return; IFolder folder = nonExistingFolderInExistingProject; try { //Note that on *nix, "c:/temp" is a relative path with two segments //so this is treated as relative to an undefined path variable called "c:". IPath location = new Path("c:/temp"); folder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); assertEquals("1.0", location, folder.getRawLocation()); } catch (CoreException e) { fail("1.99", e); } } /** * Tests the timestamp of a linked file when the local file is created or * deleted. See bug 34150 for more details. */ public void testModificationStamp() { IPath location = getRandomLocation(); IFile linkedFile = nonExistingFileInExistingProject; try { try { linkedFile.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.99", e); } assertEquals("1.0", IResource.NULL_STAMP, linkedFile.getModificationStamp()); //create local file try { resolve(location).toFile().createNewFile(); linkedFile.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("2.91", e); } catch (IOException e) { fail("2.92", e); } assertTrue("2.0", linkedFile.getModificationStamp() >= 0); //delete local file ensureDoesNotExistInFileSystem(resolve(location).toFile()); try { linkedFile.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("3.99", e); } assertEquals("4.0", IResource.NULL_STAMP, linkedFile.getModificationStamp()); } finally { Workspace.clear(resolve(location).toFile()); } } public void testMoveFile() { IResource[] sources = new IResource[] {nonExistingFileInExistingProject, nonExistingFileInExistingFolder}; IResource[] destinations = new IResource[] {existingProject, closedProject, nonExistingFileInOtherExistingProject, nonExistingFileInExistingFolder}; Boolean[] deepCopy = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {sources, destinations, deepCopy, monitors}; new TestPerformer("LinkedResourceTest.testMoveFile") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFile source = (IFile) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { source.createLink(localFile, IResource.NONE, null); source.move(destination.getFullPath(), isDeep ? IResource.NONE : IResource.SHALLOW, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IFile source = (IFile) args[0]; IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; if (monitor instanceof CancelingProgressMonitor) return false; IResource parent = destination.getParent(); if (!isDeep && parent == null) return true; if (!parent.isAccessible()) return true; if (source.equals(destination)) return true; if (source.getType() != destination.getType()) return true; if (destination.exists()) return true; //passed all failure case so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IResource destination = (IResource) args[1]; boolean isDeep = ((Boolean) args[2]).booleanValue(); IProgressMonitor monitor = (IProgressMonitor) args[3]; IPath sourceLocation = resolve(localFile); URI sourceLocationURI = URIUtil.toURI(sourceLocation); if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; if (!destination.exists()) return false; //destination should only be linked for a shallow move if (isDeep) { if (destination.isLinked()) return false; if (resolve(localFile).equals(destination.getLocation())) return false; if (!destination.getProject().getLocation().isPrefixOf(destination.getLocation())) return false; } else { if (!destination.isLinked()) return false; if (!sourceLocation.equals(destination.getLocation())) return false; if (!sourceLocationURI.equals(destination.getLocationURI())) return false; } return true; } }.performTest(inputs); } public void testMoveFolder() { IResource[] sourceResources = new IResource[] {nonExistingFolderInExistingProject, nonExistingFolderInExistingFolder}; IResource[] destinationResources = new IResource[] {existingProject, closedProject, nonExistingProject, existingFolderInExistingProject, nonExistingFolderInOtherExistingProject, nonExistingFolderInExistingFolder}; IProgressMonitor[] monitors = new IProgressMonitor[] {new FussyProgressMonitor(), new CancelingProgressMonitor(), null}; Object[][] inputs = new Object[][] {sourceResources, destinationResources, monitors}; new TestPerformer("LinkedResourceTest.testMoveFolder") { protected static final String CANCELED = "canceled"; public void cleanUp(Object[] args, int count) { super.cleanUp(args, count); try { doCleanup(); } catch (Exception e) { fail("invocation " + count + " failed to cleanup", e); } } public Object invokeMethod(Object[] args, int count) throws Exception { IFolder source = (IFolder) args[0]; IResource destination = (IResource) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).prepare(); try { source.createLink(localFolder, IResource.NONE, null); source.move(destination.getFullPath(), IResource.SHALLOW, monitor); } catch (OperationCanceledException e) { return CANCELED; } if (monitor instanceof FussyProgressMonitor) ((FussyProgressMonitor) monitor).sanityCheck(); return null; } public boolean shouldFail(Object[] args, int count) { IFolder source = (IFolder) args[0]; IResource destination = (IResource) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (monitor instanceof CancelingProgressMonitor) return false; IResource parent = destination.getParent(); if (parent == null) return true; if (source.equals(destination)) return true; if (source.getType() != destination.getType()) return true; if (!parent.isAccessible()) return true; if (destination.exists()) return true; //passed all failure case so it should succeed return false; } public boolean wasSuccess(Object[] args, Object result, Object[] oldState) throws Exception { IResource destination = (IResource) args[1]; IProgressMonitor monitor = (IProgressMonitor) args[2]; if (result == CANCELED) return monitor instanceof CancelingProgressMonitor; if (!destination.exists()) return false; if (!destination.isLinked()) return false; if (!resolve(localFolder).equals(destination.getLocation())) return false; return true; } }.performTest(inputs); } /** * Tests moving a linked file resource that doesn't exist in the file system */ public void testMoveMissingFile() { IPath location = getRandomLocation(); IFile linkedFile = nonExistingFileInExistingProject; try { linkedFile.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IFile dest = existingProject.getFile("FailedMoveDest"); try { linkedFile.move(dest.getFullPath(), IResource.NONE, getMonitor()); fail("2.0"); } catch (CoreException e1) { //should fail } assertTrue("2.1", !dest.exists()); try { linkedFile.move(dest.getFullPath(), IResource.FORCE, getMonitor()); fail("2.2"); } catch (CoreException e1) { //should fail } assertTrue("2.3", !dest.exists()); } /** * Tests moving a linked folder that doesn't exist in the file system */ public void testMoveMissingFolder() { IPath location = getRandomLocation(); IFolder linkedFolder = nonExistingFolderInExistingProject; try { linkedFolder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.99", e); } IFolder dest = existingProject.getFolder("FailedMoveDest"); try { linkedFolder.move(dest.getFullPath(), IResource.NONE, getMonitor()); fail("2.0"); } catch (CoreException e1) { //should fail } assertTrue("2.1", !dest.exists()); try { linkedFolder.move(dest.getFullPath(), IResource.FORCE, getMonitor()); fail("2.2"); } catch (CoreException e1) { //should fail } assertTrue("2.3", !dest.exists()); } public void testMoveProjectWithLinks() { IPath fileLocation = getRandomLocation(); IFile file = nonExistingFileInExistingProject; IFolder folder = nonExistingFolderInExistingProject; IFile childFile = folder.getFile(childName); IResource[] oldResources = new IResource[] {file, folder, existingProject, childFile}; try { try { createFileInFileSystem(resolve(fileLocation)); folder.createLink(localFolder, IResource.NONE, getMonitor()); file.createLink(fileLocation, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } //move the project IProject destination = getWorkspace().getRoot().getProject("MoveTargetProject"); IFile newFile = destination.getFile(file.getProjectRelativePath()); IFolder newFolder = destination.getFolder(folder.getProjectRelativePath()); IFile newChildFile = newFolder.getFile(childName); IResource[] newResources = new IResource[] {destination, newFile, newFolder, newChildFile}; assertDoesNotExistInWorkspace("2.0", destination); try { existingProject.move(destination.getFullPath(), IResource.SHALLOW, getMonitor()); } catch (CoreException e) { fail("2.1", e); } assertExistsInWorkspace("3.0", newResources); assertDoesNotExistInWorkspace("3.1", oldResources); assertTrue("3.2", newFile.isLinked()); assertEquals("3.3", resolve(fileLocation), newFile.getLocation()); assertTrue("3.4", newFolder.isLinked()); assertEquals("3.5", resolve(localFolder), newFolder.getLocation()); assertTrue("3.6", destination.isSynchronized(IResource.DEPTH_INFINITE)); //now do a deep move back to the original project try { destination.move(existingProject.getFullPath(), IResource.NONE, getMonitor()); } catch (CoreException e) { fail("5.0", e); } assertExistsInWorkspace("5.1", oldResources); assertDoesNotExistInWorkspace("5.2", newResources); assertTrue("5.3", !file.isLinked()); assertTrue("5.4", !folder.isLinked()); assertEquals("5.5", existingProject.getLocation().append(file.getProjectRelativePath()), file.getLocation()); assertEquals("5.6", existingProject.getLocation().append(folder.getProjectRelativePath()), folder.getLocation()); assertTrue("5.7", existingProject.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("5.8", destination.isSynchronized(IResource.DEPTH_INFINITE)); } finally { Workspace.clear(resolve(fileLocation).toFile()); } } /** * Tests bug 117402. */ public void testMoveProjectWithLinks2() { IPath fileLocation = getRandomLocation(); IFile linkedFile = existingProject.getFile("(test)"); try { try { createFileInFileSystem(resolve(fileLocation), getRandomContents()); linkedFile.createLink(fileLocation, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } //move the project IProject destination = getWorkspace().getRoot().getProject("CopyTargetProject"); try { existingProject.move(destination.getFullPath(), IResource.SHALLOW, getMonitor()); } catch (CoreException e) { fail("2.0", e); } IFile newFile = destination.getFile(linkedFile.getProjectRelativePath()); assertTrue("3.0", newFile.isLinked()); assertEquals("3.1", resolve(fileLocation), newFile.getLocation()); } finally { Workspace.clear(resolve(fileLocation).toFile()); } } public void testNatureVeto() { //note: simpleNature has the link veto turned on. //test create link on project with nature veto try { IProjectDescription description = existingProject.getDescription(); description.setNatureIds(new String[] {NATURE_SIMPLE}); existingProject.setDescription(description, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } try { nonExistingFolderInExistingProject.createLink(localFolder, IResource.NONE, getMonitor()); fail("1.1"); } catch (CoreException e) { //should fail } try { nonExistingFileInExistingProject.createLink(localFile, IResource.NONE, getMonitor()); fail("1.2"); } catch (CoreException e) { //should fail } //test add nature with veto to project that already has link try { existingProject.delete(IResource.FORCE, getMonitor()); existingProject.create(getMonitor()); existingProject.open(getMonitor()); nonExistingFolderInExistingProject.createLink(localFolder, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("2.0", e); } try { IProjectDescription description = existingProject.getDescription(); description.setNatureIds(new String[] {NATURE_SIMPLE}); existingProject.setDescription(description, IResource.NONE, getMonitor()); fail("3.0"); } catch (CoreException e) { //should fail } } /** * Tests creating a link within a link, and ensuring that both links still * exist when the project is closed/opened (bug 177367). */ public void testNestedLink() { final IFileStore store1 = getTempStore(); final IFileStore store2 = getTempStore(); URI location1 = store1.toURI(); URI location2 = store2.toURI(); //folder names are important here, because we want a certain order in the link hash map IFolder link = existingProject.getFolder("aA"); IFolder linkChild = link.getFolder("b"); try { store1.mkdir(EFS.NONE, getMonitor()); store2.mkdir(EFS.NONE, getMonitor()); link.createLink(location1, IResource.NONE, getMonitor()); linkChild.createLink(location2, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("0.99", e); } assertTrue("1.0", link.exists()); assertTrue("1.1", link.isLinked()); assertTrue("1.2", linkChild.exists()); assertTrue("1.3", linkChild.isLinked()); assertEquals("1.4", location1, link.getLocationURI()); assertEquals("1.5", location2, linkChild.getLocationURI()); //now delete and recreate the project try { existingProject.delete(IResource.NEVER_DELETE_PROJECT_CONTENT, getMonitor()); existingProject.create(getMonitor()); existingProject.open(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } assertTrue("2.0", link.exists()); assertTrue("2.1", link.isLinked()); assertTrue("2.2", linkChild.exists()); assertTrue("2.3", linkChild.isLinked()); assertEquals("2.4", location1, link.getLocationURI()); assertEquals("2.5", location2, linkChild.getLocationURI()); } /** * Create a project with a linked resource at depth > 2, and refresh it. */ public void testRefreshDeepLink() { IFolder link = nonExistingFolderInExistingFolder; IPath linkLocation = localFolder; IPath localChild = linkLocation.append("Child"); IFile linkChild = link.getFile(localChild.lastSegment()); createFileInFileSystem(resolve(localChild)); try { link.createLink(linkLocation, IResource.NONE, getMonitor()); } catch (CoreException e) { fail("0.99", e); } assertTrue("1.0", link.exists()); assertTrue("1.1", linkChild.exists()); try { IProject project = link.getProject(); project.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("1.99", e); } assertTrue("2.0", link.exists()); assertTrue("2.1", linkChild.exists()); } }
false
false
null
null
diff --git a/src/fitnesse/Arguments.java b/src/fitnesse/Arguments.java index 7ab16a3fe..435931db5 100644 --- a/src/fitnesse/Arguments.java +++ b/src/fitnesse/Arguments.java @@ -1,122 +1,122 @@ // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse; public class Arguments { public static final String DEFAULT_PATH = "."; public static final String DEFAULT_ROOT = "FitNesseRoot"; public static final int DEFAULT_PORT = 80; public static final int DEFAULT_COMMAND_PORT = 9123; public static final String DEFAULT_CONFIG_FILE = "plugins.properties"; public static final int DEFAULT_VERSION_DAYS = 14; private String rootPath = DEFAULT_PATH; private int port = -1; private String rootDirectory = DEFAULT_ROOT; private String logDirectory; private boolean omitUpdate = false; private int daysTillVersionsExpire = DEFAULT_VERSION_DAYS; private String userpass; private boolean installOnly; private String command = null; private String output = null; private String configFile = null; public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } public int getPort() { return port == -1 ? getDefaultPort() : port; } private int getDefaultPort() { return command == null ? DEFAULT_PORT : DEFAULT_COMMAND_PORT; } public void setPort(String port) { this.port = Integer.parseInt(port); } public String getRootDirectory() { return rootDirectory; } public void setRootDirectory(String rootDirectory) { this.rootDirectory = rootDirectory; } public String getLogDirectory() { return logDirectory; } public void setLogDirectory(String logDirectory) { this.logDirectory = logDirectory; } public void setOmitUpdates(boolean omitUpdates) { this.omitUpdate = omitUpdates; } public boolean isOmittingUpdates() { return omitUpdate; } public void setUserpass(String userpass) { this.userpass = userpass; } public String getUserpass() { if (userpass == null || userpass.length() == 0) return null; else return userpass; } public int getDaysTillVersionsExpire() { return daysTillVersionsExpire; } public void setDaysTillVersionsExpire(String daysTillVersionsExpire) { this.daysTillVersionsExpire = Integer.parseInt(daysTillVersionsExpire); } public boolean isInstallOnly() { return installOnly; } public void setInstallOnly(boolean installOnly) { this.installOnly = installOnly; } public String getCommand() { if (command == null) return null; else return command; } public void setCommand(String command) { this.command = command; } public void setOutput(String output) { this.output = output; } public String getOutput() { return output; } public String getConfigFile() { - return configFile == null ? DEFAULT_CONFIG_FILE : configFile; + return configFile == null ? (rootPath + "/" + DEFAULT_CONFIG_FILE) : configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } } diff --git a/src/fitnesse/ArgumentsTest.java b/src/fitnesse/ArgumentsTest.java index 197276ebe..6df34a105 100644 --- a/src/fitnesse/ArgumentsTest.java +++ b/src/fitnesse/ArgumentsTest.java @@ -1,97 +1,116 @@ // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse; import static org.junit.Assert.*; import fitnesseMain.FitNesseMain; import org.junit.Test; public class ArgumentsTest { private Arguments args; @Test public void testSimpleCommandline() throws Exception { args = makeArgs(new String[0]); assertNotNull(args); assertEquals(80, args.getPort()); assertEquals(".", args.getRootPath()); } private Arguments makeArgs(String... argArray) { return args = FitNesseMain.parseCommandLine(argArray); } @Test public void testArgumentsDefaults() throws Exception { makeArgs(); assertEquals(80, args.getPort()); assertEquals(".", args.getRootPath()); assertEquals("FitNesseRoot", args.getRootDirectory()); assertEquals(null, args.getLogDirectory()); assertEquals(false, args.isOmittingUpdates()); assertEquals(14, args.getDaysTillVersionsExpire()); assertEquals(null, args.getUserpass()); assertEquals(false, args.isInstallOnly()); assertNull(args.getCommand()); } @Test public void testArgumentsAlternates() throws Exception { String argString = "-p 123 -d MyWd -r MyRoot -l LogDir -e 321 -o -a userpass.txt -i"; makeArgs(argString.split(" ")); assertEquals(123, args.getPort()); assertEquals("MyWd", args.getRootPath()); assertEquals("MyRoot", args.getRootDirectory()); assertEquals("LogDir", args.getLogDirectory()); assertEquals(true, args.isOmittingUpdates()); assertEquals(321, args.getDaysTillVersionsExpire()); assertEquals("userpass.txt", args.getUserpass()); assertEquals(true, args.isInstallOnly()); } @Test public void testAllArguments() throws Exception { args = makeArgs("-p", "81", "-d", "directory", "-r", "root", "-l", "myLogDirectory", "-o", "-e", "22"); assertNotNull(args); assertEquals(81, args.getPort()); assertEquals("directory", args.getRootPath()); assertEquals("root", args.getRootDirectory()); assertEquals("myLogDirectory", args.getLogDirectory()); assertTrue(args.isOmittingUpdates()); assertEquals(22, args.getDaysTillVersionsExpire()); } @Test public void testNotOmitUpdates() throws Exception { args = makeArgs("-p", "81", "-d", "directory", "-r", "root", "-l", "myLogDirectory"); assertNotNull(args); assertEquals(81, args.getPort()); assertEquals("directory", args.getRootPath()); assertEquals("root", args.getRootDirectory()); assertEquals("myLogDirectory", args.getLogDirectory()); assertFalse(args.isOmittingUpdates()); } @Test public void commandShouldUseDifferentDefaultPort() throws Exception { args = makeArgs("-c", "someCommand"); assertNotNull(args); assertEquals(Arguments.DEFAULT_COMMAND_PORT, args.getPort()); } @Test public void commandShouldAllowPortToBeSet() throws Exception { args = makeArgs("-c", "someCommand", "-p", "666"); assertNotNull(args); assertEquals(666, args.getPort()); } @Test public void testBadArgument() throws Exception { args = makeArgs("-x"); assertNull(args); } + + @Test + public void defaultConfigLocation() { + args = makeArgs(); + assertEquals("./plugins.properties", args.getConfigFile()); + } + + @Test + public void configLocationWithDifferentRootPath() { + args = makeArgs("-d", "customDir"); + assertEquals("customDir/plugins.properties", args.getConfigFile()); + } + + @Test + public void customConfigLocation() { + args = makeArgs("-f", "custom.properties"); + assertEquals("custom.properties", args.getConfigFile()); + } + }
false
false
null
null
diff --git a/module-nio/src/examples/org/apache/http/nio/examples/AsyncHttpServer.java b/module-nio/src/examples/org/apache/http/nio/examples/AsyncHttpServer.java index e780ebdc2..5475e3762 100644 --- a/module-nio/src/examples/org/apache/http/nio/examples/AsyncHttpServer.java +++ b/module-nio/src/examples/org/apache/http/nio/examples/AsyncHttpServer.java @@ -1,256 +1,259 @@ package org.apache.http.nio.examples; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.URLDecoder; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.ContentProducer; import org.apache.http.entity.EntityTemplate; import org.apache.http.entity.FileEntity; import org.apache.http.impl.DefaultHttpParams; import org.apache.http.nio.IOConsumer; import org.apache.http.nio.IOEventDispatch; import org.apache.http.nio.IOProducer; import org.apache.http.nio.IOSession; import org.apache.http.nio.IOReactor; import org.apache.http.nio.impl.AsyncHttpServerConnection; import org.apache.http.nio.impl.DefaultListeningIOReactor; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExecutionContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.SyncHttpExecutionContext; public class AsyncHttpServer { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } HttpParams params = new DefaultHttpParams(null); params .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000) .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false) .setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true) .setParameter(HttpProtocolParams.ORIGIN_SERVER, "Jakarta-HttpComponents-NIO/1.1"); HttpContext globalContext = new SyncHttpExecutionContext(null); globalContext.setAttribute("server.docroot", args[0]); IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch(params, globalContext); IOReactor ioReactor = new DefaultListeningIOReactor(new InetSocketAddress(8080), params); try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } static class DefaultIoEventDispatch implements IOEventDispatch { private static final String CONSUMER = "CONSUMER"; private static final String PRODUCER = "PRODUCER"; private static final String CONNECTION = "CONNECTION"; private static final String WORKER = "WORKER"; private final HttpParams params; private final HttpContext context; public DefaultIoEventDispatch(final HttpParams params, final HttpContext context) { super(); if (params == null) { throw new IllegalArgumentException("HTTP parameters may nor be null"); } this.params = params; this.context = context; } public void connected(IOSession session) { AsyncHttpServerConnection conn = new AsyncHttpServerConnection(session, this.params); session.setAttribute(CONNECTION, conn); session.setAttribute(CONSUMER, conn.getIOConsumer()); session.setAttribute(PRODUCER, conn.getIOProducer()); // Set up HTTP service - HttpService httpService = new HttpService(); - httpService.addInterceptor(new ResponseDate()); - httpService.addInterceptor(new ResponseServer()); - httpService.addInterceptor(new ResponseContent()); - httpService.addInterceptor(new ResponseConnControl()); + BasicHttpProcessor httpProcessor = new BasicHttpProcessor(); + httpProcessor.addInterceptor(new ResponseDate()); + httpProcessor.addInterceptor(new ResponseServer()); + httpProcessor.addInterceptor(new ResponseContent()); + httpProcessor.addInterceptor(new ResponseConnControl()); + + HttpService httpService = new HttpService(httpProcessor); httpService.setParams(this.params); httpService.registerRequestHandler("*", new HttpFileHandler()); Thread worker = new WorkerThread(httpService, conn, this.context); session.setAttribute(WORKER, worker); worker.setDaemon(true); worker.start(); session.setSocketTimeout(20000); } public void inputReady(final IOSession session) { IOConsumer consumer = (IOConsumer) session.getAttribute(CONSUMER); try { consumer.consumeInput(); } catch (IOException ex) { consumer.shutdown(ex); } } public void outputReady(final IOSession session) { IOProducer producer = (IOProducer) session.getAttribute(PRODUCER); try { producer.produceOutput(); } catch (IOException ex) { producer.shutdown(ex); } } public void timeout(final IOSession session) { IOConsumer consumer = (IOConsumer) session.getAttribute(CONSUMER); consumer.shutdown(new SocketTimeoutException("Socket read timeout")); } public void disconnected(final IOSession session) { HttpConnection conn = (HttpConnection) session.getAttribute(CONNECTION); try { conn.shutdown(); } catch (IOException ex) { System.err.println("I/O error while shutting down connection"); } Thread worker = (Thread) session.getAttribute(WORKER); worker.interrupt(); } } static class HttpFileHandler implements HttpRequestHandler { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod(); if (!method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("HEAD")) { throw new MethodNotSupportedException(method + " method not supported"); } String docroot = (String) context.getAttribute("server.docroot"); String target = request.getRequestLine().getUri(); final File file = new File(docroot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write(file.getPath()); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); body.setContentType("text/html; charset=UTF-8"); response.setEntity(body); System.out.println("File " + file.getPath() + " not found"); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("Access denied"); writer.write("</h1></body></html>"); writer.flush(); } }); body.setContentType("text/html; charset=UTF-8"); response.setEntity(body); System.out.println("Cannot read file " + file.getPath()); } else { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, "text/html"); response.setEntity(body); System.out.println("Serving file " + file.getPath()); } } } static class WorkerThread extends Thread { private final HttpService httpservice; private final HttpServerConnection conn; private final HttpContext context; public WorkerThread( final HttpService httpservice, final HttpServerConnection conn, final HttpContext parentContext) { super(); this.httpservice = httpservice; this.conn = conn; this.context = new HttpExecutionContext(parentContext); } public void run() { System.out.println("New connection thread"); try { while (!Thread.interrupted() && this.conn.isOpen()) { this.httpservice.handleRequest(this.conn, this.context); } } catch (ConnectionClosedException ex) { System.err.println("Client closed connection"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } catch (HttpException ex) { System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); } finally { try { this.conn.shutdown(); } catch (IOException ignore) {} } } } }
false
false
null
null
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java index 64dc8d63a..ea4cb708f 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java @@ -1,824 +1,824 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.ui.editor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ContentProposalAdapter; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCustomField; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaReportElement; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylyn.internal.bugzilla.core.RepositoryConfiguration; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_OPERATION; import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.RepositoryOperation; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.ui.DatePicker; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.mylyn.tasks.ui.editors.AbstractRepositoryTaskEditor; import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.Section; /** * An editor used to view a bug report that exists on a server. It uses a <code>BugReport</code> object to store the * data. * * @author Mik Kersten (hardening of prototype) * @author Rob Elves * @author Jeff Pound (Attachment work) */ public class BugzillaTaskEditor extends AbstractRepositoryTaskEditor { private static final String LABEL_TIME_TRACKING = "Bugzilla Time Tracking"; private static final String LABEL_CUSTOM_FIELD = "Custom Fields"; protected Text keywordsText; protected Text estimateText; protected Text actualText; protected Text remainingText; protected Text addTimeText; protected Text deadlineText; protected DatePicker deadlinePicker; protected Text votesText; protected Text assignedTo; /** * Creates a new <code>ExistingBugEditor</code>. */ public BugzillaTaskEditor(FormEditor editor) { super(editor); // Set up the input for comparing the bug report to the server // CompareConfiguration config = new CompareConfiguration(); // config.setLeftEditable(false); // config.setRightEditable(false); // config.setLeftLabel("Local Bug Report"); // config.setRightLabel("Remote Bug Report"); // config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); // config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); // compareInput = new BugzillaCompareInput(config); } @Override protected boolean supportsCommentSort() { return false; } @Override protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } + // NOTE: urlText should not be back ported to 3.3 due to background color failure attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); - // false, SWT.FLAT | SWT.SINGLE); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } } private boolean hasCustomAttributeChanges() { if (taskData == null) return false; String customAttributeKeys[] = { BugzillaReportElement.BUG_FILE_LOC.getKeyString(), BugzillaReportElement.DEPENDSON.getKeyString(), BugzillaReportElement.BLOCKED.getKeyString(), BugzillaReportElement.KEYWORDS.getKeyString(), BugzillaReportElement.VOTES.getKeyString(), BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString(), BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString(), BugzillaReportElement.ESTIMATED_TIME.getKeyString(), BugzillaReportElement.REMAINING_TIME.getKeyString(), BugzillaReportElement.ACTUAL_TIME.getKeyString(), BugzillaReportElement.DEADLINE.getKeyString(), BugzillaReportElement.STATUS_WHITEBOARD.getKeyString() }; for (String key : customAttributeKeys) { RepositoryTaskAttribute attribute = taskData.getAttribute(key); if (hasChanged(attribute)) { return true; } } return false; } @Override protected boolean hasVisibleAttributeChanges() { return super.hasVisibleAttributeChanges() || this.hasCustomAttributeChanges(); } private void addBugHyperlinks(Composite composite, String key) { Composite hyperlinksComposite = getManagedForm().getToolkit().createComposite(composite); RowLayout rowLayout = new RowLayout(); rowLayout.marginBottom = 0; rowLayout.marginLeft = 0; rowLayout.marginRight = 0; rowLayout.marginTop = 0; rowLayout.spacing = 0; hyperlinksComposite.setLayout(new RowLayout()); String values = taskData.getAttributeValue(key); if (values != null && values.length() > 0) { for (String bugNumber : values.split(",")) { final String bugId = bugNumber.trim(); final String bugUrl = repository.getRepositoryUrl() + IBugzillaConstants.URL_GET_SHOW_BUG + bugId; final AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getRepositoryUrl(), bugId); createTaskListHyperlink(hyperlinksComposite, bugId, bugUrl, task); } } } protected void addRoles(Composite parent) { Section rolesSection = getManagedForm().getToolkit().createSection(parent, ExpandableComposite.SHORT_TITLE_BAR); rolesSection.setText("Users in the roles selected below can always view this bug"); rolesSection.setDescription("(The assignee can always see a bug, and this section does not take effect unless the bug is restricted to at least one group.)"); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; rolesSection.setLayout(gl); rolesSection.setLayoutData(gd); Composite rolesComposite = getManagedForm().getToolkit().createComposite(rolesSection); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 5; attributesLayout.verticalSpacing = 4; rolesComposite.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; rolesComposite.setLayoutData(attributesData); rolesSection.setClient(rolesComposite); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString()); } Button button = addButtonField(rolesComposite, attribute, SWT.CHECK); if (hasChanged(attribute)) { button.setBackground(getColorIncoming()); } attribute = null; attribute = taskData.getAttribute(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString()); } button = addButtonField(rolesComposite, attribute, SWT.CHECK); if (hasChanged(attribute)) { button.setBackground(getColorIncoming()); } } @Override protected boolean hasContentAssist(RepositoryTaskAttribute attribute) { return BugzillaReportElement.NEWCC.getKeyString().equals(attribute.getId()); } @Override protected boolean hasContentAssist(RepositoryOperation repositoryOperation) { BUGZILLA_OPERATION operation; try { operation = BUGZILLA_OPERATION.valueOf(repositoryOperation.getKnobName()); } catch (RuntimeException e) { // FIXME: ? StatusHandler.log(new Status(IStatus.INFO, BugzillaUiPlugin.PLUGIN_ID, "Unrecognized operation: " + repositoryOperation.getKnobName(), e)); operation = null; } if (operation != null && operation == BUGZILLA_OPERATION.reassign) { return true; } else { return false; } } private Button addButtonField(Composite rolesComposite, RepositoryTaskAttribute attribute, int style) { if (attribute == null) { return null; } String name = attribute.getName(); if (hasOutgoingChange(attribute)) { name += "*"; } final Button button = getManagedForm().getToolkit().createButton(rolesComposite, name, style); if (!attribute.isReadOnly()) { button.setData(attribute); button.setSelection(attribute.getValue().equals("1")); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String sel = "1"; if (!button.getSelection()) { sel = "0"; } RepositoryTaskAttribute a = (RepositoryTaskAttribute) button.getData(); a.setValue(sel); attributeChanged(a); } }); } return button; } protected void addBugzillaTimeTracker(FormToolkit toolkit, Composite parent) { Section timeSection = toolkit.createSection(parent, ExpandableComposite.SHORT_TITLE_BAR); timeSection.setText(LABEL_TIME_TRACKING); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; timeSection.setLayout(gl); timeSection.setLayoutData(gd); Composite timeComposite = toolkit.createComposite(timeSection); gl = new GridLayout(4, false); timeComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; timeComposite.setLayoutData(gd); RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { createLabel(timeComposite, attribute); estimateText = createTextField(timeComposite, attribute, SWT.FLAT); estimateText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); } Label label = toolkit.createLabel(timeComposite, "Current Estimate:"); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); float total = 0; try { total = (Float.parseFloat(taskData.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + Float.parseFloat(taskData.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()))); } catch (Exception e) { // ignore likely NumberFormatException } Text currentEstimate = toolkit.createText(timeComposite, "" + total); currentEstimate.setFont(TEXT_FONT); currentEstimate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); currentEstimate.setEditable(false); attribute = this.taskData.getAttribute(BugzillaReportElement.ACTUAL_TIME.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); Text actualText = createTextField(timeComposite, attribute, SWT.FLAT); actualText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); actualText.setEditable(false); } // Add Time taskData.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), "0"); final RepositoryTaskAttribute addTimeAttribute = this.taskData.getAttribute(BugzillaReportElement.WORK_TIME.getKeyString()); if (addTimeAttribute != null) { createLabel(timeComposite, addTimeAttribute); addTimeText = toolkit.createText(timeComposite, taskData.getAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString()), SWT.BORDER); addTimeText.setFont(TEXT_FONT); addTimeText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); addTimeText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { addTimeAttribute.setValue(addTimeText.getText()); attributeChanged(addTimeAttribute); } }); } attribute = this.taskData.getAttribute(BugzillaReportElement.REMAINING_TIME.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); createTextField(timeComposite, attribute, SWT.FLAT); } attribute = this.taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); Composite dateWithClear = toolkit.createComposite(timeComposite); GridLayout layout = new GridLayout(2, false); layout.marginWidth = 1; dateWithClear.setLayout(layout); deadlinePicker = new DatePicker(dateWithClear, /* SWT.NONE */SWT.BORDER, taskData.getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString()), false); deadlinePicker.setFont(TEXT_FONT); deadlinePicker.setDatePattern("yyyy-MM-dd"); if (hasChanged(attribute)) { deadlinePicker.setBackground(getColorIncoming()); } deadlinePicker.addPickerSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { Calendar cal = deadlinePicker.getDate(); if (cal != null) { Date d = cal.getTime(); SimpleDateFormat f = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); f.applyPattern("yyyy-MM-dd"); taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), f.format(d)); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); // TODO goes dirty even if user presses cancel // markDirty(true); } else { taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), ""); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); deadlinePicker.setDate(null); } } }); ImageHyperlink clearDeadlineDate = toolkit.createImageHyperlink(dateWithClear, SWT.NONE); clearDeadlineDate.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); clearDeadlineDate.setToolTipText("Clear"); clearDeadlineDate.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), ""); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); deadlinePicker.setDate(null); } }); } timeSection.setClient(timeComposite); } protected void addKeywordsList(Composite attributesComposite) throws IOException { // newLayout(attributesComposite, 1, "Keywords:", PROPERTY); final RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.KEYWORDS); if (attribute == null) return; Label label = createLabel(attributesComposite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); // toolkit.createText(attributesComposite, keywords) keywordsText = createTextField(attributesComposite, attribute, SWT.FLAT); keywordsText.setFont(TEXT_FONT); GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keywordsData.horizontalSpan = 2; keywordsData.widthHint = 200; keywordsText.setLayoutData(keywordsData); Button changeKeywordsButton = getManagedForm().getToolkit().createButton(attributesComposite, "Edit...", SWT.FLAT); GridData keyWordsButtonData = new GridData(); changeKeywordsButton.setLayoutData(keyWordsButtonData); changeKeywordsButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { String keywords = attribute.getValue(); Shell shell = null; if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) { shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); } else { shell = new Shell(PlatformUI.getWorkbench().getDisplay()); } List<String> validKeywords = new ArrayList<String>(); try { validKeywords = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getKeywords(); } catch (Exception ex) { // ignore } KeywordsDialog keywordsDialog = new KeywordsDialog(shell, keywords, validKeywords); int responseCode = keywordsDialog.open(); String newKeywords = keywordsDialog.getSelectedKeywordsString(); if (responseCode == Dialog.OK && keywords != null) { keywordsText.setText(newKeywords); attribute.setValue(newKeywords); attributeChanged(attribute); } else { return; } } }); } protected void addVoting(Composite attributesComposite) { Label label = getManagedForm().getToolkit().createLabel(attributesComposite, "Votes:"); label.setForeground(getManagedForm().getToolkit().getColors().getColor(IFormColors.TITLE)); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite votingComposite = getManagedForm().getToolkit().createComposite(attributesComposite); GridLayout layout = new GridLayout(3, false); layout.marginHeight = 0; layout.marginWidth = 0; votingComposite.setLayout(layout); RepositoryTaskAttribute votesAttribute = taskData.getAttribute(BugzillaReportElement.VOTES.getKeyString()); votesText = createTextField(votingComposite, votesAttribute, SWT.FLAT | SWT.READ_ONLY); votesText.setFont(TEXT_FONT); GridDataFactory.fillDefaults().minSize(30, SWT.DEFAULT).hint(30, SWT.DEFAULT).applyTo(votesText); if (votesAttribute != null && hasChanged(votesAttribute)) { votesText.setBackground(getColorIncoming()); } votesText.setEditable(false); Hyperlink showVotesHyperlink = getManagedForm().getToolkit().createHyperlink(votingComposite, "Show votes", SWT.NONE); showVotesHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { if (BugzillaTaskEditor.this.getEditor() instanceof TaskEditor) { TasksUiUtil.openUrl(repository.getRepositoryUrl() + IBugzillaConstants.URL_SHOW_VOTES + taskData.getTaskId()); } } }); Hyperlink voteHyperlink = getManagedForm().getToolkit().createHyperlink(votingComposite, "Vote", SWT.NONE); voteHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { if (BugzillaTaskEditor.this.getEditor() instanceof TaskEditor) { TasksUiUtil.openUrl(repository.getRepositoryUrl() + IBugzillaConstants.URL_VOTE + taskData.getTaskId()); } } }); } @Override protected void validateInput() { } @Override protected String getHistoryUrl() { if (repository != null && taskData != null) { return repository.getRepositoryUrl() + IBugzillaConstants.URL_BUG_ACTIVITY + taskData.getTaskId(); } else { return null; } } /** * @author Frank Becker (bug 198027) FIXME: A lot of duplicated code here between this and NewBugzillataskEditor */ @Override protected void addAssignedTo(Composite peopleComposite) { RepositoryTaskAttribute assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (assignedAttribute != null) { String bugzillaVersion; try { bugzillaVersion = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getInstallVersion(); } catch (CoreException e1) { // ignore bugzillaVersion = "2.18"; } if (bugzillaVersion.compareTo("3.1") < 0) { // old bugzilla workflow is used super.addAssignedTo(peopleComposite); return; } Label label = createLabel(peopleComposite, assignedAttribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); assignedTo = createTextField(peopleComposite, assignedAttribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(assignedTo); assignedTo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String sel = assignedTo.getText(); RepositoryTaskAttribute a = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (!(a.getValue().equals(sel))) { a.setValue(sel); markDirty(true); } } }); ContentAssistCommandAdapter adapter = applyContentAssist(assignedTo, createContentProposalProvider(assignedAttribute)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(assignedAttribute); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); FormToolkit toolkit = getManagedForm().getToolkit(); Label dummylabel = toolkit.createLabel(peopleComposite, ""); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(dummylabel); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); } addButtonField(peopleComposite, attribute, SWT.CHECK); } } protected boolean attributeChanged(RepositoryTaskAttribute attribute) { if (attribute == null) { return false; } // Support comment wrapping for bugzilla 2.18 if (attribute.getId().equals(BugzillaReportElement.NEW_COMMENT.getKeyString())) { if (repository.getVersion().startsWith("2.18")) { attribute.setValue(BugzillaUiPlugin.formatTextToLineWrap(attribute.getValue(), true)); } } return super.attributeChanged(attribute); } @Override protected void addSelfToCC(Composite composite) { // XXX: Work around for adding QAContact to People section. Update once bug#179254 is complete boolean haveRealName = false; RepositoryTaskAttribute qaContact = taskData.getAttribute(BugzillaReportElement.QA_CONTACT_NAME.getKeyString()); if (qaContact == null) { qaContact = taskData.getAttribute(BugzillaReportElement.QA_CONTACT.getKeyString()); } else { haveRealName = true; } if (qaContact != null) { Label label = createLabel(composite, qaContact); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text textField; if (qaContact.isReadOnly()) { textField = createTextField(composite, qaContact, SWT.FLAT | SWT.READ_ONLY); } else { textField = createTextField(composite, qaContact, SWT.FLAT); ContentAssistCommandAdapter adapter = applyContentAssist(textField, createContentProposalProvider(qaContact)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(qaContact); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); } GridDataFactory.fillDefaults().grab(true, false).applyTo(textField); if (haveRealName) { textField.setText(textField.getText() + " <" + taskData.getAttributeValue(BugzillaReportElement.QA_CONTACT.getKeyString()) + ">"); } } super.addSelfToCC(composite); } }
false
true
protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); // false, SWT.FLAT | SWT.SINGLE); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } }
protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } // NOTE: urlText should not be back ported to 3.3 due to background color failure attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } }
diff --git a/src/net/incredibles/brtaquiz/activity/ResultActivity.java b/src/net/incredibles/brtaquiz/activity/ResultActivity.java index 033367f..b7cf1d7 100644 --- a/src/net/incredibles/brtaquiz/activity/ResultActivity.java +++ b/src/net/incredibles/brtaquiz/activity/ResultActivity.java @@ -1,187 +1,186 @@ package net.incredibles.brtaquiz.activity; import android.app.NotificationManager; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.inject.Inject; import net.incredibles.brtaquiz.R; import net.incredibles.brtaquiz.controller.ResultController; import net.incredibles.brtaquiz.service.TimerService; import net.incredibles.brtaquiz.util.IndefiniteProgressingTask; import net.incredibles.brtaquiz.util.PieChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roboguice.activity.RoboActivity; import roboguice.inject.InjectResource; import roboguice.inject.InjectView; /** * @author sharafat * @Created 2/21/12 9:49 PM */ public class ResultActivity extends RoboActivity { private static final Logger LOG = LoggerFactory.getLogger(ResultActivity.class); @InjectView(R.id.total_questions) private TextView totalQuestionsTextView; @InjectView(R.id.answered) private TextView answeredTextView; @InjectView(R.id.correct) private TextView correctTextView; @InjectView(R.id.incorrect) private TextView incorrectTextView; @InjectView(R.id.unanswered) private TextView unansweredTextView; @InjectView(R.id.total_time) private TextView totalTimeTextView; @InjectView(R.id.time_taken) private TextView timeTakenTextView; @InjectView(R.id.detailed_result_btn) private Button detailedResultBtn; @InjectView(R.id.show_chart_btn) private Button showChartBtn; @InjectView(R.id.quit_btn) private Button quitBtn; @InjectResource(R.string.preparing_result) private String preparingResult; @InjectResource(R.string.result) private String result; @InjectResource(R.string.correct) private String correct; @InjectResource(R.string.incorrect) private String incorrect; @InjectResource(R.string.unanswered) private String unanswered; @Inject NotificationManager notificationManager; @Inject private ResultController resultController; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); notificationManager.cancel(TimerService.SERVICE_ID); boolean resultAlreadySaved = getIntent().getBooleanExtra(LoginActivity.KEY_RESULT_ALREADY_SAVED, false); new PrepareResultTask(resultAlreadySaved).execute(); setContentView(R.layout.result); setButtonClickHandlers(); } private void updateUI() { totalQuestionsTextView.setText(Integer.toString(resultController.getTotalQuestions())); answeredTextView.setText(Integer.toString(resultController.getAnswered())); correctTextView.setText(Integer.toString(resultController.getCorrect())); incorrectTextView.setText(Integer.toString(resultController.getIncorrect())); unansweredTextView.setText(Integer.toString(resultController.getUnanswered())); totalTimeTextView.setText(resultController.getTotalTime()); timeTakenTextView.setText(resultController.getTimeTaken()); } private void setButtonClickHandlers() { detailedResultBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ResultActivity.this, ResultDetailsActivity.class)); } }); showChartBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int[] colors = new int[]{Color.GREEN, Color.RED, Color.YELLOW}; String[] computingParameters = new String[]{correct, incorrect, unanswered}; double[] pieValues = {resultController.getCorrect(), resultController.getIncorrect(), resultController.getUnanswered()}; PieChart pieChart = new PieChart(); pieChart.setChartValues(pieValues); pieChart.setChartColors(colors); pieChart.setCOMPUTING_PARAMETER(computingParameters); pieChart.setGraphTitle(result); - //TODO: Correct classCastException problem and uncomment the following -// startActivity(pieChart.execute(ResultActivity.this)); + startActivity(pieChart.execute(ResultActivity.this)); } }); quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showLauncherScreen(); finish(); } }); } private void showLauncherScreen() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private class PrepareResultTask extends IndefiniteProgressingTask<Void> { public PrepareResultTask(final boolean resultAlreadySaved) { super(ResultActivity.this, preparingResult, new OnTaskExecutionListener<Void>() { @Override public Void execute() { resultController.prepareResult(resultAlreadySaved); return null; } @Override public void onSuccess(Void result) { updateUI(); } @Override public void onException(Exception e) { LOG.error("Error while preparing result", e); throw new RuntimeException(e); } }); } } /** * The primary purpose is to prevent systems before android.os.Build.VERSION_CODES.ECLAIR * from calling their default KeyEvent.KEYCODE_BACK during onKeyDown. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR return true; } return super.onKeyDown(keyCode, event); } /** Overrides the default implementation for KeyEvent.KEYCODE_BACK so that all systems call onBackPressed(). */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { onBackPressed(); return true; } return super.onKeyUp(keyCode, event); } /** If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and add this method. */ private void onBackPressed() { //Do nothing... } } diff --git a/src/net/incredibles/brtaquiz/util/PieChart.java b/src/net/incredibles/brtaquiz/util/PieChart.java index 73a1615..e9385aa 100644 --- a/src/net/incredibles/brtaquiz/util/PieChart.java +++ b/src/net/incredibles/brtaquiz/util/PieChart.java @@ -1,94 +1,94 @@ package net.incredibles.brtaquiz.util; import org.achartengine.ChartFactory; import org.achartengine.model.CategorySeries; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.SimpleSeriesRenderer; import android.content.Context; import android.content.Intent; public class PieChart { private double[] chartValues; private int[] chartColors; private String[] COMPUTING_PARAMETER; private String graphTitle; public double[] getChartValues() { return chartValues; } public void setChartValues(double[] chartValues) { this.chartValues = chartValues; } public int[] getChartColors() { return chartColors; } public void setChartColors(int[] chartColors) { this.chartColors = chartColors; } public String[] getCOMPUTING_PARAMETER() { return COMPUTING_PARAMETER; } public void setCOMPUTING_PARAMETER(String[] cOMPUTING_PARAMETER) { COMPUTING_PARAMETER = cOMPUTING_PARAMETER; } public String getGraphTitle() { return graphTitle; } public void setGraphTitle(String graphTitle) { this.graphTitle = graphTitle; } public DefaultRenderer buildCategoryRenderer(int[] colors) { DefaultRenderer renderer = new DefaultRenderer(); renderer.setLabelsTextSize(15); renderer.setLegendTextSize(15); renderer.setMargins(new int[] { 20, 30, 15, 0 }); for (int color : colors) { SimpleSeriesRenderer r = new SimpleSeriesRenderer(); r.setColor(color); renderer.addSeriesRenderer(r); } return renderer; } /** * Builds a category series using the provided values. * - * @param titles the series titles + * @param title the series titles * @param values the values * @return the category series */ public CategorySeries buildCategoryDataset(String title, double[] values, String[] graphTitles) { CategorySeries series = new CategorySeries(title); int k = 0; for (double value : values) { series.add(graphTitles[k++], value); } return series; } /** * Executes the chart demo. * * @param context the context * @return the built intent */ public Intent execute(Context context) { DefaultRenderer renderer = buildCategoryRenderer(chartColors); renderer.setZoomButtonsVisible(true); renderer.setZoomEnabled(true); renderer.setChartTitleTextSize(20); return ChartFactory.getPieChartIntent(context, buildCategoryDataset(graphTitle, chartValues, COMPUTING_PARAMETER), renderer, graphTitle); } }
false
false
null
null
diff --git a/src/wordcram/BBTree.java b/src/wordcram/BBTree.java index 5beb54d..c8bcb62 100644 --- a/src/wordcram/BBTree.java +++ b/src/wordcram/BBTree.java @@ -1,145 +1,146 @@ package wordcram; import java.util.ArrayList; import processing.core.*; /* Copyright 2010 Daniel Bernier 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. */ class BBTree { private int x; private int y; private int right; private int bottom; private BBTree[] kids; private int rootX; private int rootY; + int swelling = 0; + BBTree(int x, int y, int right, int bottom) { this.x = x; this.y = y; this.right = right; this.bottom = bottom; } void addKids(BBTree... _kids) { ArrayList<BBTree> kidList = new ArrayList<BBTree>(); for (BBTree kid : _kids) { if (kid != null) { kidList.add(kid); } } kids = kidList.toArray(new BBTree[0]); } void setLocation(int x, int y) { rootX = x; rootY = y; if (!isLeaf()) { for (BBTree kid : kids) { kid.setLocation(x, y); } } } boolean overlaps(BBTree otherTree) { if (rectCollide(this, otherTree)) { if (this.isLeaf() && otherTree.isLeaf()) { return true; } else if (this.isLeaf()) { // Then otherTree isn't a leaf. for (BBTree otherKid : otherTree.kids) { if (this.overlaps(otherKid)) { return true; } } } else { for (BBTree myKid : this.kids) { if (otherTree.overlaps(myKid)) { return true; } } } } return false; } private int[] getPoints() { return new int[] { rootX - swelling + x, rootY - swelling + y, rootX + swelling + right, rootY + swelling + bottom }; } private boolean rectCollide(BBTree aTree, BBTree bTree) { int[] a = aTree.getPoints(); int[] b = bTree.getPoints(); return a[3] > b[1] && a[1] < b[3] && a[2] > b[0] && a[0] < b[2]; } boolean containsPoint(float x, float y) { - return this.rootX + this.x < x && - this.rootX + this.right > x && - this.rootY + this.y < y && - this.rootY + this.bottom > y; + return this.rootX + this.x < x && + this.rootX + this.right > x && + this.rootY + this.y < y && + this.rootY + this.bottom > y; } boolean isLeaf() { return kids == null; } - int swelling = 0; void swell(int extra) { swelling += extra; if (!isLeaf()) { for (int i = 0; i < kids.length; i++) { kids[i].swell(extra); } } } void draw(PGraphics g) { g.pushStyle(); g.noFill(); g.stroke(30, 255, 255, 50); drawLeaves(g); g.popStyle(); } private void drawLeaves(PGraphics g) { if (this.isLeaf()) { drawBounds(g, getPoints()); } else { for (int i = 0; i < kids.length; i++) { kids[i].drawLeaves(g); } } } private void drawBounds(PGraphics g, int[] rect) { g.rect(rect[0], rect[1], rect[2], rect[3]); } }
false
false
null
null
diff --git a/Factory/src/factory/graphics/AnimatedObject.java b/Factory/src/factory/graphics/AnimatedObject.java index 742ab83..79f57fa 100644 --- a/Factory/src/factory/graphics/AnimatedObject.java +++ b/Factory/src/factory/graphics/AnimatedObject.java @@ -1,117 +1,88 @@ package factory.graphics; -import GraphicItem; import java.awt.Image; import java.awt.Toolkit; import java.util.ArrayList; class AnimatedObject { protected int x, y; // current position protected int dx, dy; // change in position protected int theta; // image angle protected int dtheta; // change in image angle protected int imageWidth, imageHeight; // image size protected Image image; protected ArrayList<GraphicItem> items; // inventory of items // Constructors public AnimatedObject() { } public AnimatedObject(int init_x, int init_y, int init_theta, int init_dx, int init_dy, int init_dtheta, int init_imageWidth, int init_imageHeight, String init_imagePath) { x = init_x; y = init_y; theta = init_theta; dx = init_dx; dy = init_dy; dtheta = init_dtheta; imageWidth = init_imageWidth; imageHeight = init_imageHeight; image = Toolkit.getDefaultToolkit().getImage(init_imagePath); } // Set functions public void setPosition(int init_x, int init_y) { x = init_x; y = init_y; } public void setSpeed(int init_dx, int init_dy) { dx = init_dx; dy = init_dy; } public void setImage(String imagePath) { image = Toolkit.getDefaultToolkit().getImage(imagePath); } public void setAngle(int init_theta) { theta = init_theta; } // Get functions public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public int getAngle() { return theta; } public int getImageWidth() { return imageWidth; } public int getImageHeight() { return imageHeight; } - public void addItem(GraphicItem newItem) - { - items.add(newItem); - } - public void clearItems() - { - items.clear(); - } - public boolean hasItem() - { - if(items.size() >= 1) - return true; - else - return false; - } - public GraphicItem popItem() - { - GraphicItem lastItem = items.get(items.size()-1); // get last item - items.remove(items.size()-1); // remove last item - return lastItem; // return last item - } - public int getSize() - { - return items.size(); - } - public GraphicItem getItemAt(int i) - { - return items.get(i); - } + // Update functions public void move() { x += dx; y += dy; theta += dtheta; } } \ No newline at end of file
false
false
null
null
diff --git a/src/share/org/apache/struts/taglib/html/MessagesTag.java b/src/share/org/apache/struts/taglib/html/MessagesTag.java index 2b2b1e2b5..ace09c821 100644 --- a/src/share/org/apache/struts/taglib/html/MessagesTag.java +++ b/src/share/org/apache/struts/taglib/html/MessagesTag.java @@ -1,363 +1,350 @@ /* - * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/taglib/html/MessagesTag.java,v 1.21 2003/08/19 23:38:24 dgraham Exp $ - * $Revision: 1.21 $ - * $Date: 2003/08/19 23:38:24 $ + * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/taglib/html/MessagesTag.java,v 1.22 2003/09/09 03:49:29 rleland Exp $ + * $Revision: 1.22 $ + * $Date: 2003/09/09 03:49:29 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Struts", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.struts.taglib.html; import java.util.Iterator; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.Globals; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.taglib.TagUtils; import org.apache.struts.util.MessageResources; /** * Custom tag that iterates the elements of a message collection. * It defaults to retrieving the messages from <code>Globals.ERROR_KEY</code>, * but if the message attribute is set to true then the messages will be * retrieved from <code>Globals.MESSAGE_KEY</code>. This is an alternative * to the default <code>ErrorsTag</code>. * * @author David Winterfeldt - * @version $Revision: 1.21 $ $Date: 2003/08/19 23:38:24 $ + * @version $Revision: 1.22 $ $Date: 2003/09/09 03:49:29 $ * @since Struts 1.1 */ public class MessagesTag extends BodyTagSupport { /** * The message resources for this package. */ protected static MessageResources messageResources = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** - * Commons Logging instance. - */ - private static final Log log = LogFactory.getLog(MessagesTag.class); - - /** * Iterator of the elements of this error collection, while we are actually * running. */ protected Iterator iterator = null; /** * Whether or not any error messages have been processed. */ protected boolean processed = false; /** * The name of the scripting variable to be exposed. */ protected String id = null; /** * The servlet context attribute key for our resources. */ protected String bundle = null; /** * The session attribute key for our locale. */ protected String locale = Globals.LOCALE_KEY; /** * The request attribute key for our error messages (if any). */ protected String name = Globals.ERROR_KEY; /** * The name of the property for which error messages should be returned, * or <code>null</code> to return all errors. */ protected String property = null; /** * The message resource key for errors header. */ protected String header = null; /** * The message resource key for errors footer. */ protected String footer = null; /** * If this is set to 'true', then the <code>Globals.MESSAGE_KEY</code> will * be used to retrieve the messages from scope. */ protected String message = null; public String getId() { return (this.id); } public void setId(String id) { this.id = id; } public String getBundle() { return (this.bundle); } public void setBundle(String bundle) { this.bundle = bundle; } public String getLocale() { return (this.locale); } public void setLocale(String locale) { this.locale = locale; } public String getName() { return (this.name); } public void setName(String name) { this.name = name; } public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } public String getHeader() { return (this.header); } public void setHeader(String header) { this.header = header; } public String getFooter() { return (this.footer); } public void setFooter(String footer) { this.footer = footer; } public String getMessage() { return (this.message); } public void setMessage(String message) { this.message = message; } /** * Construct an iterator for the specified collection, and begin * looping through the body once per element. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { // Initialize for a new request. processed = false; // Were any messages specified? ActionMessages messages = null; // Make a local copy of the name attribute that we can modify. String name = this.name; if (message != null && "true".equalsIgnoreCase(message)) { name = Globals.MESSAGE_KEY; } try { messages = TagUtils.getInstance().getActionMessages(pageContext, name); } catch (JspException e) { TagUtils.getInstance().saveException(pageContext, e); throw e; } // Acquire the collection we are going to iterate over this.iterator = (property == null) ? messages.get() : messages.get(property); // Store the first value and evaluate, or skip the body if none if (!this.iterator.hasNext()) { return SKIP_BODY; } ActionMessage report = (ActionMessage) this.iterator.next(); String msg = TagUtils.getInstance().message( pageContext, bundle, locale, report.getKey(), report.getValues()); if (msg != null) { pageContext.setAttribute(id, msg); } else { pageContext.removeAttribute(id); - - // log missing key to ease debugging - if (log.isDebugEnabled()) { - log.debug( - messageResources.getMessage( - "messageTag.resources", - report.getKey())); - } } if (header != null && header.length() > 0) { String headerMessage = TagUtils.getInstance().message(pageContext, bundle, locale, header); if (headerMessage != null) { TagUtils.getInstance().write(pageContext, headerMessage); } } // Set the processed variable to true so the // doEndTag() knows processing took place processed = true; return (EVAL_BODY_TAG); } /** * Make the next collection element available and loop, or * finish the iterations if there are no more elements. * * @exception JspException if a JSP exception has occurred */ public int doAfterBody() throws JspException { // Render the output from this iteration to the output stream if (bodyContent != null) { TagUtils.getInstance().writePrevious(pageContext, bodyContent.getString()); bodyContent.clearBody(); } // Decide whether to iterate or quit if (iterator.hasNext()) { ActionMessage report = (ActionMessage) iterator.next(); String msg = TagUtils.getInstance().message( pageContext, bundle, locale, report.getKey(), report.getValues()); pageContext.setAttribute(id, msg); return (EVAL_BODY_TAG); } else { return (SKIP_BODY); } } /** * Clean up after processing this enumeration. * * @exception JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { if (processed && footer != null && footer.length() > 0) { String footerMessage = TagUtils.getInstance().message(pageContext, bundle, locale, footer); if (footerMessage != null) { TagUtils.getInstance().write(pageContext, footerMessage); } } return EVAL_PAGE; } /** * Release all allocated resources. */ public void release() { super.release(); iterator = null; processed = false; id = null; bundle = null; locale = Globals.LOCALE_KEY; name = Globals.ERROR_KEY; property = null; header = null; footer = null; message = null; } }
false
false
null
null
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/ui/OverviewActivity.java b/SeriesGuide/src/com/battlelancer/seriesguide/ui/OverviewActivity.java index 5da36f686..2d38b75a4 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/ui/OverviewActivity.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/ui/OverviewActivity.java @@ -1,221 +1,233 @@ /* * Copyright 2011 Uwe Trottmann * * 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.battlelancer.seriesguide.ui; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.View; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.MenuItem; import com.battlelancer.seriesguide.adapters.TabPagerAdapter; import com.battlelancer.seriesguide.items.Series; import com.battlelancer.seriesguide.util.DBUtils; import com.battlelancer.seriesguide.util.TaskManager; import com.battlelancer.seriesguide.util.UpdateTask; import com.battlelancer.seriesguide.util.Utils; import com.battlelancer.thetvdbapi.TheTVDB; import com.google.analytics.tracking.android.EasyTracker; import com.uwetrottmann.seriesguide.R; /** * Hosts an {@link OverviewFragment}. */ public class OverviewActivity extends BaseActivity { private int mShowId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.overview); mShowId = getIntent().getIntExtra(OverviewFragment.InitBundle.SHOW_TVDBID, -1); if (mShowId == -1) { finish(); return; } final ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(getString(R.string.description_overview)); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // look if we are on a multi-pane or single-pane layout... View pagerView = findViewById(R.id.pager); if (pagerView != null && pagerView.getVisibility() == View.VISIBLE) { + // clear up left-over fragments from multi-pane layout + findAndRemoveFragment(R.id.fragment_overview); + findAndRemoveFragment(R.id.fragment_seasons); + // ...single pane layout with view pager ViewPager pager = (ViewPager) pagerView; // setup action bar tabs actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); TabPagerAdapter tabsAdapter = new TabPagerAdapter(getSupportFragmentManager(), this, actionBar, pager, getMenu()); tabsAdapter.addTab(R.string.description_overview, OverviewFragment.class, getIntent() .getExtras()); Bundle args = new Bundle(); args.putInt(SeasonsFragment.InitBundle.SHOW_TVDBID, mShowId); tabsAdapter.addTab(R.string.seasons, SeasonsFragment.class, args); } else { + // FIXME: crashes if coming from single-pane layout due to left-over fragments // ...multi-pane overview and seasons fragment if (savedInstanceState == null) { Fragment overviewFragment = OverviewFragment.newInstance(mShowId); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out); ft.replace(R.id.fragment_overview, overviewFragment); ft.commit(); Fragment seasonsFragment = SeasonsFragment.newInstance(mShowId); FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction(); ft2.setCustomAnimations(R.anim.fade_in, R.anim.fade_out); ft2.replace(R.id.fragment_seasons, seasonsFragment); ft2.commit(); } } // if (AndroidUtils.isICSOrHigher()) { // // register for Android Beam // mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // if (mNfcAdapter != null) { // mNfcAdapter.setNdefPushMessageCallback(this, this); // } // } // try to update this show onUpdate(); } + private void findAndRemoveFragment(int fragmentId) { + Fragment overviewFragment = getSupportFragmentManager().findFragmentById(fragmentId); + if (overviewFragment != null) { + getSupportFragmentManager().beginTransaction().remove(overviewFragment).commit(); + } + } + @Override protected void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); } @Override protected void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.shrink_enter, R.anim.shrink_exit); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent upIntent = new Intent(this, ShowsActivity.class); upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(upIntent); overridePendingTransition(R.anim.shrink_enter, R.anim.shrink_exit); return true; } return super.onOptionsItemSelected(item); } private void onUpdate() { // only update this show if no global update is running and we have a // connection if (!TaskManager.getInstance(this).isUpdateTaskRunning(false) && Utils.isAllowedConnection(this)) { final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); // check if auto-update is enabled final boolean isAutoUpdateEnabled = prefs.getBoolean( SeriesGuidePreferences.KEY_AUTOUPDATE, true); if (isAutoUpdateEnabled) { final String showId = String.valueOf(mShowId); boolean isTime = TheTVDB.isUpdateShow(showId, System.currentTimeMillis(), this); // look if we need to update if (isTime) { final Context context = getApplicationContext(); Handler handler = new Handler(); Runnable r = new Runnable() { @Override public void run() { UpdateTask updateTask = new UpdateTask(showId, context); TaskManager.getInstance(context).tryUpdateTask(updateTask, false, -1); } }; handler.postDelayed(r, 1000); } } } } @Override public boolean onSearchRequested() { // refine search with the show's title final Series show = DBUtils.getShow(this, String.valueOf(mShowId)); final String showTitle = show.getTitle(); Bundle args = new Bundle(); args.putString(SearchFragment.InitBundle.SHOW_TITLE, showTitle); startSearch(null, false, args, false); return true; } // @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // @Override // public NdefMessage createNdefMessage(NfcEvent event) { // final Series show = DBUtils.getShow(this, String.valueOf(mShowId)); // // send id, also title and overview (both can be empty) // NdefMessage msg = new NdefMessage(new NdefRecord[] { // createMimeRecord( // "application/com.battlelancer.seriesguide.beam", String.valueOf(mShowId) // .getBytes()), // createMimeRecord("application/com.battlelancer.seriesguide.beam", // show.getTitle() // .getBytes()), // createMimeRecord("application/com.battlelancer.seriesguide.beam", show // .getOverview() // .getBytes()) // }); // return msg; // } // // /** // * Creates a custom MIME type encapsulated in an NDEF record // * // * @param mimeType // */ // @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // public NdefRecord createMimeRecord(String mimeType, byte[] payload) { // byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII")); // NdefRecord mimeRecord = new NdefRecord( // NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload); // return mimeRecord; // } }
false
false
null
null
diff --git a/src/main/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java b/src/main/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java index d11a2bbe5..8c8a168d9 100644 --- a/src/main/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java +++ b/src/main/java/org/apache/commons/math/distribution/AbstractIntegerDistribution.java @@ -1,331 +1,331 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.exception.OutOfRangeException; import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.random.RandomDataImpl; import org.apache.commons.math.util.FastMath; /** * Base class for integer-valued discrete distributions. Default * implementations are provided for some of the methods that do not vary * from distribution to distribution. * * @version $Id$ */ public abstract class AbstractIntegerDistribution extends AbstractDistribution implements IntegerDistribution, Serializable { /** Serializable version identifier */ private static final long serialVersionUID = -1146319659338487221L; /** * RandomData instance used to generate samples from the distribution. * @since 2.2 */ protected final RandomDataImpl randomData = new RandomDataImpl(); /** * Default constructor. */ protected AbstractIntegerDistribution() {} /** * For a random variable {@code X} whose values are distributed according * to this distribution, this method returns {@code P(X < x)}. In other * words, this method represents the (cumulative) distribution function, * or CDF, for this distribution. * If {@code x} does not represent an integer value, the CDF is * evaluated at the greatest integer less than {@code x}. * * @param x Value at which the distribution function is evaluated. * @return the cumulative probability that a random variable with this * distribution takes a value less than or equal to {@code x}. * @throws MathException if the cumulative probability can not be * computed due to convergence or other numerical errors. */ public double cumulativeProbability(double x) throws MathException { return cumulativeProbability((int) FastMath.floor(x)); } /** * For a random variable {@code X} whose values are distributed * according to this distribution, this method returns * {@code P(x0 < X < x1)}. * * @param x0 Inclusive lower bound. * @param x1 Inclusive upper bound. * @return the probability that a random variable with this distribution * will take a value between {@code x0} and {@code x1}, * including the endpoints. * @throws MathException if the cumulative probability can not be * computed due to convergence or other numerical errors. * @throws NumberIsTooSmallException if {@code x1 > x0}. */ @Override public double cumulativeProbability(double x0, double x1) throws MathException { if (x1 < x0) { throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x1, x0, true); } if (FastMath.floor(x0) < x0) { return cumulativeProbability(((int) FastMath.floor(x0)) + 1, (int) FastMath.floor(x1)); // don't want to count mass below x0 } else { // x0 is mathematical integer, so use as is return cumulativeProbability((int) FastMath.floor(x0), (int) FastMath.floor(x1)); } } /** * For a random variable {@code X} whose values are distributed according * to this distribution, this method returns {@code P(X < x)}. In other * words, this method represents the probability distribution function, * or PDF, for this distribution. * * @param x Value at which the PDF is evaluated. * @return PDF for this distribution. * @throws MathException if the cumulative probability can not be * computed due to convergence or other numerical errors. */ public abstract double cumulativeProbability(int x) throws MathException; /** * For a random variable {@code X} whose values are distributed according * to this distribution, this method returns {@code P(X = x)}. In other * words, this method represents the probability mass function, or PMF, * for the distribution. * If {@code x} does not represent an integer value, 0 is returned. * * @param x Value at which the probability density function is evaluated. * @return the value of the probability density function at {@code x}. */ public double probability(double x) { double fl = FastMath.floor(x); if (fl == x) { return this.probability((int) x); } else { return 0; } } /** * For a random variable {@code X} whose values are distributed according * to this distribution, this method returns {@code P(x0 < X < x1)}. * * @param x0 Inclusive lower bound. * @param x1 Inclusive upper bound. * @return the cumulative probability. * @throws MathException if the cumulative probability can not be * computed due to convergence or other numerical errors. * @throws NumberIsTooSmallException {@code if x0 > x1}. */ public double cumulativeProbability(int x0, int x1) throws MathException { if (x1 < x0) { throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x1, x0, true); } return cumulativeProbability(x1) - cumulativeProbability(x0 - 1); } /** * For a random variable {@code X} whose values are distributed according * to this distribution, this method returns the largest {@code x}, such - * that {@code P(X < x) < p}. + * that {@code P(X <= x) <= p}. * * @param p Desired probability. * @return the largest {@code x} such that {@code P(X < x) <= p}. * @throws MathException if the inverse cumulative probability can not be * computed due to convergence or other numerical errors. * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}. */ public int inverseCumulativeProbability(final double p) throws MathException{ if (p < 0 || p > 1) { throw new OutOfRangeException(p, 0, 1); } // by default, do simple bisection. // subclasses can override if there is a better method. int x0 = getDomainLowerBound(p); int x1 = getDomainUpperBound(p); double pm; while (x0 < x1) { int xm = x0 + (x1 - x0) / 2; pm = checkedCumulativeProbability(xm); if (pm > p) { // update x1 if (xm == x1) { // this can happen with integer division // simply decrement x1 --x1; } else { // update x1 normally x1 = xm; } } else { // update x0 if (xm == x0) { // this can happen with integer division // simply increment x0 ++x0; } else { // update x0 normally x0 = xm; } } } // insure x0 is the correct critical point pm = checkedCumulativeProbability(x0); while (pm > p) { --x0; pm = checkedCumulativeProbability(x0); } return x0; } /** * {@inheritDoc} */ public void reseedRandomGenerator(long seed) { randomData.reSeed(seed); } /** * Generates a random value sampled from this distribution. The default * implementation uses the * <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling"> * inversion method. * </a> * * @return a random value. * @since 2.2 * @throws MathException if an error occurs generating the random value. */ public int sample() throws MathException { return randomData.nextInversionDeviate(this); } /** * Generates a random sample from the distribution. The default * implementation generates the sample by calling {@link #sample()} * in a loop. * * @param sampleSize number of random values to generate. * @since 2.2 * @return an array representing the random sample. * @throws MathException if an error occurs generating the sample. * @throws NotStrictlyPositiveException if {@code sampleSize <= 0}. */ public int[] sample(int sampleSize) throws MathException { if (sampleSize <= 0) { throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize); } int[] out = new int[sampleSize]; for (int i = 0; i < sampleSize; i++) { out[i] = sample(); } return out; } /** * Computes the cumulative probability function and checks for NaN * values returned. * Throws MathException if the value is NaN. Rethrows any MathException encountered * evaluating the cumulative probability function. Throws * MathException if the cumulative probability function returns NaN. * * @param argument Input value. * @return the cumulative probability. * @throws MathException if the cumulative probability is NaN */ private double checkedCumulativeProbability(int argument) throws MathException { double result = Double.NaN; result = cumulativeProbability(argument); if (Double.isNaN(result)) { throw new MathException(LocalizedFormats.DISCRETE_CUMULATIVE_PROBABILITY_RETURNED_NAN, argument); } return result; } /** * Access the domain value lower bound, based on {@code p}, used to * bracket a PDF root. This method is used by * {@link #inverseCumulativeProbability(double)} to find critical values. * * @param p Desired probability for the critical value * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}. */ protected abstract int getDomainLowerBound(double p); /** * Access the domain value upper bound, based on {@code p}, used to * bracket a PDF root. This method is used by * {@link #inverseCumulativeProbability(double)} to find critical values. * * @param p Desired probability for the critical value. * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}. */ protected abstract int getDomainUpperBound(double p); /** * Access the lower bound of the support. * * @return lower bound of the support (Integer.MIN_VALUE for negative infinity) */ public abstract int getSupportLowerBound(); /** * Access the upper bound of the support. * * @return upper bound of the support (Integer.MAX_VALUE for positive infinity) */ public abstract int getSupportUpperBound(); /** * Use this method to get information about whether the lower bound * of the support is inclusive or not. For discrete support, * only true here is meaningful. * * @return true (always but at Integer.MIN_VALUE because of the nature of discrete support) */ @Override public boolean isSupportLowerBoundInclusive() { return true; } /** * Use this method to get information about whether the upper bound * of the support is inclusive or not. For discrete support, * only true here is meaningful. * * @return true (always but at Integer.MAX_VALUE because of the nature of discrete support) */ @Override public boolean isSupportUpperBoundInclusive() { return true; } }
true
false
null
null
diff --git a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/AbstractApplicationConfigurationSource.java b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/AbstractApplicationConfigurationSource.java index 714875b3a..6195e3cbb 100644 --- a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/AbstractApplicationConfigurationSource.java +++ b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/AbstractApplicationConfigurationSource.java @@ -1,164 +1,163 @@ /** * Sonatype Nexus (TM) Open Source Version. * Copyright (c) 2008 Sonatype, Inc. All rights reserved. * Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html * This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License Version 3 for more details. * You should have received a copy of the GNU General Public License Version 3 along with this program. * If not, see http://www.gnu.org/licenses/. * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. * "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc. */ package org.sonatype.nexus.configuration.source; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.interpolation.InterpolatorFilterReader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.sonatype.configuration.ConfigurationException; import org.sonatype.nexus.configuration.model.Configuration; import org.sonatype.nexus.configuration.model.io.xpp3.NexusConfigurationXpp3Reader; import org.sonatype.nexus.configuration.model.io.xpp3.NexusConfigurationXpp3Writer; import org.sonatype.nexus.util.ApplicationInterpolatorProvider; /** * Abstract class that encapsulates Modello model loading and saving with interpolation. * * @author cstamas */ public abstract class AbstractApplicationConfigurationSource extends AbstractConfigurationSource implements ApplicationConfigurationSource { /** * The application interpolation provider. */ @Requirement private ApplicationInterpolatorProvider interpolatorProvider; /** The configuration. */ private Configuration configuration; public Configuration getConfiguration() { return configuration; } public void setConfiguration( Configuration configuration ) { this.configuration = configuration; } /** * Called by subclasses when loaded configuration is rejected for some reason. */ protected void rejectConfiguration( String message, Throwable e ) { this.configuration = null; if ( message != null ) { getLogger().warn( message, e ); } } /** * Load configuration. * * @param file the file * @return the configuration * @throws IOException Signals that an I/O exception has occurred. */ protected void loadConfiguration( InputStream is ) - throws IOException + throws IOException, + ConfigurationException { setConfigurationUpgraded( false ); Reader fr = null; try { NexusConfigurationXpp3Reader reader = new NexusConfigurationXpp3Reader(); fr = new InputStreamReader( is ); InterpolatorFilterReader ip = new InterpolatorFilterReader( fr, interpolatorProvider.getInterpolator() ); // read again with interpolation configuration = reader.read( ip ); } catch ( XmlPullParserException e ) { - rejectConfiguration( "Nexus configuration file was not loaded, it has the wrong structure.", e ); + configuration = null; - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "Nexus.xml is broken:", e ); + throw new ConfigurationException( "Nexus configuration file was not loaded, it has the wrong structure.", e ); } - } finally { if ( fr != null ) { fr.close(); } } // check the model version if loaded if ( configuration != null && !Configuration.MODEL_VERSION.equals( configuration.getVersion() ) ) { rejectConfiguration( "Nexus configuration file was loaded but discarded, it has the wrong version number.", null ); } if ( getConfiguration() != null ) { getLogger().info( "Configuration loaded succesfully." ); } } /** * Save configuration. * * @param file the file * @throws IOException Signals that an I/O exception has occurred. */ protected void saveConfiguration( OutputStream os, Configuration configuration ) throws IOException { Writer fw = null; try { fw = new OutputStreamWriter( os ); NexusConfigurationXpp3Writer writer = new NexusConfigurationXpp3Writer(); writer.write( fw, configuration ); } finally { if ( fw != null ) { fw.flush(); fw.close(); } } } /** * Returns the default source of ConfigurationSource. May be null. */ public ApplicationConfigurationSource getDefaultsSource() { return null; } } diff --git a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/FileConfigurationSource.java b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/FileConfigurationSource.java index 5d7aa1814..b870299de 100644 --- a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/FileConfigurationSource.java +++ b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/source/FileConfigurationSource.java @@ -1,339 +1,343 @@ /** * Sonatype Nexus (TM) Open Source Version. * Copyright (c) 2008 Sonatype, Inc. All rights reserved. * Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html * This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License Version 3 for more details. * You should have received a copy of the GNU General Public License Version 3 along with this program. * If not, see http://www.gnu.org/licenses/. * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. * "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc. */ package org.sonatype.nexus.configuration.source; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.sonatype.configuration.ConfigurationException; import org.sonatype.configuration.validation.InvalidConfigurationException; import org.sonatype.configuration.validation.ValidationRequest; import org.sonatype.configuration.validation.ValidationResponse; import org.sonatype.nexus.configuration.application.upgrade.ApplicationConfigurationUpgrader; import org.sonatype.nexus.configuration.model.Configuration; import org.sonatype.nexus.configuration.model.ConfigurationHelper; import org.sonatype.nexus.configuration.validator.ApplicationConfigurationValidator; import org.sonatype.nexus.configuration.validator.ConfigurationValidator; import org.sonatype.plexus.appevents.ApplicationEventMulticaster; import org.sonatype.security.events.SecurityConfigurationChangedEvent; /** * The default configuration source powered by Modello. It will try to load configuration, upgrade if needed and * validate it. It also holds the one and only existing Configuration object. * * @author cstamas */ @Component( role = ApplicationConfigurationSource.class, hint = "file" ) public class FileConfigurationSource extends AbstractApplicationConfigurationSource { /** * The configuration file. */ @org.codehaus.plexus.component.annotations.Configuration( value = "${nexus-work}/conf/nexus.xml" ) private File configurationFile; /** * The configuration validator. */ @Requirement private ApplicationConfigurationValidator configurationValidator; /** * The configuration upgrader. */ @Requirement private ApplicationConfigurationUpgrader configurationUpgrader; /** * The nexus defaults configuration source. */ @Requirement( hint = "static" ) private ApplicationConfigurationSource nexusDefaults; @Requirement private ApplicationEventMulticaster eventMulticaster; @Requirement private ConfigurationHelper configHelper; /** Flag to mark defaulted config */ private boolean configurationDefaulted; /** * Gets the configuration validator. * * @return the configuration validator */ public ConfigurationValidator getConfigurationValidator() { return configurationValidator; } /** * Sets the configuration validator. * * @param configurationValidator the new configuration validator */ public void setConfigurationValidator( ConfigurationValidator configurationValidator ) { if ( !ApplicationConfigurationValidator.class.isAssignableFrom( configurationValidator.getClass() ) ) { throw new IllegalArgumentException( "ConfigurationValidator is invalid type " + configurationValidator.getClass().getName() ); } this.configurationValidator = (ApplicationConfigurationValidator) configurationValidator; } /** * Gets the configuration file. * * @return the configuration file */ public File getConfigurationFile() { return configurationFile; } /** * Sets the configuration file. * * @param configurationFile the new configuration file */ public void setConfigurationFile( File configurationFile ) { this.configurationFile = configurationFile; } public Configuration loadConfiguration() throws ConfigurationException, IOException { // propagate call and fill in defaults too nexusDefaults.loadConfiguration(); if ( getConfigurationFile() == null || getConfigurationFile().getAbsolutePath().contains( "${" ) ) { throw new ConfigurationException( "The configuration file is not set or resolved properly: " + getConfigurationFile().getAbsolutePath() ); } if ( !getConfigurationFile().exists() ) { getLogger().warn( "No configuration file in place, copying the default one and continuing with it." ); // get the defaults and stick it to place setConfiguration( nexusDefaults.getConfiguration() ); saveConfiguration( getConfigurationFile() ); configurationDefaulted = true; } else { configurationDefaulted = false; } + try + { loadConfiguration( getConfigurationFile() ); - - // check for loaded model - if ( getConfiguration() == null ) + } + catch ( ConfigurationException e ) { + getLogger().info( "Configuration file is invalid, attempting upgrade" ); + upgradeConfiguration( getConfigurationFile() ); loadConfiguration( getConfigurationFile() ); // if the configuration is upgraded we need to reload the security. // it would be great if this was put somewhere else, but I am out of ideas. // the problem is the default security was already loaded with the security-system component was loaded // so it has the defaults, the upgrade from 1.0.8 -> 1.4 moves security out of the nexus.xml // and we cannot use the 'correct' way of updating the info, because that would cause an infinit loop loading the nexus.xml this.eventMulticaster.notifyEventListeners( new SecurityConfigurationChangedEvent( null ) ); } ValidationResponse vResponse = getConfigurationValidator().validateModel( new ValidationRequest( getConfiguration() ) ); setValidationResponse( vResponse ); if ( vResponse.isValid() ) { if ( vResponse.isModified() ) { getLogger().info( "Validation has modified the configuration, storing the changes." ); storeConfiguration(); } return getConfiguration(); } else { throw new InvalidConfigurationException( vResponse ); } } public void storeConfiguration() throws IOException { saveConfiguration( getConfigurationFile() ); } public InputStream getConfigurationAsStream() throws IOException { return new FileInputStream( getConfigurationFile() ); } public ApplicationConfigurationSource getDefaultsSource() { return nexusDefaults; } protected void upgradeConfiguration( File file ) throws IOException, ConfigurationException { getLogger().info( "Trying to upgrade the configuration file " + file.getAbsolutePath() ); setConfiguration( configurationUpgrader.loadOldConfiguration( file ) ); // after all we should have a configuration if ( getConfiguration() == null ) { throw new ConfigurationException( "Could not upgrade Nexus configuration! Please replace the " + file.getAbsolutePath() + " file with a valid Nexus configuration file." ); } getLogger().info( "Creating backup from the old file and saving the upgraded configuration." ); // backup the file File backup = new File( file.getParentFile(), file.getName() + ".bak" ); FileUtils.copyFile( file, backup ); // set the upgradeInstance to warn Nexus about this setConfigurationUpgraded( true ); saveConfiguration( file ); } /** * Load configuration. * * @param file the file * @return the configuration * @throws IOException Signals that an I/O exception has occurred. */ private void loadConfiguration( File file ) - throws IOException + throws IOException, + ConfigurationException { getLogger().info( "Loading Nexus configuration from " + file.getAbsolutePath() ); FileInputStream fis = null; try { fis = new FileInputStream( file ); loadConfiguration( fis ); // seems a bit dirty, but the config might need to be upgraded. if( this.getConfiguration() != null ) { // decrypt the passwords configHelper.encryptDecryptPasswords( this.getConfiguration(), false ); } } finally { if ( fis != null ) { fis.close(); } } } /** * Save configuration. * * @param file the file * @throws IOException Signals that an I/O exception has occurred. */ private void saveConfiguration( File file ) throws IOException { FileOutputStream fos = null; File backupFile = new File( file.getParentFile(), file.getName() + ".old" ); try { // Create the dir if doesn't exist, throw runtime exception on failure // bad bad bad if ( !file.getParentFile().exists() && !file.getParentFile().mkdirs() ) { String message = "\r\n******************************************************************************\r\n" + "* Could not create configuration file [ " + file.toString() + "]!!!! *\r\n" + "* Nexus cannot start properly until the process has read+write permissions to this folder *\r\n" + "******************************************************************************"; getLogger().fatalError( message ); } // copy the current nexus config file as file.bak if ( file.exists() ) { FileUtils.copyFile( file, backupFile ); } // Clone the conf so we can encrypt the passwords Configuration copyOfConfig = configHelper.clone( this.getConfiguration() ); // encrypt the passwords configHelper.encryptDecryptPasswords( copyOfConfig, true ); fos = new FileOutputStream( file ); saveConfiguration( fos, copyOfConfig ); fos.flush(); } finally { IOUtil.close( fos ); } // if all went well, delete the bak file backupFile.delete(); } /** * Was the active configuration fetched from config file or from default source? True if it from default source. */ public boolean isConfigurationDefaulted() { return configurationDefaulted; } } \ No newline at end of file
false
false
null
null
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaClient.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaClient.java index 46c15ad83..a3ef8df91 100644 --- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaClient.java +++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaClient.java @@ -1,1524 +1,1525 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.security.auth.login.LoginException; import javax.swing.text.html.HTML.Tag; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.PartBase; import org.apache.commons.httpclient.methods.multipart.PartSource; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; import org.eclipse.core.net.proxy.IProxyData; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.mylyn.commons.net.AbstractWebLocation; import org.eclipse.mylyn.commons.net.AuthenticationCredentials; import org.eclipse.mylyn.commons.net.AuthenticationType; import org.eclipse.mylyn.commons.net.HtmlStreamTokenizer; import org.eclipse.mylyn.commons.net.HtmlTag; import org.eclipse.mylyn.commons.net.Policy; import org.eclipse.mylyn.commons.net.WebUtil; import org.eclipse.mylyn.commons.net.HtmlStreamTokenizer.Token; import org.eclipse.mylyn.internal.bugzilla.core.history.BugzillaTaskHistoryParser; import org.eclipse.mylyn.internal.bugzilla.core.history.TaskHistory; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.mylyn.tasks.core.RepositoryResponse; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.RepositoryResponse.ResponseKind; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper; import org.eclipse.mylyn.tasks.core.data.TaskData; import org.eclipse.mylyn.tasks.core.data.TaskDataCollector; /** * @author Mik Kersten * @author Rob Elves * @author Steffen Pingel */ public class BugzillaClient { private static final String COOKIE_BUGZILLA_LOGIN = "Bugzilla_login"; protected static final String USER_AGENT = "BugzillaConnector"; private static final int MAX_RETRIEVED_PER_QUERY = 100; private static final String QUERY_DELIMITER = "?"; private static final String KEY_ID = "id"; private static final String VAL_TRUE = "true"; private static final String KEY_CC = "cc"; private static final String POST_BUG_CGI = "/post_bug.cgi"; private static final String PROCESS_BUG_CGI = "/process_bug.cgi"; public static final int WRAP_LENGTH = 80; private static final String VAL_PROCESS_BUG = "process_bug"; private static final String KEY_FORM_NAME = "form_name"; private static final String VAL_NONE = "none"; private static final String KEY_KNOB = "knob"; // TODO change to BugzillaReportElement.ADD_COMMENT private static final String KEY_COMMENT = "comment"; private static final String KEY_SHORT_DESC = "short_desc"; // Pages with this string in the html occur when login is required //private static final String LOGIN_REQUIRED = "goaheadandlogin=1"; private static final String VALUE_CONTENTTYPEMETHOD_MANUAL = "manual"; private static final String VALUE_ISPATCH = "1"; private static final String VALUE_ACTION_INSERT = "insert"; private static final String ATTRIBUTE_CONTENTTYPEENTRY = "contenttypeentry"; private static final String ATTRIBUTE_CONTENTTYPEMETHOD = "contenttypemethod"; private static final String ATTRIBUTE_ISPATCH = "ispatch"; // private static final String CONTENT_TYPE_TEXT_HTML = "text/html"; // private static final String CONTENT_TYPE_APP_XCGI = "application/x-cgi"; private static final String CONTENT_TYPE_APP_RDF_XML = "application/rdf+xml"; private static final String CONTENT_TYPE_APP_XML = "application/xml"; private static final String CONTENT_TYPE_TEXT_XML = "text/xml"; private static final String[] VALID_CONFIG_CONTENT_TYPES = { CONTENT_TYPE_APP_RDF_XML, CONTENT_TYPE_APP_XML, CONTENT_TYPE_TEXT_XML }; private static final String ATTR_CHARSET = "charset"; private static IdleConnectionTimeoutThread idleConnectionTimeoutThread = new IdleConnectionTimeoutThread(); static { idleConnectionTimeoutThread.start(); } protected Proxy proxy = Proxy.NO_PROXY; protected String username; protected String password; protected URL repositoryUrl; protected String characterEncoding; private boolean authenticated; private final Map<String, String> configParameters; private final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); private boolean lastModifiedSupported = true; private final BugzillaLanguageSettings bugzillaLanguageSettings; private RepositoryConfiguration repositoryConfiguration; private HostConfiguration hostConfiguration; private final AbstractWebLocation location; public BugzillaClient(AbstractWebLocation location, String characterEncoding, Map<String, String> configParameters, BugzillaLanguageSettings languageSettings) throws MalformedURLException { AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (credentials != null) { this.username = credentials.getUserName(); this.password = credentials.getPassword(); } this.repositoryUrl = new URL(location.getUrl()); this.location = location; this.characterEncoding = characterEncoding; this.configParameters = configParameters; this.bugzillaLanguageSettings = languageSettings; this.proxy = location.getProxyForHost(location.getUrl(), IProxyData.HTTP_PROXY_TYPE); WebUtil.configureHttpClient(httpClient, USER_AGENT); idleConnectionTimeoutThread.addConnectionManager(httpClient.getHttpConnectionManager()); } @Override protected void finalize() throws Throwable { shutdown(); idleConnectionTimeoutThread.removeConnectionManager(httpClient.getHttpConnectionManager()); } public void validate(IProgressMonitor monitor) throws IOException, CoreException { monitor = Policy.monitorFor(monitor); GzipGetMethod method = null; try { logout(monitor); method = getConnect(repositoryUrl + "/", monitor); } finally { if (method != null) { method.releaseConnection(); } } } protected boolean hasAuthenticationCredentials() { return username != null && username.length() > 0; } private GzipGetMethod getConnect(String serverURL, IProgressMonitor monitor) throws IOException, CoreException { return connectInternal(serverURL, false, monitor); } /** * in order to provide an even better solution for bug 196056 the size of the bugzilla configuration downloaded must * be reduced. By using a cached version of the config.cgi this can reduce traffic considerably: * http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.phoenix/infra-scripts/bugzilla/?root=Technology_Project * * @param serverURL * @return a GetMethod with possibly gzip encoded response body, so caller MUST check with * "gzip".equals(method.getResponseHeader("Content-encoding") or use the utility method * getResponseBodyAsUnzippedStream(). * @throws IOException * @throws CoreException */ - private GzipGetMethod getConnectGzip(String serverURL, IProgressMonitor monitor) throws IOException, CoreException { + protected GzipGetMethod getConnectGzip(String serverURL, IProgressMonitor monitor) throws IOException, + CoreException { return connectInternal(serverURL, true, monitor); } private GzipGetMethod connectInternal(String requestURL, boolean gzip, IProgressMonitor monitor) throws IOException, CoreException { monitor = Policy.monitorFor(monitor); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); for (int attempt = 0; attempt < 2; attempt++) { // force authentication if (!authenticated && hasAuthenticationCredentials()) { authenticate(monitor); } GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(requestURL), gzip); if (requestURL.contains(QUERY_DELIMITER)) { getMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER))); } getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + characterEncoding); // Resolves bug#195113 httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); // WARNING!! Setting browser compatibility breaks Bugzilla // authentication // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // getMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); getMethod.setDoAuthentication(true); int code; try { code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor); } catch (IOException e) { getMethod.getResponseBodyNoop(); getMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e)); } if (code == HttpURLConnection.HTTP_OK) { return getMethod; } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { getMethod.getResponseBodyNoop(); // login or reauthenticate due to an expired session getMethod.releaseConnection(); authenticated = false; authenticate(monitor); } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { authenticated = false; getMethod.getResponseBodyNoop(); getMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Proxy authentication required")); } else { getMethod.getResponseBodyNoop(); getMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); } } throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "All connection attempts to " + repositoryUrl.toString() + " failed. Please verify connection and authentication information.")); } public void logout(IProgressMonitor monitor) throws IOException, CoreException { monitor = Policy.monitorFor(monitor); authenticated = true; String loginUrl = repositoryUrl + "/relogin.cgi"; GzipGetMethod method = null; try { method = getConnect(loginUrl, monitor); authenticated = false; httpClient.getState().clearCookies(); } finally { if (method != null) { method.releaseConnection(); } } } - private InputStream getResponseStream(HttpMethodBase method, IProgressMonitor monitor) throws IOException { + protected InputStream getResponseStream(HttpMethodBase method, IProgressMonitor monitor) throws IOException { InputStream in = WebUtil.getResponseBodyAsStream(method, monitor); if (isZippedReply(method)) { in = new java.util.zip.GZIPInputStream(in); } return in; } private boolean isZippedReply(HttpMethodBase method) { // content-encoding:gzip can be set by a dedicated perl script or mod_gzip boolean zipped = (null != method.getResponseHeader("Content-encoding") && method.getResponseHeader( "Content-encoding").getValue().equals(IBugzillaConstants.CONTENT_ENCODING_GZIP)) || // content-type: application/x-gzip can be set by any apache after 302 redirect, based on .gz suffix (null != method.getResponseHeader("Content-Type") && method.getResponseHeader("Content-Type") .getValue() .equals("application/x-gzip")); return zipped; } public void authenticate(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); if (!hasAuthenticationCredentials()) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Authentication credentials missing.")); } GzipPostMethod postMethod = null; try { hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); NameValuePair[] formData = new NameValuePair[2]; formData[0] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_LOGIN, username); formData[1] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_PASSWORD, password); postMethod = new GzipPostMethod(WebUtil.getRequestPath(repositoryUrl.toString() + IBugzillaConstants.URL_POST_LOGIN), true); postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + characterEncoding); postMethod.setRequestBody(formData); postMethod.setDoAuthentication(true); postMethod.setFollowRedirects(false); httpClient.getState().clearCookies(); AuthenticationCredentials httpAuthCredentials = location.getCredentials(AuthenticationType.HTTP); if (httpAuthCredentials != null && httpAuthCredentials.getUserName() != null && httpAuthCredentials.getUserName().length() > 0) { httpClient.getParams().setAuthenticationPreemptive(true); } int code = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor); if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { authenticated = false; postMethod.getResponseBodyNoop(); postMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "HTTP authentication failed.")); } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { authenticated = false; postMethod.getResponseBodyNoop(); postMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Proxy authentication required")); } else if (code != HttpURLConnection.HTTP_OK) { authenticated = false; postMethod.getResponseBodyNoop(); postMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); } if (hasAuthenticationCredentials()) { for (Cookie cookie : httpClient.getState().getCookies()) { if (cookie.getName().equals(COOKIE_BUGZILLA_LOGIN)) { authenticated = true; break; } } if (!authenticated) { InputStream input = getResponseStream(postMethod, monitor); try { parseHtmlError(input); } finally { input.close(); } } } else { // anonymous login authenticated = true; } } catch (IOException e) { throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e)); } finally { if (postMethod != null) { postMethod.releaseConnection(); } httpClient.getParams().setAuthenticationPreemptive(false); } } public boolean getSearchHits(IRepositoryQuery query, TaskDataCollector collector, TaskAttributeMapper mapper, IProgressMonitor monitor) throws IOException, CoreException { GzipPostMethod postMethod = null; try { String queryUrl = query.getUrl(); int start = queryUrl.indexOf('?'); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if (start != -1) { queryUrl = queryUrl.substring(start + 1); String[] result = queryUrl.split("&"); if (result.length > 0) { for (String string : result) { String[] nameValue = string.split("="); if (nameValue.length == 1) { pairs.add(new NameValuePair(nameValue[0].trim(), "")); } else if (nameValue.length == 2 && nameValue[0] != null && nameValue[1] != null) { pairs.add(new NameValuePair(nameValue[0].trim(), URLDecoder.decode(nameValue[1].trim(), characterEncoding))); } } } } NameValuePair ctypePair = new NameValuePair("ctype", "rdf"); // Test that we don't specify content type twice. if (!pairs.contains(ctypePair)) { pairs.add(ctypePair); } postMethod = postFormData(IBugzillaConstants.URL_BUGLIST, pairs.toArray(new NameValuePair[pairs.size()]), monitor); if (postMethod.getResponseHeader("Content-Type") != null) { Header responseTypeHeader = postMethod.getResponseHeader("Content-Type"); for (String type : VALID_CONFIG_CONTENT_TYPES) { if (responseTypeHeader.getValue().toLowerCase(Locale.ENGLISH).contains(type)) { InputStream stream = getResponseStream(postMethod, monitor); try { RepositoryQueryResultsFactory queryFactory = getQueryResultsFactory(stream); int count = queryFactory.performQuery(repositoryUrl.toString(), collector, mapper, TaskDataCollector.MAX_HITS); return count > 0; } finally { stream.close(); } } } } parseHtmlError(getResponseStream(postMethod, monitor)); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } return false; } protected RepositoryQueryResultsFactory getQueryResultsFactory(InputStream stream) { return new RepositoryQueryResultsFactory(stream, characterEncoding); } public static void setupExistingBugAttributes(String serverUrl, TaskData existingReport) { // ordered list of elements as they appear in UI // and additional elements that may not appear in the incoming xml // stream but need to be present for bug submission / not always dirty // state handling BugzillaAttribute[] reportElements = { BugzillaAttribute.SHORT_DESC, BugzillaAttribute.BUG_STATUS, BugzillaAttribute.RESOLUTION, BugzillaAttribute.BUG_ID, BugzillaAttribute.REP_PLATFORM, BugzillaAttribute.PRODUCT, BugzillaAttribute.OP_SYS, BugzillaAttribute.COMPONENT, BugzillaAttribute.VERSION, BugzillaAttribute.PRIORITY, BugzillaAttribute.BUG_SEVERITY, BugzillaAttribute.ASSIGNED_TO, BugzillaAttribute.TARGET_MILESTONE, BugzillaAttribute.REPORTER, BugzillaAttribute.DEPENDSON, BugzillaAttribute.BLOCKED, BugzillaAttribute.BUG_FILE_LOC, BugzillaAttribute.NEWCC, BugzillaAttribute.KEYWORDS, BugzillaAttribute.CC, BugzillaAttribute.NEW_COMMENT, BugzillaAttribute.QA_CONTACT, BugzillaAttribute.STATUS_WHITEBOARD, BugzillaAttribute.DEADLINE }; for (BugzillaAttribute element : reportElements) { BugzillaTaskDataHandler.createAttribute(existingReport, element); } } public static String getBugUrlWithoutLogin(String repositoryUrl, String id) { String url = repositoryUrl + IBugzillaConstants.URL_GET_SHOW_BUG + id; return url; } public static String getCharsetFromString(String string) { int charsetStartIndex = string.indexOf(ATTR_CHARSET); if (charsetStartIndex != -1) { int charsetEndIndex = string.indexOf("\"", charsetStartIndex); // TODO: // could // be // space // after? if (charsetEndIndex == -1) { charsetEndIndex = string.length(); } String charsetString = string.substring(charsetStartIndex + 8, charsetEndIndex); if (Charset.availableCharsets().containsKey(charsetString)) { return charsetString; } } return null; } public RepositoryConfiguration getRepositoryConfiguration(IProgressMonitor monitor) throws IOException, CoreException { GzipGetMethod method = null; int attempt = 0; while (attempt < 2) { try { method = getConnectGzip(repositoryUrl + IBugzillaConstants.URL_GET_CONFIG_RDF, monitor); // provide a solution for bug 196056 by allowing a (cached) gzipped configuration to be sent // modified to also accept "application/x-gzip" as results from a 302 redirect to a previously gzipped file. if (method == null) { throw new IOException("Could not retrieve configuratoin. HttpClient return null method."); } InputStream stream = getResponseStream(method, monitor); try { if (method.getResponseHeader("Content-Type") != null) { Header responseTypeHeader = method.getResponseHeader("Content-Type"); for (String type : VALID_CONFIG_CONTENT_TYPES) { if (responseTypeHeader.getValue().toLowerCase(Locale.ENGLISH).contains(type)) { RepositoryConfigurationFactory configFactory = new RepositoryConfigurationFactory( stream, characterEncoding); repositoryConfiguration = configFactory.getConfiguration(); if (repositoryConfiguration != null) { if (!repositoryConfiguration.getProducts().isEmpty()) { repositoryConfiguration.setRepositoryUrl(repositoryUrl.toString()); return repositoryConfiguration; } else { if (attempt == 0) { // empty configuration, retry authenticate authenticated = false; break; } else { throw new CoreException( new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve repository configuration. Ensure credentials are valid.")); } } } } } } if (authenticated) { parseHtmlError(stream); return null; } } finally { stream.close(); } } finally { attempt++; if (method != null) { method.releaseConnection(); } } } return null; } public void getAttachmentData(String attachmentId, OutputStream out, IProgressMonitor monitor) throws IOException, CoreException { String url = repositoryUrl + IBugzillaConstants.URL_GET_ATTACHMENT_DOWNLOAD + attachmentId; GetMethod method = connectInternal(url, false, monitor);//getConnectGzip(url, monitor); try { int status = WebUtil.execute(httpClient, hostConfiguration, method, monitor); if (status == HttpStatus.SC_OK) { out.write(method.getResponseBody()); } else { parseHtmlError(method.getResponseBodyAsStream()); } } catch (IOException e) { throw e; } finally { method.releaseConnection(); } } public void postAttachment(String bugReportID, String comment, String description, String contentType, boolean isPatch, PartSource source, IProgressMonitor monitor) throws HttpException, IOException, CoreException { monitor = Policy.monitorFor(monitor); Assert.isNotNull(bugReportID); Assert.isNotNull(source); Assert.isNotNull(contentType); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); if (!authenticated && hasAuthenticationCredentials()) { authenticate(monitor); } GzipPostMethod postMethod = null; try { postMethod = new GzipPostMethod(WebUtil.getRequestPath(repositoryUrl + IBugzillaConstants.URL_POST_ATTACHMENT_UPLOAD), true); // This option causes the client to first // check // with the server to see if it will in fact receive the post before // actually sending the contents. postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); List<PartBase> parts = new ArrayList<PartBase>(); parts.add(new StringPart(IBugzillaConstants.POST_INPUT_ACTION, VALUE_ACTION_INSERT, characterEncoding)); if (username != null && password != null) { parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGZILLA_LOGIN, username, characterEncoding)); parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGZILLA_PASSWORD, password, characterEncoding)); } parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGID, bugReportID, characterEncoding)); if (description != null) { parts.add(new StringPart(IBugzillaConstants.POST_INPUT_DESCRIPTION, description, characterEncoding)); } if (comment != null) { parts.add(new StringPart(IBugzillaConstants.POST_INPUT_COMMENT, comment, characterEncoding)); } parts.add(new FilePart(IBugzillaConstants.POST_INPUT_DATA, source)); if (isPatch) { parts.add(new StringPart(ATTRIBUTE_ISPATCH, VALUE_ISPATCH)); } else { parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEMETHOD, VALUE_CONTENTTYPEMETHOD_MANUAL)); parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEENTRY, contentType)); } postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[1]), postMethod.getParams())); postMethod.setDoAuthentication(true); int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor); if (status == HttpStatus.SC_OK) { InputStream input = getResponseStream(postMethod, monitor); try { parseHtmlError(input); } finally { input.close(); } } else { postMethod.getResponseBodyNoop(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Http error: " + HttpStatus.getStatusText(status))); // throw new IOException("Communication error occurred during // upload. \n\n" // + HttpStatus.getStatusText(status)); } } finally { if (postMethod != null) { postMethod.releaseConnection(); } } } /** * calling method must release the connection on the returned PostMethod once finished. * * @throws CoreException */ private GzipPostMethod postFormData(String formUrl, NameValuePair[] formData, IProgressMonitor monitor) throws IOException, CoreException { GzipPostMethod postMethod = null; monitor = Policy.monitorFor(monitor); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); if (!authenticated && hasAuthenticationCredentials()) { authenticate(monitor); } postMethod = new GzipPostMethod(WebUtil.getRequestPath(repositoryUrl.toString() + formUrl), true); postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + characterEncoding); httpClient.getHttpConnectionManager().getParams().setSoTimeout(WebUtil.getConnectionTimeout()); // postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new BugzillaRetryHandler()); postMethod.setRequestBody(formData); postMethod.setDoAuthentication(true); // httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECT_TIMEOUT); int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor); if (status == HttpStatus.SC_OK) { return postMethod; } else { postMethod.getResponseBodyNoop(); postMethod.releaseConnection(); //StatusManager.log("Post failed: " + HttpStatus.getStatusText(status), this); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), new IOException( "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status)))); // throw new IOException("Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status)); } } public RepositoryResponse postTaskData(TaskData taskData, IProgressMonitor monitor) throws IOException, CoreException { NameValuePair[] formData = null; String prefix = null; String prefix2 = null; String postfix = null; String postfix2 = null; monitor = Policy.monitorFor(monitor); if (taskData == null) { return null; } else if (taskData.isNew()) { formData = getPairsForNew(taskData); prefix = IBugzillaConstants.FORM_PREFIX_BUG_218; prefix2 = IBugzillaConstants.FORM_PREFIX_BUG_220; postfix = IBugzillaConstants.FORM_POSTFIX_216; postfix2 = IBugzillaConstants.FORM_POSTFIX_218; } else { formData = getPairsForExisting(taskData, new SubProgressMonitor(monitor, 1)); } String result = null; GzipPostMethod method = null; InputStream input = null; try { if (taskData.isNew()) { method = postFormData(POST_BUG_CGI, formData, monitor); } else { method = postFormData(PROCESS_BUG_CGI, formData, monitor); } if (method == null) { throw new IOException("Could not post form, client returned null method."); } input = getResponseStream(method, monitor); BufferedReader in = new BufferedReader(new InputStreamReader(input, method.getRequestCharSet())); if (in.markSupported()) { in.mark(1028); } HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(in, null); boolean existingBugPosted = false; boolean isTitle = false; String title = ""; for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG && ((HtmlTag) (token.getValue())).getTagType() == Tag.TITLE && !((HtmlTag) (token.getValue())).isEndTag()) { isTitle = true; continue; } if (isTitle) { // get all of the data in the title tag if (token.getType() != Token.TAG) { title += ((StringBuffer) token.getValue()).toString().toLowerCase(Locale.ENGLISH) + " "; continue; } else if (token.getType() == Token.TAG && ((HtmlTag) token.getValue()).getTagType() == Tag.TITLE && ((HtmlTag) token.getValue()).isEndTag()) { boolean found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_PROCESSED).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (!taskData.isNew() && found) { existingBugPosted = true; } else if (taskData.isNew() && prefix != null && prefix2 != null && postfix != null && postfix2 != null) { int startIndex = -1; int startIndexPrefix = title.toLowerCase(Locale.ENGLISH).indexOf( prefix.toLowerCase(Locale.ENGLISH)); int startIndexPrefix2 = title.toLowerCase(Locale.ENGLISH).indexOf( prefix2.toLowerCase(Locale.ENGLISH)); if (startIndexPrefix != -1 || startIndexPrefix2 != -1) { if (startIndexPrefix != -1) { startIndex = startIndexPrefix + prefix.length(); } else { startIndex = startIndexPrefix2 + prefix2.length(); } int stopIndex = title.toLowerCase(Locale.ENGLISH).indexOf( postfix.toLowerCase(Locale.ENGLISH), startIndex); if (stopIndex == -1) { stopIndex = title.toLowerCase(Locale.ENGLISH).indexOf( postfix2.toLowerCase(Locale.ENGLISH), startIndex); } if (stopIndex > -1) { result = (title.substring(startIndex, stopIndex)).trim(); } } } break; } } } if ((!taskData.isNew() && existingBugPosted != true) || (taskData.isNew() && result == null)) { try { if (in.markSupported()) { in.reset(); } } catch (IOException e) { // ignore } parseHtmlError(in); } if (taskData.isNew()) { return new RepositoryResponse(ResponseKind.TASK_CREATED, result); } else { return new RepositoryResponse(ResponseKind.TASK_UPDATED, taskData.getTaskId()); } } catch (ParseException e) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "Unable to parse response from " + repositoryUrl.toString() + ".")); } finally { if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } } } private NameValuePair[] getPairsForNew(TaskData taskData) { Map<String, NameValuePair> fields = new HashMap<String, NameValuePair>(); // go through all of the attributes and add them to // the bug post Collection<TaskAttribute> attributes = new ArrayList<TaskAttribute>(taskData.getRoot().getAttributes().values()); Iterator<TaskAttribute> itr = attributes.iterator(); while (itr.hasNext()) { TaskAttribute a = itr.next(); if (a != null && a.getId() != null && a.getId().compareTo("") != 0) { String value = null; value = a.getValue(); if (value == null) { continue; } if (a.getId().equals(BugzillaAttribute.NEWCC.getKey())) { TaskAttribute b = taskData.getRoot().createAttribute(BugzillaAttribute.CC.getKey()); b.getMetaData().defaults().setReadOnly(BugzillaAttribute.CC.isReadOnly()).setKind( BugzillaAttribute.CC.getKind()).setLabel(BugzillaAttribute.CC.toString()).setType( BugzillaAttribute.CC.getType()); for (String val : a.getValues()) { if (val != null) { b.addValue(val); } } a = b; cleanIfShortLogin(a); } else { cleanQAContact(a); } fields.put(a.getId(), new NameValuePair(a.getId(), value)); } } TaskAttribute descAttribute = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION); if (descAttribute != null && !descAttribute.getValue().equals("")) { String bugzillaVersion = null; if (repositoryConfiguration != null) { bugzillaVersion = repositoryConfiguration.getInstallVersion(); } else { bugzillaVersion = "2.18"; } if (bugzillaVersion.startsWith("2.18")) { fields.put(KEY_COMMENT, new NameValuePair(KEY_COMMENT, formatTextToLineWrap(descAttribute.getValue(), true))); } else { fields.put(KEY_COMMENT, new NameValuePair(KEY_COMMENT, descAttribute.getValue())); } } return fields.values().toArray(new NameValuePair[fields.size()]); } private void cleanQAContact(TaskAttribute a) { if (a.getId().equals(BugzillaAttribute.QA_CONTACT.getKey())) { cleanIfShortLogin(a); } } private void cleanIfShortLogin(TaskAttribute a) { if ("true".equals(configParameters.get(IBugzillaConstants.REPOSITORY_SETTING_SHORT_LOGIN))) { if (a.getValue() != null && a.getValue().length() > 0) { int atIndex = a.getValue().indexOf("@"); if (atIndex != -1) { String newValue = a.getValue().substring(0, atIndex); a.setValue(newValue); } } } } private NameValuePair[] getPairsForExisting(TaskData model, IProgressMonitor monitor) throws CoreException { boolean groupSecurityEnabled = false; Map<String, NameValuePair> fields = new HashMap<String, NameValuePair>(); fields.put(KEY_FORM_NAME, new NameValuePair(KEY_FORM_NAME, VAL_PROCESS_BUG)); // go through all of the attributes and add them to the bug post Collection<TaskAttribute> attributes = model.getRoot().getAttributes().values(); Iterator<TaskAttribute> itr = attributes.iterator(); while (itr.hasNext()) { TaskAttribute a = itr.next(); if (a == null) { continue; } else if (a.getId().equals(BugzillaAttribute.QA_CONTACT.getKey()) || a.getId().equals(BugzillaAttribute.ASSIGNED_TO.getKey())) { cleanIfShortLogin(a); } else if (a.getId().equals(BugzillaAttribute.REPORTER.getKey()) || a.getId().equals(BugzillaAttribute.CC.getKey()) || a.getId().equals(BugzillaAttribute.REMOVECC.getKey()) || a.getId().equals(BugzillaAttribute.CREATION_TS.getKey())) { continue; } if (a.getId().equals(BugzillaAttribute.NEW_COMMENT.getKey())) { String bugzillaVersion = null; if (repositoryConfiguration != null) { bugzillaVersion = repositoryConfiguration.getInstallVersion(); } else { bugzillaVersion = "2.18"; } if (bugzillaVersion.startsWith("2.18")) { a.setValue(formatTextToLineWrap(a.getValue(), true)); } } if (a.getId().equals(BugzillaAttribute.GROUP.getKey()) && a.getValue().length() > 0) { groupSecurityEnabled = true; } if (a.getId() != null && a.getId().compareTo("") != 0) { String value = a.getValue(); if (a.getId().equals(BugzillaAttribute.DELTA_TS.getKey())) { value = stripTimeZone(value); } fields.put(a.getId(), new NameValuePair(a.getId(), value != null ? value : "")); } } // when posting the bug id is encoded in a hidden field named 'id' TaskAttribute attributeBugId = model.getRoot().getAttribute(BugzillaAttribute.BUG_ID.getKey()); if (attributeBugId != null) { fields.put(KEY_ID, new NameValuePair(KEY_ID, attributeBugId.getValue())); } // add the operation to the bug post TaskAttribute attributeOperation = model.getRoot().getMappedAttribute(TaskAttribute.OPERATION); if (attributeOperation == null) { fields.put(KEY_KNOB, new NameValuePair(KEY_KNOB, VAL_NONE)); } else { TaskAttribute originalOperation = model.getRoot().getAttribute( TaskAttribute.PREFIX_OPERATION + attributeOperation.getValue()); if (originalOperation == null) { // Work around for bug#241012 fields.put(KEY_KNOB, new NameValuePair(KEY_KNOB, VAL_NONE)); } else { String inputAttributeId = originalOperation.getMetaData().getValue( TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID); if (originalOperation == null) { fields.put(KEY_KNOB, new NameValuePair(KEY_KNOB, VAL_NONE)); } else if (inputAttributeId == null || inputAttributeId.equals("")) { String sel = attributeOperation.getValue(); fields.put(KEY_KNOB, new NameValuePair(KEY_KNOB, sel)); } else { fields.put(KEY_KNOB, new NameValuePair(KEY_KNOB, attributeOperation.getValue())); TaskAttribute inputAttribute = attributeOperation.getTaskData().getRoot().getAttribute( inputAttributeId); if (inputAttribute != null) { if (inputAttribute.getOptions().size() > 0) { String sel = inputAttribute.getValue(); String knob = inputAttribute.getId(); if (knob.equals(BugzillaOperation.resolve.getInputId())) { knob = BugzillaAttribute.RESOLUTION.getKey(); } fields.put(knob, new NameValuePair(knob, inputAttribute.getOption(sel))); } else { String sel = inputAttribute.getValue(); String knob = attributeOperation.getValue(); if (knob.equals(BugzillaOperation.reassign.toString())) { knob = BugzillaAttribute.ASSIGNED_TO.getKey(); } fields.put(knob, new NameValuePair(knob, sel)); } } } } } if (model.getRoot().getMappedAttribute(BugzillaAttribute.SHORT_DESC.getKey()) != null) { fields.put(KEY_SHORT_DESC, new NameValuePair(KEY_SHORT_DESC, model.getRoot().getMappedAttribute( BugzillaAttribute.SHORT_DESC.getKey()).getValue())); } if (model.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW) != null && model.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW).getValue().length() > 0) { fields.put(KEY_COMMENT, new NameValuePair(KEY_COMMENT, model.getRoot().getMappedAttribute( TaskAttribute.COMMENT_NEW).getValue())); } else if (attributeOperation != null && attributeOperation.getValue().equals(BugzillaOperation.duplicate.toString())) { // fix for bug#198677 fields.put(KEY_COMMENT, new NameValuePair(KEY_COMMENT, "")); } TaskAttribute attributeRemoveCC = model.getRoot().getMappedAttribute(BugzillaAttribute.REMOVECC.getKey()); if (attributeRemoveCC != null) { List<String> removeCC = attributeRemoveCC.getValues(); if (removeCC != null && removeCC.size() > 0) { String[] s = new String[removeCC.size()]; fields.put(KEY_CC, new NameValuePair(KEY_CC, toCommaSeparatedList(removeCC.toArray(s)))); fields.put(BugzillaAttribute.REMOVECC.getKey(), new NameValuePair(BugzillaAttribute.REMOVECC.getKey(), VAL_TRUE)); } } if (groupSecurityEnabled) { // get security info from html and include in post Map<String, String> groupIds = getGroupSecurityInformation(model, monitor); for (String key : groupIds.keySet()) { fields.put(key, new NameValuePair(key, groupIds.get(key))); } } return fields.values().toArray(new NameValuePair[fields.size()]); } private Map<String, String> getGroupSecurityInformation(TaskData taskData, IProgressMonitor monitor) throws CoreException { Map<String, String> groupSecurityInformation = new HashMap<String, String>(); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); String bugUrl = taskData.getRepositoryUrl() + IBugzillaConstants.URL_GET_SHOW_BUG + taskData.getTaskId(); GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(bugUrl), false); getMethod.setRequestHeader("Content-Type", "text/xml; charset=" + characterEncoding); httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); getMethod.setDoAuthentication(true); int code; InputStream inStream = null; try { code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor); if (code == HttpURLConnection.HTTP_OK) { inStream = getResponseStream(getMethod, monitor); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(new BufferedReader(new InputStreamReader( inStream, characterEncoding)), null); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG && ((HtmlTag) (token.getValue())).getTagType() == Tag.INPUT && !((HtmlTag) (token.getValue())).isEndTag()) { HtmlTag tag = (HtmlTag) token.getValue(); // String name = tag.getAttribute("name"); String id = tag.getAttribute("id"); String checkedValue = tag.getAttribute("checked"); String type = tag.getAttribute("type"); if (type != null && type.equalsIgnoreCase("checkbox") && id != null && id.startsWith("bit-")) { groupSecurityInformation.put(id, checkedValue); } } } } } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve group security information", e)); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { //ignore } } } return groupSecurityInformation; } public static String stripTimeZone(String longTime) { String result = longTime; if (longTime != null) { String[] values = longTime.split(" "); if (values != null && values.length > 2) { result = values[0] + " " + values[1]; } } return result; } private static String toCommaSeparatedList(String[] strings) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < strings.length; i++) { buffer.append(strings[i]); if (i != strings.length - 1) { buffer.append(","); } } return buffer.toString(); } /** * Utility method for determining what potential error has occurred from a bugzilla html reponse page */ private void parseHtmlError(InputStream inputStream) throws IOException, CoreException { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, characterEncoding)); parseHtmlError(in); } private void parseHtmlError(BufferedReader in) throws IOException, CoreException { HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(in, null); boolean isTitle = false; String title = ""; String body = ""; try { for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { body += token.toString(); if (token.getType() == Token.TAG && ((HtmlTag) (token.getValue())).getTagType() == Tag.TITLE && !((HtmlTag) (token.getValue())).isEndTag()) { isTitle = true; continue; } if (isTitle) { // get all of the data in the title tag if (token.getType() != Token.TAG) { title += ((StringBuffer) token.getValue()).toString().toLowerCase(Locale.ENGLISH) + " "; continue; } else if (token.getType() == Token.TAG && ((HtmlTag) token.getValue()).getTagType() == Tag.TITLE && ((HtmlTag) token.getValue()).isEndTag()) { boolean found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_ERROR_LOGIN).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (found) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), title)); } found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_ERROR_COLLISION).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (found) { throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.REPOSITORY_COLLISION, repositoryUrl.toString())); } found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_ERROR_COMMENT_REQUIRED).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (found) { throw new CoreException(new BugzillaStatus(IStatus.INFO, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.REPOSITORY_COMMENT_REQUIRED)); } found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_ERROR_LOGGED_OUT).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (found) { authenticated = false; // throw new // BugzillaException(IBugzillaConstants.LOGGED_OUT); throw new CoreException(new BugzillaStatus(IStatus.INFO, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.REPOSITORY_LOGGED_OUT, "You have been logged out. Please retry operation.")); } found = false; for (Iterator<String> iterator = bugzillaLanguageSettings.getResponseForCommand( BugzillaLanguageSettings.COMMAND_CHANGES_SUBMITTED).iterator(); iterator.hasNext() && !found;) { String value = iterator.next().toLowerCase(Locale.ENGLISH); found = found || title.indexOf(value) != -1; } if (found) { return; } isTitle = false; } } } throw new CoreException(RepositoryStatus.createHtmlStatus(repositoryUrl.toString(), IStatus.INFO, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY, "A repository error has occurred.", body)); } catch (ParseException e) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "Unable to parse response from " + repositoryUrl.toString() + ".")); } finally { in.close(); } } public TaskHistory getHistory(String taskId, IProgressMonitor monitor) throws IOException, CoreException { hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); if (!authenticated && hasAuthenticationCredentials()) { authenticate(monitor); } GzipGetMethod method = null; try { String url = repositoryUrl + IBugzillaConstants.SHOW_ACTIVITY + taskId; method = getConnectGzip(url, monitor); if (method != null) { InputStream in = getResponseStream(method, monitor); try { BugzillaTaskHistoryParser parser = new BugzillaTaskHistoryParser(in, characterEncoding); try { return parser.retrieveHistory(bugzillaLanguageSettings); } catch (LoginException e) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), IBugzillaConstants.INVALID_CREDENTIALS)); } catch (ParseException e) { authenticated = false; throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "Unable to parse response from " + repositoryUrl.toString() + ".")); } } finally { in.close(); } } } finally { if (method != null) { method.releaseConnection(); } } return null; } public void getTaskData(Set<String> taskIds, final TaskDataCollector collector, final TaskAttributeMapper mapper, final IProgressMonitor monitor) throws IOException, CoreException { GzipPostMethod method = null; HashMap<String, TaskData> taskDataMap = new HashMap<String, TaskData>(); // make a copy to modify set taskIds = new HashSet<String>(taskIds); int authenticationAttempt = 0; while (taskIds.size() > 0) { try { Set<String> idsToRetrieve = new HashSet<String>(); Iterator<String> itr = taskIds.iterator(); for (int x = 0; itr.hasNext() && x < MAX_RETRIEVED_PER_QUERY; x++) { idsToRetrieve.add(itr.next()); } NameValuePair[] formData = new NameValuePair[idsToRetrieve.size() + 2]; if (idsToRetrieve.size() == 0) { return; } itr = idsToRetrieve.iterator(); int x = 0; for (; itr.hasNext(); x++) { String taskId = itr.next(); formData[x] = new NameValuePair("id", taskId); TaskData taskData = new TaskData(mapper, getConnectorKind(), repositoryUrl.toString(), taskId); setupExistingBugAttributes(repositoryUrl.toString(), taskData); taskDataMap.put(taskId, taskData); } formData[x++] = new NameValuePair("ctype", "xml"); formData[x] = new NameValuePair("excludefield", "attachmentdata"); method = postFormData(IBugzillaConstants.URL_POST_SHOW_BUG, formData, monitor); if (method == null) { throw new IOException("Could not post form, client returned null method."); } boolean parseable = false; if (method.getResponseHeader("Content-Type") != null) { Header responseTypeHeader = method.getResponseHeader("Content-Type"); for (String type : VALID_CONFIG_CONTENT_TYPES) { if (responseTypeHeader.getValue().toLowerCase(Locale.ENGLISH).contains(type)) { InputStream input = getResponseStream(method, monitor); try { MultiBugReportFactory factory = new MultiBugReportFactory(input, characterEncoding); List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>(); if (repositoryConfiguration != null) { customFields = repositoryConfiguration.getCustomFields(); } factory.populateReport(taskDataMap, collector, mapper, customFields); taskIds.removeAll(idsToRetrieve); parseable = true; break; } finally { input.close(); } } } } if (!parseable) { parseHtmlError(getResponseStream(method, monitor)); break; } } catch (CoreException c) { if (c.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN && authenticationAttempt < 1) { authenticated = false; authenticationAttempt++; //StatusHandler.log(c.getStatus()); } else { throw c; } } finally { if (method != null) { method.releaseConnection(); } } } } protected String getConnectorKind() { return BugzillaCorePlugin.CONNECTOR_KIND; } public String getConfigurationTimestamp(IProgressMonitor monitor) throws CoreException { if (!lastModifiedSupported) { return null; } String lastModified = null; HeadMethod method = null; try { method = connectHead(repositoryUrl + IBugzillaConstants.URL_GET_CONFIG_RDF, monitor); Header lastModifiedHeader = method.getResponseHeader("Last-Modified"); if (lastModifiedHeader != null && lastModifiedHeader.getValue() != null && lastModifiedHeader.getValue().length() > 0) { lastModified = lastModifiedHeader.getValue(); } else { lastModifiedSupported = false; } } catch (Exception e) { lastModifiedSupported = false; throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Error retrieving configuration timestamp", e)); } finally { if (method != null) { method.releaseConnection(); } } return lastModified; } private HeadMethod connectHead(String requestURL, IProgressMonitor monitor) throws IOException, CoreException { hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); for (int attempt = 0; attempt < 2; attempt++) { // force authentication if (!authenticated && hasAuthenticationCredentials()) { authenticate(monitor); } HeadMethod headMethod = new HeadMethod(WebUtil.getRequestPath(requestURL)); if (requestURL.contains(QUERY_DELIMITER)) { headMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER))); } headMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + characterEncoding); // WARNING!! Setting browser compatability breaks Bugzilla // authentication // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // headMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new BugzillaRetryHandler()); headMethod.setDoAuthentication(true); int code; try { code = WebUtil.execute(httpClient, hostConfiguration, headMethod, monitor); } catch (IOException e) { headMethod.getResponseBody(); headMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e)); } if (code == HttpURLConnection.HTTP_OK) { return headMethod; } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { headMethod.getResponseBody(); // login or reauthenticate due to an expired session headMethod.releaseConnection(); authenticated = false; authenticate(monitor); } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { authenticated = false; headMethod.getResponseBody(); headMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Proxy authentication required")); } else { headMethod.getResponseBody(); headMethod.releaseConnection(); throw new CoreException(new BugzillaStatus(Status.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); // throw new IOException("HttpClient connection error response // code: " + code); } } throw new CoreException(new BugzillaStatus(Status.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "All connection attempts to " + repositoryUrl.toString() + " failed. Please verify connection and authentication information.")); } public void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration) { this.repositoryConfiguration = repositoryConfiguration; } public RepositoryConfiguration getRepositoryConfiguration() { return repositoryConfiguration; } public void shutdown() { ((MultiThreadedHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown(); } /** * Break text up into lines so that it is displayed properly in bugzilla */ public static String formatTextToLineWrap(String origText, boolean hardWrap) { if (!hardWrap) { return origText; } else { String newText = ""; while (!origText.equals("")) { int newLine = origText.indexOf('\n'); if (newLine == -1) { if (origText.length() > WRAP_LENGTH) { int spaceIndex = origText.lastIndexOf(" ", WRAP_LENGTH); if (spaceIndex == -1) { spaceIndex = WRAP_LENGTH; } newText = newText + origText.substring(0, spaceIndex) + "\n"; origText = origText.substring(spaceIndex + 1, origText.length()); } else { newText = newText + origText; origText = ""; } } else { newText = newText + origText.substring(0, newLine + 1); origText = origText.substring(newLine + 1, origText.length()); } } return newText; } } }
false
false
null
null
diff --git a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java index 0edec57b05..01c05710fd 100644 --- a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java +++ b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1PropertiesBuilder.java @@ -1,48 +1,48 @@ /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds 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.jclouds.openhosting; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.Constants.PROPERTY_ISO3166_CODES; import java.util.Properties; import org.jclouds.elasticstack.ElasticStackPropertiesBuilder; /** * * @author Adrian Cole */ public class OpenHostingEast1PropertiesBuilder extends ElasticStackPropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_ISO3166_CODES, "US-VA"); + properties.setProperty(PROPERTY_ISO3166_CODES, "US-FL"); properties.setProperty(PROPERTY_ENDPOINT, "https://api.east1.openhosting.com"); properties.setProperty(PROPERTY_API_VERSION, "2.0"); return properties; } public OpenHostingEast1PropertiesBuilder(Properties properties) { super(properties); } } diff --git a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1ProviderMetadata.java b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1ProviderMetadata.java index ef5341a027..aae3250faf 100644 --- a/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1ProviderMetadata.java +++ b/providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1ProviderMetadata.java @@ -1,108 +1,108 @@ /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds 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.jclouds.openhosting; import com.google.common.collect.ImmutableSet; import java.net.URI; import java.util.Set; import org.jclouds.providers.BaseProviderMetadata; /** * Implementation of {@link org.jclouds.types.ProviderMetadata} for OpenHosting's * East1 provider. * * @author Jeremy Whitlock <[email protected]> */ public class OpenHostingEast1ProviderMetadata extends BaseProviderMetadata { /** * {@inheritDoc} */ @Override public String getId() { return "openhosting-east1"; } /** * {@inheritDoc} */ @Override public String getType() { return COMPUTE_TYPE; } /** * {@inheritDoc} */ @Override public String getName() { return "OpenHosting East1"; } /** * {@inheritDoc} */ @Override public String getIdentityName() { return "User UUID"; } /** * {@inheritDoc} */ @Override public String getCredentialName() { return "Secret API Key"; } /** * {@inheritDoc} */ @Override public URI getHomepage() { return URI.create("https://east1.openhosting.com/"); } /** * {@inheritDoc} */ @Override public URI getConsole() { return URI.create("https://east1.openhosting.com/accounts/login"); } /** * {@inheritDoc} */ @Override public URI getApiDocumentation() { return URI.create("http://www.openhosting.com/support/api/"); } /** * {@inheritDoc} */ @Override public Set<String> getIso3166Codes() { - return ImmutableSet.of("US-VA"); + return ImmutableSet.of("US-FL"); } } diff --git a/providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1TemplateBuilderLiveTest.java b/providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1TemplateBuilderLiveTest.java index d7d034413a..f01de9ec3a 100644 --- a/providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1TemplateBuilderLiveTest.java +++ b/providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1TemplateBuilderLiveTest.java @@ -1,83 +1,83 @@ /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds 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.jclouds.openhosting.compute; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.util.Set; import org.jclouds.compute.BaseTemplateBuilderLiveTest; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamilyVersion64Bit; import org.jclouds.compute.domain.Template; import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; /** * * @author Adrian Cole */ @Test(groups = "live") public class OpenHostingEast1TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { public OpenHostingEast1TemplateBuilderLiveTest() { provider = "openhosting-east1"; } @Override protected Predicate<OsFamilyVersion64Bit> defineUnsupportedOperatingSystems() { return Predicates.not(new Predicate<OsFamilyVersion64Bit>() { @Override public boolean apply(OsFamilyVersion64Bit input) { switch (input.family) { case UBUNTU: return (input.version.equals("") || input.version.equals("10.10")) && input.is64Bit; case DEBIAN: return (input.version.equals("") || input.version.equals("5.0")) && input.is64Bit; case CENTOS: return (input.version.equals("") || input.version.equals("5.5")) && input.is64Bit; default: return false; } } }); } @Test public void testDefaultTemplateBuilder() throws IOException { Template defaultTemplate = this.context.getComputeService().templateBuilder().build(); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.10"); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(defaultTemplate.getLocation().getId(), "openhosting-east1"); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); } @Override protected Set<String> getIso3166Codes() { - return ImmutableSet.<String> of("US-VA"); + return ImmutableSet.<String> of("US-FL"); } }
false
false
null
null