answer
stringlengths
17
10.2M
import java.lang.Runtime; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.io.File; import java.io.FileNotFoundException; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; import static org.junit.Assert.*; import static org.hamcrest.Matchers.equalTo; import align2.BBMap; public class AlignTest { static final String BASE_DIR = "/Users/anders/mu_bbmap/"; static final String CLEAN_BBMAP = BASE_DIR + "src/bbmap/current "; static final String[] GOLD_ARGS = {"in=" + BASE_DIR + "src/bbmap/resources/e_coli_1000.fq", "out=" + BASE_DIR + "sams/gold.sam", "overwrite=t", "build=1", "path=" + BASE_DIR + "src/bbmap"}; @Test public void test_removal_of_reads() { assertTrue("Removal of Reads Failure!", test_mr("removal_of_reads_pre", "removal_of_reads_post")); } @Test public void test_addition_of_reads() { assertTrue("Addition of Reads Failure!", test_mr("addition_of_reads_pre", "addition_of_reads_post")); } @Test public void test_unmapped_reads() { assertTrue("Unmapped Reads Failure!", test_mr("unmapped_reads_pre", "unmapped_reads_post")); } @Test public void test_mapped_reads() { assertTrue("Mapped Reads Failure!", test_mr("mapped_reads_pre", "mapped_reads_post")); } @Test public void test_permutation_of_reads() { assertTrue("Permutation of Reads Failure!", test_mr("permutation_of_reads_pre", "permutation_of_reads_post")); } @BeforeClass public static void setUpClass() { //Create this mutant's reference input String[] original_args = { "in=" + BASE_DIR + "src/bbmap/resources/e_coli_1000.fq", "out=" + BASE_DIR + "sams/original.sam", "overwrite=t", "build=1", "path=" + BASE_DIR + "src/bbmap", "threads=1"}; BBMap.main(original_args); } @AfterClass public static void tearDownClass() { //remove all SAM files } public static Boolean test_mr(String mr_pre, String mr_post) { Method mr_pre_method, mr_post_method; Class thisClass = AlignTest.class; try { mr_pre_method = thisClass.getMethod(mr_pre, String.class, String.class); //apply mutation - make new input file mr_pre_method.invoke(null, BASE_DIR + "src/bbmap/resources/e_coli_1000.fq", BASE_DIR + "altered_reads/e_coli_1000_altered.fq"); } catch (Exception e) { System.err.println("Problem invoking pre funcion"); e.printStackTrace(); } String[] modified_args = { "in=" + BASE_DIR + "altered_reads/e_coli_1000_altered.fq", "out=" + BASE_DIR + "sams/modified.sam", "overwrite=t", "build=1", "path=" + BASE_DIR + "src/bbmap", "threads=1"}; //Create comparison SAM BBMap.main(modified_args); //Perform the relation test Boolean result = false; try { String original = BASE_DIR + "sams/original.sam"; String modified = BASE_DIR + "sams/modified.sam"; mr_post_method = thisClass.getMethod(mr_post, String.class, String.class); result = (Boolean)mr_post_method.invoke(null, original, modified); } catch(Exception e) { e.printStackTrace(); } return result; } public static void removal_of_reads_pre(String input_filename, String output_filename) { Random rand = new Random(); try { PrintWriter writer = new PrintWriter(output_filename); FileReader file_reader = new FileReader(input_filename); BufferedReader reader = new BufferedReader(file_reader); while (true) { String line = reader.readLine(); if (line == null) { break; } if ((line.charAt(0) == '@') && (rand.nextDouble() > 0.5)) { //write this read writer.println(line); writer.println(reader.readLine()); writer.println(reader.readLine()); writer.println(reader.readLine()); } } reader.close(); file_reader.close(); writer.close(); } catch(Exception e) { e.printStackTrace(); } } public static boolean removal_of_reads_post(String original_sam, String output_sam) { boolean pass = true; try { HashMap<String, String> original_map = build_sam_mapping(original_sam); HashMap<String, String> modified_map = build_sam_mapping(output_sam); //compare modified SAM for (Object key : modified_map.keySet().toArray()) { String original = original_map.get((String)key); if ( (original == null) || (!original.equals(modified_map.get((String)key))) ) { System.out.println("Key " + key + " is " + modified_map.get((String)key) + " in modified, was " + original + " in original"); pass = false; } } } catch (Exception e) { e.printStackTrace(); } return pass; } public static void mapped_reads_pre(String input_filename, String output_filename) { //scan the fastq file and output the unmapped reads String original_sam = BASE_DIR + "sams/original.sam"; try { PrintWriter writer = new PrintWriter(output_filename); FileReader sam_file_reader = new FileReader(original_sam); BufferedReader sam_reader = new BufferedReader(sam_file_reader); FileReader fq_file_reader = new FileReader(input_filename); BufferedReader fq_reader = new BufferedReader(fq_file_reader); //scan sam file String line; String[] lineParts; int index; ArrayList<String> mappedList = new ArrayList<String>(); sam_reader.readLine(); sam_reader.readLine(); sam_reader.readLine(); while ((line = sam_reader.readLine()) != null) { lineParts = line.split("\t"); index = Integer.valueOf(lineParts[3]); if (index != 0) { mappedList.add(lineParts[0]); } } sam_reader.close(); sam_file_reader.close(); //scan fq file to find matches and output while ((line = fq_reader.readLine()) != null) { if (line.charAt(0) == '@') { //this line is a read if (mappedList.contains(line.substring(1))) { //this read was mapped - add it to the new fastq file writer.println(line); //label writer.println(fq_reader.readLine()); //read head writer.println(fq_reader.readLine()); //read ext writer.println(fq_reader.readLine()); //read tail } } } writer.close(); fq_reader.close(); fq_file_reader.close(); } catch(Exception e) { e.printStackTrace(); } } public static boolean mapped_reads_post(String original_sam, String output_sam) { boolean pass = true; try { HashMap<String, String> modified_map = build_sam_mapping(output_sam); //modified sam should have no mappings for (String val : modified_map.values()) { if (Integer.valueOf(val).equals(0)) { pass = false; } } } catch (Exception e) { e.printStackTrace(); } return pass; } public static void unmapped_reads_pre(String input_filename, String output_filename) { //scan the fastq file and output the unmapped reads String original_sam = BASE_DIR + "sams/original.sam"; try { PrintWriter writer = new PrintWriter(output_filename); FileReader sam_file_reader = new FileReader(original_sam); BufferedReader sam_reader = new BufferedReader(sam_file_reader); FileReader fq_file_reader = new FileReader(input_filename); BufferedReader fq_reader = new BufferedReader(fq_file_reader); //scan sam file String line; String[] lineParts; int index; ArrayList<String> unmappedList = new ArrayList<String>(); sam_reader.readLine(); sam_reader.readLine(); sam_reader.readLine(); while ((line = sam_reader.readLine()) != null) { lineParts = line.split("\t"); index = Integer.valueOf(lineParts[3]); if (index == 0) { unmappedList.add(lineParts[0]); } } sam_reader.close(); sam_file_reader.close(); //scan fq file to find matches and output while ((line = fq_reader.readLine()) != null) { if (line.charAt(0) == '@') { //this line is a read if (unmappedList.contains(line.substring(1))) { //this read was unmapped - add it to the new fastq file writer.println(line); //label writer.println(fq_reader.readLine()); //read head writer.println(fq_reader.readLine()); //read ext writer.println(fq_reader.readLine()); //read tail } } } writer.close(); fq_reader.close(); fq_file_reader.close(); } catch(Exception e) { e.printStackTrace(); } } public static boolean unmapped_reads_post(String original_sam, String output_sam) { boolean pass = true; try { HashMap<String, String> modified_map = build_sam_mapping(output_sam); //modified sam should have no mappings for (String val : modified_map.values()) { if (!Integer.valueOf(val).equals(0)) { pass = false; } } } catch (Exception e) { e.printStackTrace(); } return pass; } public static void addition_of_reads_pre(String input_filename, String output_filename) { try { PrintWriter writer = new PrintWriter(output_filename); FileReader file_reader = new FileReader(input_filename); BufferedReader reader = new BufferedReader(file_reader); String readName, readHead, readExt, readTail; while (true) { String line = reader.readLine(); if (line == null) { break; } if (line.charAt(0) == '@') { //write original version of read readName = line; writer.println(line); readHead = reader.readLine(); writer.println(readHead); readExt = reader.readLine(); writer.println(readExt); readTail = reader.readLine(); writer.println(readTail); //write this read's duplicate writer.println(readName + "v2"); writer.println(readHead); writer.println(readExt); writer.println(readTail); } } reader.close(); file_reader.close(); writer.close(); } catch(Exception e) { e.printStackTrace(); } } public static boolean addition_of_reads_post(String original_sam, String output_sam) { boolean pass = true; HashMap<String, String> original_map = build_sam_mapping(original_sam); HashMap<String, String> modified_map = build_sam_mapping(output_sam); for (String key: original_map.keySet()) { if (!modified_map.containsKey(key) || !modified_map.get(key).equals(original_map.get(key)) || !modified_map.get(key).equals(modified_map.get(key + "v2"))) { pass = false; } } return pass; } public static void permutation_of_reads_pre(String input_filename, String output_filename) { HashMap<String, String[]> map = new HashMap<String, String[]>(); try { PrintWriter writer = new PrintWriter(output_filename); FileReader file_reader = new FileReader(input_filename); BufferedReader reader = new BufferedReader(file_reader); String line; String[] fullRead; while( (line = reader.readLine()) != null ) { if (line.charAt(0) == '@') { //this line starts a read fullRead = new String[4]; fullRead[0] = line.substring(1); fullRead[1] = reader.readLine(); fullRead[2] = reader.readLine(); fullRead[3] = reader.readLine(); map.put(line.substring(1), fullRead); } } //shuffle keys int index; Random random = new Random(); String temp; String[] keys =map.keySet().toArray(new String[0]); for (int i = keys.length - 1; i > 0; i index = random.nextInt(i + 1); temp = keys[index]; keys[index] = keys[i]; keys[i] = temp; } //write new fastq file using new ordering for (String key : keys) { fullRead = map.get(key); writer.println(fullRead[0]); writer.println(fullRead[1]); writer.println(fullRead[2]); writer.println(fullRead[3]); } reader.close(); file_reader.close(); writer.close(); } catch(Exception e) { e.printStackTrace(); } } public static boolean permutation_of_reads_post(String original_sam, String output_sam) { boolean pass = true; HashMap<String, String> original_map = build_sam_mapping(original_sam); HashMap<String, String> modified_map = build_sam_mapping(output_sam); //mappings should all be the same if (original_map.size() != modified_map.size()) { pass = false; } for (String key: original_map.keySet()) { if (!original_map.get(key).equals(modified_map.get(key))) { pass = false; } } return pass; } public static HashMap<String, String> build_sam_mapping(String filename) { HashMap<String, String> map = new HashMap<String, String>(); try { BufferedReader reader= new BufferedReader(new FileReader(filename)); for (int i = 1; i <= 3; i++) { //headers reader.readLine(); } String line; String[] lineArr; //build map for original while ((line = reader.readLine()) != null) { lineArr = line.split("\t"); map.put(lineArr[0], lineArr[3]); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return map; } public static void build_reference_alignment() { try { //make alignment SAM using pristine src/bbmap/current version String alignString = "java -ea -Xmx5g -cp " + CLEAN_BBMAP + String.join(" ", GOLD_ARGS); Runtime.getRuntime().exec(alignString); } catch(IOException e) { e.printStackTrace(); } } public static void main(String[] args) { BBMap.main(GOLD_ARGS); } }
package scalac.transformer; import scalac.Global; import scalac.Phase; import scalac.PhaseDescriptor; import scalac.CompilationUnit; import scalac.symtab.Definitions; import scalac.symtab.Scope; import scalac.symtab.Symbol; import scalac.symtab.SymbolNameWriter; import scalac.symtab.Type; import scalac.symtab.Modifiers; import scalac.atree.AConstant; import scalac.ast.Transformer; import scalac.ast.GenTransformer; import scalac.ast.Tree; import scalac.ast.TreeList; import scalac.backend.Primitives; import scalac.util.Name; import scalac.util.Names; import scalac.util.Debug; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Arrays; import java.util.Collections; /** * Turn types into values by applying the following transformations: * * - For all type member T of all classes, add an accessor method * T$type returnining the type as a value (the accessor is abstract * if the type member is abstract). * * - For all polymorphic methods/constructors, add a value parameter * for each type parameter. * * - Add a method getType to every class, to obtain its type as a * value. * * - Transform all type expressions into value expressions: type * application is turned into value application, type selection into * value selection, and so on. * * @author Michel Schinz * @version 1.0 */ // TODO use a constant instead of generating empty arrays all the // time. public class TypesAsValuesPhase extends Phase { private final TV_Transformer transformer; /** * The list of members to add to a given class (either type * accessors or instantiation methods). */ private final HashMap/*<Symbol,NewMember[]>*/ membersToAdd = new HashMap(); /** The list of parameters to add to a given method. */ private final HashMap/*<Symbol,List<Symbol>>*/ paramsToAdd = new HashMap(); /** The accessor method corresponding to a given type (or class) member. */ private final HashMap/*<Symbol, Symbol>*/ typeAccessor = new HashMap(); /** The instanciation method corresponding to a given class. */ private final HashMap/*<Symbol,Symbol>*/ instantiator = new HashMap(); /** The class constructor corresponding to a given class. */ private final HashMap/*<Symbol,Symbol>*/ classInitialiser = new HashMap(); private final HashMap/*<Symbol,Symbol>*/ tConstructor = new HashMap(); private final Definitions defs = global.definitions; private final Primitives prims = global.primitives; private final Type.MethodType typeAccessorType = new Type.MethodType(new Symbol[]{}, defs.TYPE_TYPE()); private final Symbol ARRAY_CONSTRUCTOR = defs.ARRAY_CLASS.primaryConstructor(); private final TEnv EENV = new TEnv(); private final Map/*<Symbol, Symbol>*/ predefTypes; private HashMap/*<Symbol, Ancestor[][]>*/ displayCache = new HashMap(); public TypesAsValuesPhase(Global global, PhaseDescriptor descriptor) { super(global, descriptor); transformer = new TV_Transformer(global); predefTypes = new HashMap(); predefTypes.put(defs.DOUBLE_CLASS, defs.RTT_DOUBLE()); predefTypes.put(defs.FLOAT_CLASS, defs.RTT_FLOAT()); predefTypes.put(defs.LONG_CLASS, defs.RTT_LONG()); predefTypes.put(defs.INT_CLASS, defs.RTT_INT()); predefTypes.put(defs.SHORT_CLASS, defs.RTT_SHORT()); predefTypes.put(defs.CHAR_CLASS, defs.RTT_CHAR()); predefTypes.put(defs.BYTE_CLASS, defs.RTT_BYTE()); predefTypes.put(defs.BOOLEAN_CLASS, defs.RTT_BOOLEAN()); predefTypes.put(defs.UNIT_CLASS, defs.RTT_UNIT()); predefTypes.put(defs.ANY_CLASS, defs.RTT_ANY()); predefTypes.put(defs.ANYVAL_CLASS, defs.RTT_ANYVAL()); predefTypes.put(defs.ALLREF_CLASS, defs.RTT_ALLREF()); predefTypes.put(defs.ALL_CLASS, defs.RTT_ALL()); membersToAdd.put(defs.ARRAY_CLASS, new NewMember[0]); paramsToAdd.put(ARRAY_CONSTRUCTOR, new Symbol[0]); displayCache.put(defs.OBJECT_CLASS, new Ancestor[][] { new Ancestor[] { new Ancestor(defs.OBJECT_CLASS, -1, -1) } }); } /** * Return the symbol of the accessor for the given type symbol. */ private Symbol getAccessorSym(Symbol typeSym) { assert typeSym.isType(); Symbol accessorSym = (Symbol)typeAccessor.get(typeSym); if (accessorSym == null) { accessorSym = typeSym.owner().newVariable(typeSym.pos, typeSym.flags, Names.TYPE(typeSym)); accessorSym.setInfo(defs.TYPE_TYPE()); typeAccessor.put(typeSym, accessorSym); } return accessorSym; } private Symbol getInstMethSym(Symbol classSym) { Symbol imSym = (Symbol)instantiator.get(classSym); if (imSym == null) { int pos = classSym.pos; boolean isStatic = !isNestedClass(classSym); Name imName = Names.INSTANTIATE(classSym, isStatic); int flags = classSym.isAbstractType() ? Modifiers.DEFERRED : 0; imSym = isStatic ? classSym.newStaticMethod(pos, 0, imName) : classSym.owner().newMethod(pos, flags, imName); // TODO special case for monomorphic instantiations Symbol[] argTypes; if (true || classSym.typeParams().length > 0) { Symbol typesP = imSym.newVParam(pos, 0, Name.fromString("types")); typesP.setInfo(defs.ARRAY_TYPE(defs.TYPE_TYPE())); argTypes = new Symbol[]{ typesP }; } else argTypes = Symbol.EMPTY_ARRAY; imSym.setInfo(new Type.MethodType(argTypes, isStatic ? defs.SCALACLASSTYPE_TYPE() : defs.TYPE_TYPE())); instantiator.put(classSym, imSym); } return imSym; } private Symbol getTConstructorSym(Symbol classSym) { Symbol tcSym = (Symbol)tConstructor.get(classSym); if (tcSym == null) { int pos = classSym.pos; boolean isStatic = !isNestedClass(classSym); Name tcName = Names.TYPECONSTRUCTOR(classSym, isStatic); tcSym = isStatic ? classSym.newStaticField(pos, 0, tcName) : classSym.owner().newField(pos, 0, tcName); tcSym.setInfo(defs.TYPECONSTRUCTOR_TYPE()); tConstructor.put(classSym, tcSym); } return tcSym; } private Symbol getClassInitSym(Symbol classSym) { Symbol ciSym = (Symbol)classInitialiser.get(classSym); if (ciSym == null) { int pos = classSym.pos; ciSym = classSym.newStaticMethod(pos, 0, Names.CLASS_CONSTRUCTOR); ciSym.setInfo(new Type.MethodType(Symbol.EMPTY_ARRAY, defs.UNIT_TYPE())); classInitialiser.put(classSym, ciSym); } return ciSym; } private NewMember[] membersToAdd(Symbol classSym) { NewMember[] toAdd = (NewMember[])membersToAdd.get(classSym); if (toAdd == null) { HashSet seenMembers = new HashSet(); // [HACK] ArrayList toAddL = new ArrayList(); Scope.SymbolIterator membersIt = classSym.members().iterator(); while (membersIt.hasNext()) { Symbol member = membersIt.next(); // [HACK] work around a bug in the analyzer, which // doesn't add the module class to its owner's members if (member.isModule()) member = member.moduleClass(); if (!seenMembers.add(member)) continue; if (member.isClass()) { Symbol tcSym = getTConstructorSym(member); toAddL.add(NewMember.TypeConstructor(member, tcSym)); Symbol imSym = getInstMethSym(member); toAddL.add(NewMember.Instantiator(member, imSym)); } else if (member.isType()) { Symbol accSym = getInstMethSym(member); toAddL.add(NewMember.TypeAccessor(member, accSym)); } } if (!isNestedClass(classSym)) { Symbol tcSym = getTConstructorSym(classSym); toAddL.add(NewMember.TypeConstructor(classSym, tcSym)); Symbol ciSym = getClassInitSym(classSym); toAddL.add(NewMember.ClassInitialiser(classSym, ciSym, tcSym)); Symbol imSym = getInstMethSym(classSym); toAddL.add(NewMember.Instantiator(classSym, imSym)); } toAdd = (NewMember[])toAddL.toArray(new NewMember[toAddL.size()]); membersToAdd.put(classSym, toAdd); } return toAdd; } private Symbol[] paramsToAdd(Symbol methSym) { Symbol[] toAdd = (Symbol[])paramsToAdd.get(methSym); if (toAdd == null) { Symbol[] tparams = methSym.typeParams(); ArrayList toAddL = new ArrayList(); for (int i = 0; i < tparams.length; ++i) toAddL.add(getAccessorSym(tparams[i])); toAdd = (Symbol[])toAddL.toArray(new Symbol[toAddL.size()]); paramsToAdd.put(methSym, toAdd); } return toAdd; } /** * Return true iff the given symbol is not a polymorphic * primitive, which shouldn't get type parameters as value * parameters. */ private boolean monoPrimitive(Symbol sym) { return sym.isJava() || sym == ARRAY_CONSTRUCTOR || sym == defs.OBJECT_SYNCHRONIZED || sym == defs.ANY_IS || sym == defs.ANY_AS; } public Type transformInfo(Symbol symbol, Type type) { if (symbol.isClass()) { NewMember[] toAdd = membersToAdd(symbol); if (toAdd.length == 0) return type; else { Scope newMembers = new Scope(symbol.members()); for (int i = 0; i < toAdd.length; ++i) newMembers.enterOrOverload(toAdd[i].symbolToAdd()); return Type.compoundType(type.parents(), newMembers, symbol); } } else if (type.typeParams().length > 0 && !monoPrimitive(symbol)) { // Polymorphic method/constructor: // - add a value parameter for every type parameter. switch (type) { case PolyType(Symbol[] tparams, Type.MethodType(Symbol[] vparams, Type result)): List newVParams = new LinkedList(Arrays.asList(paramsToAdd(symbol))); newVParams.addAll(Arrays.asList(vparams)); Symbol[] newVParamsA = (Symbol[]) newVParams.toArray(new Symbol[newVParams.size()]); return new Type.PolyType(tparams, new Type.MethodType(newVParamsA, result)); default: throw Debug.abort("unexpected type: ", type); } } else return type; } private boolean isNestedClass(Symbol classSym) { return !classSym.owner().isPackageClass(); } public void apply(CompilationUnit unit) { transformer.apply(unit); } private class TV_Transformer extends GenTransformer { private Symbol currentOwner; public TV_Transformer(Global global) { super(global); } public Tree transform(Tree tree) { try { return transform0(tree); } catch (Error e) { System.out.println("tree: " + tree); throw e; } } public Tree transform0(Tree tree) { switch (tree) { case ClassDef(int mods, Name name, Tree.AbsTypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree.Template impl): Symbol sym = tree.symbol(); // if (impl.symbol().isNone()) // throw new Error("no symbol for " + tree); TreeList newBody = new TreeList(); // Add members (accessors and instantiators) NewMember[] toAdd = membersToAdd(sym); for (int i = 0; i < toAdd.length; ++i) { switch (toAdd[i]) { case TypeAccessor(Symbol memSym, Symbol accSym): newBody.append(typeAccessorBody(memSym, accSym)); break; case TypeConstructor(Symbol memSym, Symbol tcSym): newBody.append(tConstructorVal(memSym, tcSym)); break; case Instantiator(Symbol memSym, Symbol insSym): newBody.append(instantiatorBody(memSym, insSym)); break; case ClassInitialiser(Symbol memSym, Symbol ciSym, Symbol tcSym): newBody.append(classInitialiser(memSym, ciSym, tcSym)); break; } } newBody.append(transform(impl.body, impl.symbol())); Symbol pConst = sym.primaryConstructor(); return gen.ClassDef(sym, transform(impl.parents, pConst), impl.symbol(), newBody.toArray()); case DefDef(_, _, _, _, _, Tree rhs): Symbol symbol = getSymbolFor(tree); // TODO maybe use "overrides" method instead of name // to identify the "getType" method. if (symbol.name == Names.getType) { // Correct the body of the getType method which, // until now, was a placeholder (introduced by // RefCheck). rhs = scalaClassType(symbol.pos, symbol.owner().type(), symbol, EENV); } return gen.DefDef(symbol, transform(rhs, symbol)); case ValDef(_, _, Tree tpe, Literal(AConstant.ZERO)): // transform default values: // val x: T = _ // becomes // val x: T = asValue(T).defaultValue() Symbol symbol = getSymbolFor(tree); Tree defaultValue = gen.mkRef(tree.pos, typeAsValue(tree.pos, tpe.type, currentOwner, EENV), defs.TYPE_DEFAULTVALUE()); Tree rhs = gen.mkApply__(tree.pos, defaultValue); return gen.ValDef(symbol, rhs); case ValDef(_, _, _, Tree rhs): Symbol symbol = getSymbolFor(tree); return gen.ValDef(symbol, transform(rhs, symbol)); case New(Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs)): if (fun.symbol() == ARRAY_CONSTRUCTOR && false) { // Transform array creations: // new Array[T](size) // becomes // asValue(T).newArray[T](size) assert targs.length == 1; assert vargs.length == 1; Tree newArrayfun = gen.mkRef(tree.pos, typeAsValue(targs[0].pos, targs[0].type, currentOwner, EENV), defs.TYPE_NEWARRAY()); return gen.mkApplyTV(newArrayfun, targs, vargs); } else return super.transform(tree); case Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs): Symbol funSym = fun.symbol(); if (funSym == defs.ANY_IS) { assert targs.length == 1 && vargs.length == 0; Type type = targs[0].type; Tree expr = transform(qualifierOf(fun)); return isTrivialType(type) ? super.transform(tree) : genInstanceTest(tree.pos, expr, type); } else if (funSym == defs.ANY_AS) { // Transform instance tests: // e.asInstanceOf[T] // becomes: // asValue(T).checkCastability(e).asInstanceOf[T] // unless T is a "simple" type for which a Java // instance test is sufficient, in which case the // expression is left as is. assert targs.length == 1 && vargs.length == 0; Type type = targs[0].type; Tree expr = transform(qualifierOf(fun)); return isTrivialType(type) ? super.transform(tree) : genTypeCast(tree.pos, expr, type); } else if (!monoPrimitive(funSym)) { // Transform applications to pass types as values: // f[T1, ...](v1, ...) // becomes // f[T1, ...](asValue(T1), ..., v1, ...) Tree[] newVArgs = transform(vargs); Tree[] finalVArgs = new Tree[newVArgs.length + targs.length]; for (int i = 0; i < targs.length; ++i) finalVArgs[i] = typeAsValue(targs[i].pos, targs[i].type, currentOwner, EENV); System.arraycopy(newVArgs, 0, finalVArgs, targs.length, newVArgs.length); return gen.mkApplyTV(tree.pos, transform(fun), targs, finalVArgs); } else return super.transform(tree); default: return super.transform(tree); } } private Tree transform(Tree tree, Symbol currentOwner) { Symbol bkpOwner = this.currentOwner; this.currentOwner = currentOwner; Tree newTree = transform(tree); this.currentOwner = bkpOwner; return newTree; } private Tree[] transform(Tree[] trees, Symbol currentOwner) { Symbol bkpOwner = this.currentOwner; this.currentOwner = currentOwner; Tree[] newTrees = transform(trees); this.currentOwner = bkpOwner; return newTrees; } private int level(Symbol sym) { Symbol superClass = sym.parents()[0].symbol(); assert superClass != Symbol.NONE : sym; if (superClass == defs.ANY_CLASS) return 0; else return 1 + level(superClass); } /** * Return a method giving access to the given type, as a * value. */ private Tree.DefDef typeAccessorBody(Symbol typSym, Symbol accSym) { Tree rhs; if (typSym.isAbstractType()) rhs = Tree.Empty; else if (typSym.isClass()) rhs = scalaClassType(typSym.pos, typSym.type(), accSym, EENV); else { final Symbol[] vparams = accSym.valueParams(); final int pos = accSym.pos; final HashMap varMap = new HashMap(); Symbol[] tparams = typSym.typeParams(); for (int i = 0; i < tparams.length; ++i) varMap.put(tparams[i], new Integer(i)); TEnv tEnv = new TEnv() { public boolean definesVar(Symbol sym) { return varMap.containsKey(sym); } public Tree treeForVar(Symbol sym) { int idx = ((Integer)varMap.get(sym)).intValue(); Tree array = gen.mkLocalRef(pos, vparams[0]); return gen.mkArrayGet(pos, array, idx); } }; rhs = typeAsValue(typSym.pos, typSym.type(), accSym, tEnv); } return gen.DefDef(accSym, rhs); } private Tree tConstructorVal(Symbol clsSym, Symbol tcSym) { return gen.ValDef(tcSym, tcSym.isStatic() ? Tree.Empty : tConstructorRHS(tcSym.pos, clsSym, tcSym)); } private Tree classInitialiser(Symbol clsSym, Symbol ciSym, Symbol tcSym) { if (tcSym.isStatic()) { int pos = tcSym.pos; Tree rhs = tConstructorRHS(pos, clsSym, ciSym); Tree assign = gen.Assign(pos, gen.Ident(pos, tcSym), rhs); return gen.DefDef(ciSym, assign); } else return Tree.Empty; } private Tree tConstructorRHS(int pos, Symbol clsSym, Symbol owner) { int zCount = 0, mCount = 0, pCount = 0; Symbol[] tparams = clsSym.typeParams(); for (int i = 0; i < tparams.length; ++i) { if ((tparams[i].flags & Modifiers.COVARIANT) != 0) ++pCount; else if ((tparams[i].flags & Modifiers.CONTRAVARIANT) != 0) ++mCount; else ++zCount; } Ancestor[][] disp = computeDisplay(clsSym); int[] displayCode = getDisplayCode(computeDisplay(clsSym)); Tree[] tcArgs = new Tree[] { gen.mkIntLit(pos, level(clsSym)), gen.mkStringLit(pos, prims.getJREClassName(clsSym)), isNestedClass(clsSym) ? gen.This(pos, clsSym.owner()) : gen.mkNullLit(pos), gen.mkIntLit(pos, zCount), gen.mkIntLit(pos, mCount), gen.mkIntLit(pos, pCount), gen.mkBooleanLit(pos, clsSym.parents()[0].symbol().isJava()), mkNewIntLitArray(pos, displayCode, owner) }; Symbol tcConst = defs.TYPECONSTRUCTOR_CLASS.primaryConstructor(); Tree tcCall = gen.mkApply_V(pos, gen.mkGlobalRef(pos, tcConst), tcArgs); return gen.New(pos, tcCall); } private Tree mkNewIntLitArray(int pos, int[] values, Symbol owner) { Tree[] intLits = new Tree[values.length]; for (int i = 0; i < values.length; ++i) intLits[i] = gen.mkIntLit(pos, values[i]); return gen.mkNewArray(pos, defs.INT_TYPE(), intLits, owner); } /** * Return a method to instantiate the given type. */ private Tree.DefDef instantiatorBody(Symbol clsSym, Symbol insSym) { // TODO fix flags for all symbols below final int pos = clsSym.pos; final Symbol[] vparams = insSym.valueParams(); Tree[] body = new Tree[2]; // Generate call to "getInstantiation" method of // constructor. Tree getInstFun = gen.Select(pos, gen.mkLocalRef(pos, getTConstructorSym(clsSym)), defs.TYPECONSTRUCTOR_GETINSTANTIATION()); Tree[] getInstArgs = new Tree[]{ gen.mkLocalRef(pos, vparams[0]) }; Symbol instVal = insSym.newVariable(pos, 0, Name.fromString("inst")); instVal.setInfo(defs.SCALACLASSTYPE_TYPE()); Tree instValDef = gen.ValDef(instVal, gen.mkApply_V(pos, getInstFun, getInstArgs)); // Generate test to see if a call to "instantiate" is // necessary. Tree cond = gen.mkApply_V(pos, gen.Select(pos, gen.mkLocalRef(pos, instVal), defs.ANY_BANGEQ), new Tree[] { gen.mkNullLit(pos) }); Tree thenP = gen.mkLocalRef(pos, instVal); Tree instFun = gen.Select(pos, gen.mkLocalRef(pos, getTConstructorSym(clsSym)), defs.TYPECONSTRUCTOR_INSTANTIATE()); Tree[] instArgs = new Tree[] { gen.mkLocalRef(pos, vparams[0]) }; Tree instCall = gen.mkApply_V(pos, instFun, instArgs); final HashMap varMap = new HashMap(); Symbol[] tparams = clsSym.typeParams(); for (int i = 0; i < tparams.length; ++i) varMap.put(tparams[i], new Integer(i)); // Type environment mapping the type parameters of the // class to their corresponding element in the "types" // array passed to this instantiator. TEnv tEnv = new TEnv() { public boolean definesVar(Symbol sym) { return varMap.containsKey(sym); } public Tree treeForVar(Symbol sym) { int idx = ((Integer)varMap.get(sym)).intValue(); Tree array = gen.mkLocalRef(pos, vparams[0]); return gen.mkArrayGet(pos, array, idx); } }; Type[] parents = clsSym.parents(); TreeList parentTypes = new TreeList(); for (int i = 0; i < parents.length; ++i) { Type parent = parents[i]; if (!parent.symbol().isJava()) { Tree parentType = typeAsValue(pos, parent, insSym, tEnv); parentTypes.append(parentType); } } Tree parentsArray = gen.mkNewArray(pos, defs.SCALACLASSTYPE_TYPE(), parentTypes.toArray(), insSym); Tree setParentsFun = gen.Select(pos, instCall, defs.SCALACLASSTYPE_SETPARENTS()); Tree elseP = gen.mkApply_V(pos, setParentsFun, new Tree[] { parentsArray }); Tree ifExpr = gen.If(pos, cond, thenP, elseP, defs.SCALACLASSTYPE_TYPE()); return gen.DefDef(insSym, gen.mkBlock(pos, instValDef, ifExpr)); } /** * Generate code to test if the given expression is an * instance of the given type. */ private Tree genInstanceTest(int pos, Tree expr, Type tp) { Tree tpVal = typeAsValue(pos, tp, currentOwner, EENV); Tree fun = gen.Select(pos, tpVal, defs.TYPE_ISINSTANCE()); return gen.mkApply_V(pos, fun, new Tree[] { expr }); } /** * Generate code to cast the given value to the given type. */ private Tree genTypeCast(int pos, Tree expr, Type tp) { Tree tpVal = typeAsValue(pos, tp, currentOwner, EENV); Tree fun = gen.Select(pos, tpVal, defs.TYPE_CHECKCASTABILITY()); Tree checkCastCall = gen.mkApply_V(pos, fun, new Tree[] { expr }); return gen.mkAsInstanceOf(pos, checkCastCall, tp); } /** * Return true iff the given type is "trivial", that is if it * is representable as a Java type without loss of * information. */ private boolean isTrivialType(Type tp) { switch (tp) { case ConstantType(Type base, _): return isTrivialType(base); case TypeRef(_, Symbol sym, Type[] args): return sym.isStatic() && args.length == 0; case SingleType(_, _): case ThisType(_): // TODO check case CompoundType(_, _): // TODO check return false; default: throw Debug.abort("unexpected type", tp); } } private boolean isArrayClass(Symbol sym) { return sym == defs.ARRAY_CLASS; } /** * Transform a type into a tree representing it. */ private Tree typeAsValue(int pos, Type tp, Symbol owner, TEnv env) { switch (tp) { case ConstantType(Type base, _): return typeAsValue(pos, base, owner, env); case TypeRef(Type pre, Symbol sym, Type[] args): if (env.definesVar(sym)) { assert args.length == 0; return env.treeForVar(sym); } else if (isArrayClass(sym)) { assert args.length == 1; return arrayType(pos, sym, args[0], owner, env); } else if (predefTypes.containsKey(sym)) { return gen.mkGlobalRef(pos, (Symbol)predefTypes.get(sym)); } else if (sym.isJava()) { assert args.length <= 1 : Debug.show(sym) + " " + args.length; return javaType(pos, sym); } else if (!sym.owner().isMethod()) { // Reference to a "global" type. if (owner == null) throw new Error("null owner for " + Debug.show(tp)); return scalaClassType(pos, tp, owner, env); } else { assert !isValuePrefix(pre) : tp; return gen.mkLocalRef(pos, getAccessorSym(sym)); } case SingleType(Type pre, Symbol sym): return singleType(pos, (Type.SingleType)tp); case ThisType(Symbol sym): return thisType(pos, sym); case CompoundType(Type[] parts, Scope members): return compoundType(pos, parts, members, owner, env); default: throw Debug.abortIllegalCase(tp); } } private Tree arrayType(int pos, Symbol sym, Type elemType, Symbol owner, TEnv env) { Tree constr = gen.mkPrimaryConstructorGlobalRef(pos, defs.JAVAREFARRAYTYPE_CLASS); Tree[] args = new Tree[]{ typeAsValue(pos, elemType, owner, env) }; return gen.New(pos, gen.mkApply_V(constr, args)); } private Tree javaType(int pos, Symbol sym) { Tree constr = gen.mkPrimaryConstructorGlobalRef(pos, defs.JAVACLASSTYPE_CLASS); Tree nameLit = gen.mkStringLit(pos, prims.getJREClassName(sym)); Tree[] args = new Tree[] { nameLit }; return gen.New(pos, gen.mkApply_V(constr, args)); } private Tree thisType(int pos, Symbol sym) { Tree constr = gen.mkPrimaryConstructorGlobalRef(pos, defs.SINGLETYPE_CLASS); Tree[] args = new Tree[] { gen.This(pos, sym) }; return gen.New(pos, gen.mkApply_V(constr, args)); } private Tree singleType(int pos, Type.SingleType tp) { Tree constr = gen.mkPrimaryConstructorGlobalRef(pos, defs.SINGLETYPE_CLASS); Tree[] args = new Tree[] { gen.mkQualifier(pos, tp) }; return gen.New(pos, gen.mkApply_V(constr, args)); } private Tree compoundType(int pos, Type[] parts, Scope members, Symbol owner, TEnv env) { Tree[] partsT = new Tree[parts.length]; for (int i = 0; i < parts.length; ++i) partsT[i] = typeAsValue(pos, parts[i], owner, env); Tree[] constrArgs = new Tree[] { gen.mkNewArray(pos, defs.CLASSTYPE_TYPE(), partsT, owner), gen.mkBooleanLit(pos, members.isEmpty()) }; Tree constr = gen.mkPrimaryConstructorGlobalRef(pos, defs.COMPOUNDTYPE_CLASS); return gen.New(pos, gen.mkApply_V(constr, constrArgs)); } private Tree scalaClassType(int pos, Type tp, Symbol owner, TEnv env) { switch (tp) { case TypeRef(Type pre, Symbol sym, Type[] args): Symbol insSym = getInstMethSym(sym); Tree preFun = isNestedClass(sym) ? gen.Select(pos, gen.mkQualifier(pos, pre), insSym) : gen.Ident(pos, insSym); // TODO special case for monomorphic cases Tree[] insArgs; if (true || args.length > 0) { Tree[] elems = new Tree[args.length]; int[] perm = typeParamsPermutation(sym.typeParams()); for (int i = 0; i < args.length; ++i) elems[i] = typeAsValue(pos, args[perm[i]], owner, env); insArgs = new Tree[] { gen.mkNewArray(pos, defs.TYPE_TYPE(), elems, owner) }; } else insArgs = Tree.EMPTY_ARRAY; return gen.mkApply_V(pos, preFun, insArgs); default: throw Debug.abort("unexpected type: ", tp); } } private final int VARIANT = Modifiers.COVARIANT | Modifiers.CONTRAVARIANT; /** * Compute the (unique) permutation which puts all invariant * type parameters first, followed by the contravariant ones, * then the covariants, preserving the relative ordering of * arguments with same variance. */ private int[] typeParamsPermutation(Symbol[] params) { int[] tparamsPerm = new int[params.length]; int permIdx = 0; for (int i = 0; i < params.length; ++i) if ((params[i].flags & VARIANT) == 0) tparamsPerm[permIdx++] = i; for (int i = 0; i < params.length; ++i) if ((params[i].flags & Modifiers.CONTRAVARIANT) != 0) tparamsPerm[permIdx++] = i; for (int i = 0; i < params.length; ++i) if ((params[i].flags & Modifiers.COVARIANT) != 0) tparamsPerm[permIdx++] = i; assert permIdx == tparamsPerm.length; return tparamsPerm; } /** * Extract qualifier from a tree, which must be a Select node. */ private Tree qualifierOf(Tree tree) { switch (tree) { case Select(Tree qualifier, _): return qualifier; default: throw Debug.abort("cannot extract qualifier from ", tree); } } private boolean isValuePrefix(Type pre) { switch (pre) { case ThisType(Symbol clazz): return !(clazz.isPackage() || clazz.isNone()); case NoPrefix: return false; default: return true; } } private Ancestor[][] computeDisplay0(Symbol classSym) { Symbol[] scalaParents = scalaParents(classSym); int level = level(classSym); ArrayList/*<Ancestor>*/[] display = new ArrayList[level + 1]; for (int l = 0; l < display.length; ++l) display[l] = new ArrayList(); display[level].add(new Ancestor(classSym, -1, -1)); // Go over parents from left to right and add missing // ancestors to the display, remembering where they come // from. for (int p = 0; p < scalaParents.length; ++p) { Symbol parentSymbol = scalaParents[p]; assert parentSymbol != Symbol.NONE; Ancestor[][] parentDisplay = computeDisplay(parentSymbol); assert parentDisplay.length <= display.length; for (int l = 0; l < parentDisplay.length; ++l) { ArrayList/*<Ancestor>*/ myRow = display[l]; Ancestor[] parentRow = parentDisplay[l]; for (int i = 0; i < parentRow.length; ++i) { Symbol sym = parentRow[i].symbol; Iterator myRowIt = myRow.iterator(); boolean alreadyExists = false; while (!alreadyExists && myRowIt.hasNext()) { Ancestor myAncestor = (Ancestor)myRowIt.next(); if (myAncestor.symbol == sym) alreadyExists = true; } if (!alreadyExists) myRow.add(new Ancestor(sym, p, i)); } } } Ancestor[][] finalDisplay = new Ancestor[level + 1][]; for (int i = 0; i < finalDisplay.length; ++i) { finalDisplay[i] = (Ancestor[]) display[i].toArray(new Ancestor[display[i].size()]); } return finalDisplay; } private Ancestor[][] computeDisplay(Symbol classSym) { Ancestor[][] display = (Ancestor[][])displayCache.get(classSym); if (display == null) { display = computeDisplay0(classSym); displayCache.put(classSym, display); // debugPrintDisplay(classSym, display); } return display; } private Symbol[] scalaParents(Symbol classSym) { Type[] parentTypes = classSym.parents(); ArrayList scalaParents = new ArrayList(); for (int i = 0; i < parentTypes.length; ++i) { Symbol parentSym = parentTypes[i].symbol(); if (!parentSym.isJava()) scalaParents.add(parentSym); } return (Symbol[]) scalaParents.toArray(new Symbol[scalaParents.size()]); } private int[] getDisplayCode(Ancestor[][] display) { ArrayList/*<List<Ancestor>>*/ prunedRows = new ArrayList(); int totalSize = 0; for (int l = 0; l < display.length; ++l) { Ancestor[] row = display[l]; ArrayList/*<Ancestor>*/ prunedRow = new ArrayList(row.length); for (int i = 0; i < row.length; ++i) { if (row[i].parentIndex > 0) prunedRow.add(row[i]); } prunedRows.add(prunedRow); totalSize += 1 + 2 * prunedRow.size(); } int[] res = new int[totalSize]; int i = 0; Iterator rowsIt = prunedRows.iterator(); while (rowsIt.hasNext()) { ArrayList row = (ArrayList)rowsIt.next(); res[i++] = row.size(); Iterator ancIt = row.iterator(); while (ancIt.hasNext()) { Ancestor anc = (Ancestor)ancIt.next(); res[i++] = anc.parentIndex; res[i++] = anc.position; } } assert i == totalSize; return res; } } // Debugging function private void debugPrintDisplay(Symbol sym, Ancestor[][] display) { System.out.println("display for " + Debug.show(sym)); for (int l = 0; l < display.length; ++l) { System.out.print(" [" + l + "] "); for (int i = 0; i < display[l].length; ++i) { if (i > 0) System.out.print(" "); System.out.println(" " + Debug.show(display[l][i].symbol) + "/par" + display[l][i].parentIndex + "/pos" + display[l][i].position); } } } private static class TEnv { public boolean definesVar(Symbol sym) { return false; } public Tree treeForVar(Symbol sym) { throw Debug.abort("no tree for variable " + sym); } } private static class NewMember { public Symbol symbolToAdd() { switch (this) { case TypeAccessor(_, Symbol accSym): return accSym; case TypeConstructor(_, Symbol tcSym): return tcSym; case Instantiator(_, Symbol insSym): return insSym; case ClassInitialiser(_, Symbol ciSym, _): return ciSym; default: throw Debug.abort("unexpected case"); } } public case TypeAccessor(Symbol memSym, Symbol accSym); public case TypeConstructor(Symbol memSym, Symbol tcSym); public case Instantiator(Symbol memSym, Symbol insSym); public case ClassInitialiser(Symbol memSym, Symbol ciSym, Symbol tcSym); } private static class Ancestor { public static final Ancestor[] EMPTY_ARRAY = new Ancestor[0]; public final Symbol symbol; public final int parentIndex; public final int position; public Ancestor(Symbol symbol, int parentIndex, int position) { this.symbol = symbol; this.parentIndex = parentIndex; this.position = position; } } }
package helloworld.cpd4414.pkg02; /** * * @author c0587637 */ public class HelloWorldCPD441402 { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Len Payne"); System.out.println("Jasmyn Newton"); System.out.println("Kyle Crossman"); System.out.println("Lewis Menelaws"); System.out.println("Jason Preston"); } }
package gov.nih.nci.cabig.caaers.api.impl; import static gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType.AMEND; import static gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType.WITHDRAW; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.dao.AdverseEventRecommendedReportDao; import gov.nih.nci.cabig.caaers.dao.ParticipantDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.TreatmentAssignmentDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventCtcTerm; import gov.nih.nci.cabig.caaers.domain.AdverseEventMeddraLowLevelTerm; import gov.nih.nci.cabig.caaers.domain.AdverseEventRecommendedReport; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.AeTerminology; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.Identifier; import gov.nih.nci.cabig.caaers.domain.LocalOrganization; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.ReportTableRow; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment; import gov.nih.nci.cabig.caaers.domain.dto.ApplicableReportDefinitionsDTO; import gov.nih.nci.cabig.caaers.domain.dto.EvaluationResultDTO; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper; import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.integration.schema.adverseevent.AdverseEventType; import gov.nih.nci.cabig.caaers.integration.schema.saerules.AEsOutputMessage; import gov.nih.nci.cabig.caaers.integration.schema.saerules.AdverseEventResult; import gov.nih.nci.cabig.caaers.integration.schema.saerules.AdverseEvents; import gov.nih.nci.cabig.caaers.integration.schema.saerules.EvaluateAEsInputMessage; import gov.nih.nci.cabig.caaers.integration.schema.saerules.EvaluateAEsOutputMessage; import gov.nih.nci.cabig.caaers.integration.schema.saerules.EvaluatedAdverseEventResults; import gov.nih.nci.cabig.caaers.integration.schema.saerules.RecommendedActions; import gov.nih.nci.cabig.caaers.integration.schema.saerules.SaveAndEvaluateAEsInputMessage; import gov.nih.nci.cabig.caaers.integration.schema.saerules.SaveAndEvaluateAEsOutputMessage; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.service.RecommendedActionService; import gov.nih.nci.cabig.caaers.service.migrator.adverseevent.AdverseEventConverter; import gov.nih.nci.cabig.caaers.service.migrator.adverseevent.SAEAdverseEventReportingPeriodConverter; import gov.nih.nci.cabig.caaers.utils.DateUtils; import gov.nih.nci.cabig.caaers.validation.ValidationErrors; import gov.nih.nci.cabig.caaers.ws.faults.CaaersFault; import gov.nih.nci.cabig.ctms.lang.NowFactory; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.MessageSource; /** * EvaluationService evaluate rules on the given AE's submitted by Web service. * * @author MedaV * */ public class SAEEvaluationServiceImpl implements ApplicationContextAware { private AdverseEventRecommendedReportDao adverseEventRecommendedReportDao; private StudyDao studyDao; private TreatmentAssignmentDao treatmentAssignmentDao; private ParticipantDao participantDao; private StudyParticipantAssignmentDao studyParticipantAssignmentDao; private SAEAdverseEventReportingPeriodConverter reportingPeriodConverter; private ReportDefinitionDao reportDefinitionDao; /** The now factory. */ private NowFactory nowFactory; private AdverseEventManagementServiceImpl adverseEventManagementService; private EvaluationService evaluationService; private ApplicationContext applicationContext; private MessageSource messageSource; private AdverseEventConverter converter; private RecommendedActionService recommendedActionService; private enum RequestType{SaveEvaluate, Evaluate}; private static String DEF_ERR_MSG = "Error evaluating adverse events with SAE rules"; private static Log logger = LogFactory.getLog(SAEEvaluationServiceImpl.class); /** * Process and Save the Adverse Events. * * @param saveAndEvaluateAEsInputMessage * @return * @throws CaaersFault */ public SaveAndEvaluateAEsOutputMessage saveAndProcessAdverseEvents(SaveAndEvaluateAEsInputMessage saveAndEvaluateAEsInputMessage) throws CaaersFault { Map<AdverseEvent, AdverseEventResult> mapAE2DTO = new HashMap<AdverseEvent, AdverseEventResult>(); if ( saveAndEvaluateAEsInputMessage == null ) { throw Helper.createCaaersFault(DEF_ERR_MSG, "WS_SAE_007", messageSource.getMessage("WS_SAE_007", new String[]{}, "", Locale.getDefault()) ); } SaveAndEvaluateAEsOutputMessage saveAndEvaluateAEsOutputMessage = (SaveAndEvaluateAEsOutputMessage)createResponseObject(RequestType.SaveEvaluate); try { // 0. Load the study required. String studyIdentifier = saveAndEvaluateAEsInputMessage.getCriteria().getStudyIdentifier(); Study study = fetchStudy(studyIdentifier); // 1. Call the converter and make the required object. AdverseEventReportingPeriod reportingPeriod = reportingPeriodConverter.convert(saveAndEvaluateAEsInputMessage,mapAE2DTO); // 2. Persist AdverseEvents. ValidationErrors errors = new ValidationErrors(); reportingPeriod = adverseEventManagementService.createOrUpdateAdverseEvents(reportingPeriod, errors, true); if(errors.hasErrors()){ logger.error("Adverse Event Management Service create or update call failed :" + String.valueOf(errors)); if ( errors.getErrorAt(0).getCode().equals("NO-CODE")) throw Helper.createCaaersFault(DEF_ERR_MSG, errors.getErrorAt(0).getCode(), errors.getErrorAt(0).getMessage() + " " +errors.getErrorAt(0).getReplacementVariables()[0]); else throw Helper.createCaaersFault(DEF_ERR_MSG, errors.getErrorAt(0).getCode(), errors.getErrorAt(0).getMessage()); } // 3. fire Evaluation Service to identify SAE or not ? saveAndEvaluateAEsOutputMessage = (SaveAndEvaluateAEsOutputMessage)fireSAERules(reportingPeriod, study, mapAE2DTO,RequestType.SaveEvaluate,saveAndEvaluateAEsOutputMessage); // CAAERS-6613 re-save the AEs with the requiresReporting flag if(reportingPeriod != null){ for(AdverseEvent ae : reportingPeriod.getAdverseEvents()){ AdverseEventResult aeResult = findAdverseEvent(ae, mapAE2DTO); if(aeResult == null){ continue; } else if(aeResult.isRequiresReporting()){ ae.setRequiresReporting(true); } } // save the updated reporting period adverseEventManagementService.saveReportingPeriod(reportingPeriod); } } catch(CaaersSystemException ex) { throw Helper.createCaaersFault(DEF_ERR_MSG, ex.getErrorCode(), ex.getMessage()); } return saveAndEvaluateAEsOutputMessage; } /** * Process the adverse Events. * @param evaluateAEsInputMessage * @return * @throws CaaersFault */ public EvaluateAEsOutputMessage processAdverseEvents(EvaluateAEsInputMessage evaluateAEsInputMessage) throws CaaersFault { if ( evaluateAEsInputMessage == null ) { throw Helper.createCaaersFault(DEF_ERR_MSG, "WS_SAE_007", messageSource.getMessage("WS_SAE_007", new String[]{}, "", Locale.getDefault()) ); } gov.nih.nci.cabig.caaers.integration.schema.saerules.Study study = evaluateAEsInputMessage.getStudy(); if ( study == null ) { throw Helper.createCaaersFault(DEF_ERR_MSG, "WS_GEN_001", messageSource.getMessage("WS_GEN_001", new String[]{}, "", Locale.getDefault()) ); } if ( evaluateAEsInputMessage.getAdverseEvents() == null || evaluateAEsInputMessage.getAdverseEvents().getAdverseEvent() == null || evaluateAEsInputMessage.getAdverseEvents().getAdverseEvent().size() == 0 ) { throw Helper.createCaaersFault(DEF_ERR_MSG, "WS_SAE_006", messageSource.getMessage("WS_SAE_006", new String[]{}, "", Locale.getDefault()) ); } StudyParticipantAssignment spa = new StudyParticipantAssignment(); StudySite studySite = new StudySite(); Organization siteOrg = new LocalOrganization(); siteOrg.setNciInstituteCode(study.getParticipantSiteIdentifier()); studySite.setOrganization(siteOrg); spa.setStudySite(studySite); return processAdverseEvents(evaluateAEsInputMessage.getStudy().getStudyIdentifier(), evaluateAEsInputMessage.getAdverseEvents(),spa,evaluateAEsInputMessage.getStudy().getTreatmentAssignmentCode()); } public EvaluateAEsOutputMessage processAdverseEvents(String studyId, AdverseEvents adverseEvents, StudyParticipantAssignment assignment, String tacCode) throws CaaersFault { // Construct from the input Message. List<AdverseEvent> aes = new ArrayList<AdverseEvent>(); Map<AdverseEvent, AdverseEventResult> mapAE2DTO = new HashMap<AdverseEvent, AdverseEventResult>(); Study study = null; TreatmentAssignment tas = null; try { // Fetch the study from Database study = fetchStudy(studyId); AeTerminology terminology = study.getAeTerminology(); for (AdverseEventType adverseEventDto : adverseEvents.getAdverseEvent()) { AdverseEvent ae = new AdverseEvent(); converter.convertAdverseEventDtoToAdverseEventDomain(adverseEventDto, ae, terminology, null, null); aes.add(ae); AdverseEventResult result = new AdverseEventResult(); result.setAdverseEvent(adverseEventDto); result.setRequiresReporting(false); mapAE2DTO.put(ae, result); } if (tacCode != null) { tas = resolveTreatmentAssignment(tacCode, study); } } catch (CaaersSystemException e) { throw Helper.createCaaersFault(DEF_ERR_MSG, e.getErrorCode(), e.getMessage()); } // Populate AdverseEventReporting Period AdverseEventReportingPeriod period = new AdverseEventReportingPeriod(); period.setAdverseEvents(aes); period.setAssignment(assignment); period.setTreatmentAssignment(tas); if (assignment.getStudySite() != null) { assignment.getStudySite().setStudy(study); } /** * Fill the reporting period into ae's. */ for (AdverseEvent ae : aes) { ae.setReportingPeriod(period); } // Create the response Object. EvaluateAEsOutputMessage response = (EvaluateAEsOutputMessage)createResponseObject(RequestType.Evaluate); return (EvaluateAEsOutputMessage)fireSAERules(period, study, mapAE2DTO, RequestType.Evaluate, response); } /** * Retrieve TreatmentAssignment from the Study for the * TreatmentAssignmentCode * * @param tacCode * - String representing TreatmentAssignmentCode * @param study * - instance of Study * @return instance of TreatmentAssignment */ private TreatmentAssignment resolveTreatmentAssignment(String tacCode, Study study) { TreatmentAssignment ta = null; try { ta = treatmentAssignmentDao.getAssignmentsByStudyIdExactMatch(tacCode, study.getId()); } catch (Exception e) { throw new CaaersSystemException("WS_SAE_002", messageSource.getMessage("WS_SAE_002", new String[] { String.valueOf(study.getId()) }, "", Locale.getDefault())); } return ta; } /** * Fire the SAE on the Reporting Period Adverse Events. * @param reportingPeriod * @param study * @param mapAE2DTO * @return * @throws CaaersFault */ private AEsOutputMessage fireSAERules(AdverseEventReportingPeriod reportingPeriod, Study study, Map<AdverseEvent, AdverseEventResult> mapAE2DTO, RequestType requestType,AEsOutputMessage response) throws CaaersFault { response.setEvaluatedAdverseEventResults(new EvaluatedAdverseEventResults()); //populate the output list with the AdverseEventResult objects created for each AdverseEventType response.getEvaluatedAdverseEventResults().getAdverseEventResult().addAll(mapAE2DTO.values()); try { if ( requestType.equals(RequestType.SaveEvaluate)) { ((SaveAndEvaluateAEsOutputMessage)response).setLinkToReport(constructLinkToReport(study.getId(),reportingPeriod.getParticipant().getId(), reportingPeriod.getId())); } EvaluationResultDTO dto = evaluationService.evaluateSAERules(reportingPeriod, false); List<Integer> oldAe = getOldAdverseEvents(reportingPeriod); if ( requestType.equals(RequestType.SaveEvaluate)) { ((SaveAndEvaluateAEsOutputMessage)response).setRecommendedActions(findRecommendedActions(dto, reportingPeriod, oldAe)); populateActionTextAndDueDate(response); } // create/update/delete AE recommended reports manageAdverseEventRecommendedReports(dto); //has at least one SAE ? - mark hasSAE flag in the response if(requestType.equals(RequestType.SaveEvaluate)) { //CAAERS-6316 hasSAE is used to suggest that a recommended action is present if(!((SaveAndEvaluateAEsOutputMessage)response).getRecommendedActions().isEmpty()){ ((SaveAndEvaluateAEsOutputMessage)response).setHasSAE(true); } } //retrieve all the SAEs identified by rules engine, and //Mark the Requires reporting flag on AE for(AdverseEvent ae : dto.getAllSeriousAdverseEvents()) { // find DTO object corresponding to Adverse Event. AdverseEventResult aeDTO = null ; if ( requestType.equals(RequestType.SaveEvaluate)) { aeDTO = findAdverseEvent(ae,mapAE2DTO); } else { aeDTO = mapAE2DTO.get(ae); } if(aeDTO != null) { aeDTO.setRequiresReporting(true); } } for(Entry<AdverseEvent, AdverseEventResult> aer : mapAE2DTO.entrySet()) { final AdverseEvent ae = aer.getKey(); if(ae != null && ae.getRequiresReporting() != null && ae.getRequiresReporting() && !ae.isModified()) { aer.getValue().setRequiresReporting(true); } } } catch (Exception e) { logger.error(" Exception Occured when processing rules; " + e.toString()); throw Helper.createCaaersFault(DEF_ERR_MSG, "WS_SAE_001", messageSource.getMessage("WS_SAE_001", new String[]{}, "", Locale.getDefault()) ); } return response; } private List<Integer> getOldAdverseEvents(AdverseEventReportingPeriod reportingPeriod) { List<AdverseEvent> neae = reportingPeriod.getNonExpeditedAdverseEvents(); List<Integer> oldAe = new ArrayList<Integer>(); List<ExpeditedAdverseEventReport> aeReportList = reportingPeriod.getAeReports(); if(aeReportList != null && !aeReportList.isEmpty() && neae != null) { ExpeditedAdverseEventReport aeReport = aeReportList.get(aeReportList.size()-1); Iterator<AdverseEvent> aeIterator = neae.iterator(); while(aeIterator.hasNext()){ AdverseEvent ae = aeIterator.next(); if(aeReport.doesAnotherAeWithSameTermExist(ae) != null){ if(ae.getAddedToReportAtLeastOnce() != null && ae.getAddedToReportAtLeastOnce() && !ae.isModified()){ oldAe.add(ae.getId()); } } } } return oldAe; } private void populateActionTextAndDueDate(AEsOutputMessage response){ if(response instanceof SaveAndEvaluateAEsOutputMessage) { Date now = nowFactory.getNow(); for(RecommendedActions recActions: ((SaveAndEvaluateAEsOutputMessage) response).getRecommendedActions()){ //recActions.setDueDate(recActions.getDueDate()); recActions.setActionText(recActions.getAction().substring(0, 1).toUpperCase() + recActions.getAction(). substring(1, recActions.getAction().length()).toLowerCase() + " the " + recActions.getReport()); ReportDefinition reportDefinition = reportDefinitionDao.getByName(recActions.getReport()); Date baseDate = reportDefinition.getBaseDate(); Date dueDate = reportDefinition.getExpectedDueDate(baseDate == null ? now : baseDate); recActions.setDueDate(DateUtils.getDateWithTimeZone(dueDate).toString()); } } } private void refreshReportIndexMap(Map<Integer, ExpeditedAdverseEventReport> aeReportIndexMap) { Integer ZERO = new Integer(0); aeReportIndexMap.put(ZERO, null); } /** * Find the Actions to be recommended to the client * @param evaluationResult * @param reportingPeriod * @param response */ private List<RecommendedActions> findRecommendedActions(EvaluationResultDTO evaluationResult, AdverseEventReportingPeriod reportingPeriod, List<Integer> oldRows) { List<RecommendedActions> recommendedActions = new ArrayList<RecommendedActions>(); Map<Integer, ExpeditedAdverseEventReport> aeReportIndexMap = reportingPeriod.populateAeReportIndexMap(); Map<Integer, List<ReportTableRow>> recommendedReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); Map<Integer, List<ReportTableRow>> applicableReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); refreshReportIndexMap(aeReportIndexMap); recommendedActionService.generateRecommendedReportTable(evaluationResult, aeReportIndexMap, recommendedReportTableMap); ApplicableReportDefinitionsDTO applicableReportDefinitions = evaluationService.applicableReportDefinitions(reportingPeriod.getStudy(), reportingPeriod.getAssignment()); recommendedActionService.refreshApplicableReportTable(evaluationResult, aeReportIndexMap, applicableReportTableMap, applicableReportDefinitions); // This data structure is used for handling Create/Edit Scneario. List<ReportTableRow> ignoredRows = getListOfIgnoredRows(recommendedReportTableMap); for ( Integer aeReportId : recommendedReportTableMap.keySet()){ if(!oldRows.contains(aeReportId)) { List<ReportTableRow> applicableRows = applicableReportTableMap.get(aeReportId); if ( applicableRows != null) { findMatchingRecommendations(applicableRows, recommendedReportTableMap.get(aeReportId), recommendedActions, ignoredRows) ; } } } return recommendedActions; } /** * Find the corresponding applicable report table value of the recommended table value. * @param applicableRows * @param reportName * @return */ private ReportTableRow findApplicableRow(List<ReportTableRow> applicableRows,String reportName) { for ( ReportTableRow row: applicableRows) { if ( row.getReportDefinition().getName().equals(reportName) ) { return row; } } return null; } /** * Maintain the list of rows with preSelectedFlag is true. * @param applicableRows * @return */ private List<ReportTableRow> findPreSelectedRows(List<ReportTableRow> applicableRows) { List<ReportTableRow> preSelectedRows = new ArrayList<ReportTableRow>(); for ( ReportTableRow row: applicableRows) { if ( row.isPreSelected()) { preSelectedRows.add(row); } } return preSelectedRows; } /** * Return true ifAny of the report of the Group is checked. * @param row * @param preselectedRows * @return */ private boolean isAnyInGroupChecked(ReportTableRow row,List<ReportTableRow> preselectedRows) { boolean isfound = false; for (ReportTableRow preSelectedRow: preselectedRows) { if ( preSelectedRow.getReportDefinition() != null && row.getReportDefinition() != null && preSelectedRow.getReportDefinition().getGroup() != null && row.getReportDefinition().getGroup() != null && preSelectedRow.getReportDefinition().getGroup().getName().equals(row.getReportDefinition().getGroup().getName())) { isfound = true; break; } } return isfound; } /** * Convert the Report Table Row to Action object for webservice to send the output. * @param row * @param preselectedRows * @return */ private RecommendedActions returnActionFromRow(ReportTableRow row, List<ReportTableRow> preselectedRows) { RecommendedActions action = new RecommendedActions(); action.setReport(row.getReportDefinition().getName()); if ( row.isPreSelected()) { // If the row is pre-selected. action.setAction(row.getAction().getDisplayName()); action.setDue(row.getDue()); action.setStatus(row.getStatus()); } else { if ( isAnyInGroupChecked(row, preselectedRows)) { // If the any one of the Report in the group is selected. action.setAction(row.getGrpAction().getDisplayName()); action.setDue(row.getGrpDue()); action.setStatus(row.getGrpStatus()); } else { // Other Actions. action.setAction(row.getOtherAction().getDisplayName()); action.setDue(row.getOtherDue()); action.setStatus(row.getOtherStatus()); } } return action; } /** * Return the matched is true only when the Action is Edit. * @param recommendedReportTableMap * @param ignoredRow * @return */ private boolean findMatchingRecommendedRow(Map<Integer, List<ReportTableRow>> recommendedReportTableMap, ReportTableRow ignoredRow) { boolean isFound = false; for ( Integer aeReportId :recommendedReportTableMap.keySet() ) { if ( aeReportId == 0 ) continue; for ( ReportTableRow row : recommendedReportTableMap.get(aeReportId)) { if ( (recommendedReportTableMap.size() == 2) && row.getAction().getDisplayName().equals("Edit")) { // Condition will Evaluate isFound = true; break; } } if ( isFound) break; } return isFound; } /** * This is to handle the special case of Create-Edit Scenario. * */ private List<ReportTableRow> getListOfIgnoredRows(Map<Integer, List<ReportTableRow>> recommendedReportTableMap) { List<ReportTableRow> ignoredRows = new ArrayList<ReportTableRow>(); Integer Zero = new Integer(0); List<ReportTableRow> rows = recommendedReportTableMap.get(Zero); if ( rows == null ) return ignoredRows; for ( ReportTableRow row : rows ) { boolean isFound = findMatchingRecommendedRow(recommendedReportTableMap, row); if ( isFound ) ignoredRows.add(row); } return ignoredRows; } private boolean isMatchedIgnoredRow(List<ReportTableRow> ignoredRows,ReportTableRow recommRow) { boolean isFound = false; for ( ReportTableRow row: ignoredRows ) { if ( row.getAction().equals(recommRow.getAction()) && row.getReportDefinition().getName().equals(recommRow.getReportDefinition().getName())) { isFound = true; break; } } return isFound; } /** * Return the Recommendations required report group. ( AMend/WithDraw/Create/Edit). * * @param applicableRows * @param recommRows * @param recommendedActions */ private void findMatchingRecommendations(List<ReportTableRow> applicableRows, List<ReportTableRow> recommRows, List<RecommendedActions> recommendedActions, List<ReportTableRow> ignoredRows) { // Find the report group of the pre-selected row. List<ReportTableRow> preselectedRows = findPreSelectedRows(applicableRows); for (ReportTableRow recommRow : recommRows) { ReportTableRow applicableRow = findApplicableRow(applicableRows, recommRow.getReportDefinition().getName()); if ( applicableRow == null || isMatchedIgnoredRow(ignoredRows, recommRow)) continue; RecommendedActions action = returnActionFromRow(applicableRow, preselectedRows); recommendedActions.add(action); boolean withdrawOrAmend = StringUtils.equals(action.getAction(), WITHDRAW.getDisplayName()) || StringUtils.equals(action.getAction(), AMEND.getDisplayName()) ; if (withdrawOrAmend) { for (ReportTableRow preselectedRow: preselectedRows ) { if ( preselectedRow != null ) { // Update the Group Due. action.setDue(applicableRow.getGrpDue()); // find if the report already exists. RecommendedActions preSelectedAction = null; for (RecommendedActions actionIter: recommendedActions) { if ( actionIter.getReport().equals(preselectedRow.getReportDefinition().getName()) && actionIter.getAction().equals("Create") ) { preSelectedAction = actionIter; break; } } if ( preSelectedAction == null){ // If the Create Action is not occured before, Create one manually. preSelectedAction = new RecommendedActions(); preSelectedAction.setAction(ReportDefinitionWrapper.ActionType.CREATE.toString()); // Make it Create. preSelectedAction.setStatus("Not Started"); preSelectedAction.setReport(preselectedRow.getReportDefinition().getName()); preSelectedAction.setDue(preselectedRow.getDue()); recommendedActions.add(preSelectedAction); } else { // If it is already occured, Update the due time. ReportTableRow createAction = findApplicableRow(applicableRows, preSelectedAction.getReport()) ; preSelectedAction.setDue(createAction.getDue()); } } } } } } public AdverseEventResult findAdverseEvent(AdverseEvent thatAe,Map<AdverseEvent, AdverseEventResult> mapAE2DTO){ for(AdverseEvent thisAe : mapAE2DTO.keySet()){ //are Ids matching ? if(thatAe.getExternalId() != null && thisAe.getExternalId() != null && StringUtils.equals(thisAe.getExternalId(), thatAe.getExternalId()) ) return mapAE2DTO.get(thisAe); //Compare Grade if(thatAe.getGrade() != null && thisAe.getGrade() != null && !thisAe.getGrade().equals(thatAe.getGrade()) ) continue; //are dates matching ? if(DateUtils.compareDate(thisAe.getStartDate(), thatAe.getStartDate()) != 0) continue; if(DateUtils.compareDate(thisAe.getEndDate(), thatAe.getEndDate()) != 0) continue; if(thisAe.getEventApproximateTime() != null && thatAe.getEventApproximateTime()!= null && !(thisAe.getEventApproximateTime().equals(thatAe.getEventApproximateTime()))) continue; //is the term matching ? if(thisAe.getAdverseEventCtcTerm() != null){ //ctc terminology AdverseEventCtcTerm thisCtcTerm = thisAe.getAdverseEventCtcTerm(); AdverseEventCtcTerm thatCtcTerm = thatAe.getAdverseEventCtcTerm(); if ( (thisCtcTerm == null && thatCtcTerm != null) || (thatCtcTerm == null && thisCtcTerm != null) ) continue; if( (thisCtcTerm != null && thatCtcTerm != null )&& thisCtcTerm.getTerm().getId() != thatCtcTerm.getTerm().getId()) continue; if(!StringUtils.equals(thisAe.getOtherSpecify(), thatAe.getOtherSpecify())) continue; LowLevelTerm thisLLT = thisAe.getLowLevelTerm(); LowLevelTerm thatLLT = thatAe.getLowLevelTerm(); if((thisLLT == null && thatLLT != null ) || (thatLLT == null && thisLLT != null)) continue; if((thisLLT != null && thatLLT != null ) && thisLLT.getId() != thatLLT.getId()) continue; } else { //MedDRA terminology AdverseEventMeddraLowLevelTerm thisMedDRATerm = thisAe.getAdverseEventMeddraLowLevelTerm(); AdverseEventMeddraLowLevelTerm thatMedDRATerm = thatAe.getAdverseEventMeddraLowLevelTerm(); if((thisMedDRATerm == null && thatMedDRATerm != null) && (thatMedDRATerm == null && thisMedDRATerm != null)) continue; if((thisMedDRATerm != null && thatMedDRATerm != null) && thisMedDRATerm.getLowLevelTerm().getId() != thatMedDRATerm.getLowLevelTerm().getId()) continue; } //found a match return mapAE2DTO.get(thisAe); } return null; } private String constructLinkToReport(int studyId, int participantId, int rpId) { String hostname = messageSource.getMessage("rules.hostname", new String[] {}, "", Locale.getDefault()); if ( hostname == "" || hostname == null || hostname.contains("<hostname>")) { try { hostname = java.net.InetAddress.getLocalHost().getHostName(); }catch(UnknownHostException ue) { hostname = "localhost"; } } String port = messageSource.getMessage("rules.port", new String[] {}, "", Locale.getDefault()); if ( port == "" || port == null ) { port = "8443"; } String linkToReport = "https://" + hostname + ":" + port + "/caaers/pages/ae/captureRoutine?study=" + studyId + "&participant="+ participantId + "&adverseEventReportingPeriod="+ rpId +"&_page=0&_target2=2&displayReportingPeriod=true&addReportingPeriodBinder=true"; return linkToReport; } private AEsOutputMessage createResponseObject(RequestType requestType) { AEsOutputMessage response = null; if ( requestType.equals(RequestType.Evaluate)) { response = new EvaluateAEsOutputMessage(); } else { response = new SaveAndEvaluateAEsOutputMessage(); } return response; } public AdverseEventConverter getConverter() { return converter; } public void setConverter(AdverseEventConverter converter) { this.converter = converter; } private Study fetchStudy(String identifier) { if (StringUtils.isEmpty(identifier)) { throw new CaaersSystemException("WS_SAE_004", messageSource.getMessage("WS_SAE_004", new String[] {}, "", Locale.getDefault())); } Study study = null; try { Identifier si = new Identifier(); si.setValue(identifier); study = studyDao.getByIdentifier(si); } catch (Exception e) { throw new CaaersSystemException("WS_GEN_001", messageSource.getMessage("WS_GEN_001", new String[] {}, "", Locale.getDefault())); } if (study == null) { throw new CaaersSystemException("WS_SAE_005", messageSource.getMessage("WS_SAE_005", new String[] { identifier }, "", Locale.getDefault())); } return study; } private void manageAdverseEventRecommendedReports(EvaluationResultDTO dto ){ Map<AdverseEvent,List<ReportDefinition>> adverseEventReportDefinitionMap = dto.getAdverseEventRecommendedReportsMap(); for (Map.Entry<AdverseEvent, List<ReportDefinition>> entry : adverseEventReportDefinitionMap.entrySet()) { AdverseEvent ae = entry.getKey(); List<ReportDefinition> rds = entry.getValue(); // Find out if the AE is serious if (rds != null && rds.size() > 0) { // update existing AE recommendation report or create new one Iterator<ReportDefinition> reportDefinitionIterator = rds.iterator(); while(reportDefinitionIterator.hasNext()){ ReportDefinition reportDefinition = reportDefinitionIterator.next(); AdverseEventRecommendedReport aeRecomReport; List<AdverseEventRecommendedReport> dbAeRecomReports = adverseEventRecommendedReportDao.searchAdverseEventRecommendedReportsByAdverseEvent(ae); if (dbAeRecomReports != null && !dbAeRecomReports.isEmpty()) { // AE recommendation report already exists aeRecomReport = dbAeRecomReports.get(0); if (!reportDefinition.getOrganization().equals(aeRecomReport.getReportDefinition().getOrganization()) || !reportDefinition.getGroup().equals(aeRecomReport.getReportDefinition().getGroup())) { // CAAERS-6961: Only if there is a change in the recommended Report Org or Group set the AE // reported flag to false, otherwise the AE is already considered added to the report. aeRecomReport.setAeReported(false); } } else { // create AE recommendation report aeRecomReport = new AdverseEventRecommendedReport(); aeRecomReport.setAdverseEvent(ae); aeRecomReport.setAeReported(false); } aeRecomReport.setReportDefinition(reportDefinition); aeRecomReport.setDueDate(reportDefinition.getExpectedDueDate(ae.getGradedDate())); adverseEventRecommendedReportDao.save(aeRecomReport); } } else { // delete old serious AE recommendation reports that are no longer serious in current evaluation List<AdverseEventRecommendedReport> dbAeRecomReports = adverseEventRecommendedReportDao.searchAdverseEventRecommendedReportsByAdverseEvent(ae); if(dbAeRecomReports != null && !dbAeRecomReports.isEmpty()){ AdverseEventRecommendedReport aeRecomReport = dbAeRecomReports.get(0); adverseEventRecommendedReportDao.delete(aeRecomReport); } } } } public ParticipantDao getParticipantDao() { return participantDao; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public AdverseEventManagementServiceImpl getAdverseEventManagementService() { return adverseEventManagementService; } public void setAdverseEventManagementService(AdverseEventManagementServiceImpl adverseEventManagementService) { this.adverseEventManagementService = adverseEventManagementService; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public StudyDao getStudyDao() { return studyDao; } public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } public TreatmentAssignmentDao getTreatmentAssignmentDao() { return treatmentAssignmentDao; } public void setTreatmentAssignmentDao(TreatmentAssignmentDao treatmentAssignmentDao) { this.treatmentAssignmentDao = treatmentAssignmentDao; } public EvaluationService getAdverseEventEvaluationService() { return evaluationService; } public void setAdverseEventEvaluationService(EvaluationService evaluationService) { this.evaluationService = evaluationService; } public MessageSource getMessageSource() { return messageSource; } public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } public StudyParticipantAssignmentDao getStudyParticipantAssignmentDao() { return studyParticipantAssignmentDao; } public void setStudyParticipantAssignmentDao(StudyParticipantAssignmentDao studyParticipantAssignmentDao) { this.studyParticipantAssignmentDao = studyParticipantAssignmentDao; } public SAEAdverseEventReportingPeriodConverter getReportingPeriodConverter() { return reportingPeriodConverter; } public void setReportingPeriodConverter(SAEAdverseEventReportingPeriodConverter reportingPeriodConverter) { this.reportingPeriodConverter = reportingPeriodConverter; } public RecommendedActionService getRecommendedActionService() { return recommendedActionService; } public void setRecommendedActionService(RecommendedActionService recommendedActionService) { this.recommendedActionService = recommendedActionService; } public void setAdverseEventRecommendedReportDao( AdverseEventRecommendedReportDao adverseEventRecommendedReportDao) { this.adverseEventRecommendedReportDao = adverseEventRecommendedReportDao; } public void setNowFactory(NowFactory nowFactory) { this.nowFactory = nowFactory; } public void setReportDefinitionDao(ReportDefinitionDao reportDefinitionDao) { this.reportDefinitionDao = reportDefinitionDao; } }
package gov.nih.nci.cabig.caaers.domain.repository; import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.query.AbstractQuery; import gov.nih.nci.cabig.caaers.dao.query.ResearchStaffQuery; import gov.nih.nci.cabig.caaers.dao.query.StudyQuery; import gov.nih.nci.cabig.caaers.domain.ResearchStaff; import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff; import gov.nih.nci.cabig.caaers.domain.SiteResearchStaffRole; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudyPersonnel; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; /** * @author Biju Joseph */ @Transactional(readOnly = true) public class StudyRepository { private StudyDao studyDao; private ResearchStaffDao researchStaffDao; /** * Search using a sample populate Study object * * @param study the study object * @return List of Study objects based on the sample study object * @throws Exception runtime exception object */ public List<Study> search(Study study) throws Exception { return studyDao.searchByExample(study, true); } /** * Saves a study object * * @param study the study object * @throws Exception runtime exception object */ @Transactional(readOnly = false) public void save(Study study){ //Identify newly added StudyOrganizations to associate ResearchStaff //whose associateAllStudies flag is set to true. ResearchStaffQuery query = null; List<ResearchStaff> researchStaffs = null; StudyPersonnel studyPersonnel = null; for(StudyOrganization studyOrganization : study.getStudyOrganizations()){ if(studyOrganization.getId() == null){ researchStaffs = new ArrayList<ResearchStaff>(); query= new ResearchStaffQuery(); query.filterByAssociateAllStudies(true); query.filterByOrganization(Integer.toString(studyOrganization.getOrganization().getId())); researchStaffs = researchStaffDao.getLocalResearchStaff(query); for(ResearchStaff researchStaff : researchStaffs){ for(SiteResearchStaff siteResearchStaff : researchStaff.getSiteResearchStaffs()){ if(studyOrganization.getOrganization().equals(siteResearchStaff.getOrganization())){ for(SiteResearchStaffRole siteResearchStaffRole : siteResearchStaff.getSiteResearchStaffRoles()){ studyPersonnel = new StudyPersonnel(); studyPersonnel.setSiteResearchStaff(siteResearchStaff); studyPersonnel.setStudyOrganization(studyOrganization); studyPersonnel.setRoleCode(siteResearchStaffRole.getRoleCode()); studyPersonnel.setStartDate(siteResearchStaffRole.getStartDate()); studyPersonnel.setEndDate(siteResearchStaffRole.getEndDate()); studyOrganization.addStudyPersonnel(studyPersonnel); } } } } } } //Save the study studyDao.save(study); } @Required public void setStudyDao(final StudyDao studyDao) { this.studyDao = studyDao; } public List<Study> find(final AbstractQuery query) { return studyDao.find(query); } //Associate the ResearchStaff to all the Studies public void associateStudyPersonnel(List<SiteResearchStaff> siteRsList) throws Exception{ StudyQuery query = null; List<Study> studies = null; StudyPersonnel studyPersonnel = null; for(SiteResearchStaff siteResearchStaff : siteRsList){ query = new StudyQuery(); query.joinStudyOrganization(); query.filterByStudyOrganizationNameExactMatch(siteResearchStaff.getOrganization().getName()); studies = studyDao.find(query); for(Study study : studies){ for(StudyOrganization studyOrganization : study.getStudyOrganizations()){ if(studyOrganization.getOrganization().equals(siteResearchStaff.getOrganization())){ for(SiteResearchStaffRole siteResearchStaffRole : siteResearchStaff.getSiteResearchStaffRoles()){ studyPersonnel = new StudyPersonnel(); studyPersonnel.setSiteResearchStaff(siteResearchStaff); studyPersonnel.setStudyOrganization(studyOrganization); studyPersonnel.setRoleCode(siteResearchStaffRole.getRoleCode()); studyPersonnel.setStartDate(siteResearchStaffRole.getStartDate()); studyPersonnel.setEndDate(siteResearchStaffRole.getEndDate()); boolean studyPersonnelExists = false; for(StudyPersonnel existingStudyPersonnel : studyOrganization.getStudyPersonnels()){ if(existingStudyPersonnel.equals(studyPersonnel) & existingStudyPersonnel.isActive()){ studyPersonnelExists = true; existingStudyPersonnel.setEndDate(siteResearchStaffRole.getEndDate()); break; } } if(!studyPersonnelExists){ studyOrganization.addStudyPersonnel(studyPersonnel); } } //studyOrganization.syndStudyPersonnelDates(); } } studyDao.save(study); } } } public void setResearchStaffDao(ResearchStaffDao researchStaffDao) { this.researchStaffDao = researchStaffDao; } }
package it.uniroma1.lcl.dietrolequinte.loader; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import it.uniroma1.lcl.dietrolequinte.exception.DirectoryNotFoundException; import it.uniroma1.lcl.dietrolequinte.exception.EmptyDirectoryException; import it.uniroma1.lcl.dietrolequinte.exception.NotADirectoryException; public class Loader { private String directory; private File fileDirectory; private List<AbstractLoader> loaders; /** * @param directory * @throws DirectoryNotFoundException * @throws NotADirectoryException * @throws EmptyDirectoryException */ public Loader(String directory) throws DirectoryNotFoundException, NotADirectoryException, EmptyDirectoryException { this.directory = directory; fileDirectory = new File(directory); if(!fileDirectory.exists()) { throw new DirectoryNotFoundException(); } if(fileDirectory.isFile()) { throw new NotADirectoryException(); } if(fileDirectory.list().length == 0) { throw new EmptyDirectoryException(); } Arrays.stream(fileDirectory.listFiles()).filter(this::fileIsLogFile).forEach(this::createSpecificLoader); } /** * @return Restituisce il pathname della cartella su cui * viene eseguito il programma */ public String getDirectory() { return directory; } private boolean fileIsLogFile(File f) { String format, zippedFormat; format = f.getName().split(".")[f.getName().split(".").length-1]; zippedFormat = f.getName().split(".")[f.getName().split(".").length-2]; return (format==LogFileExtensions.log.toString() || format == LogFileExtensions.txt.toString()) || (format == LogFileExtensions.zip.toString() && (zippedFormat == LogFileExtensions.txt.name() || zippedFormat == LogFileExtensions.log.name())); } /** * @param f file a partire dal quale creare il loader */ private void createSpecificLoader(File f) { String type = f.getName().split(".")[0]; try { loaders.add((AbstractLoader) Class.forName(Character.toUpperCase(type.charAt(0))+type.substring(1)+"Loader").getConstructor(File.class).newInstance(f)); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } /* caso in cui non sia stato creato il loader specifico * relativo al file f */ catch (ClassNotFoundException e) { System.out.println("Non esiste loader per il tipo di file specificato"); return; } } /** * @param args */ public static void main(String[] args) { } /** * @return Restituisce la lista dei loader specifici, * inizializzati per ogni file di log presente * nella cartella */ public List<AbstractLoader> getLoaders() { return loaders; } }
package org.project.openbaton.catalogue.mano.descriptor; import com.fasterxml.jackson.annotation.JsonIgnore; import org.project.openbaton.catalogue.mano.common.HighAvailability; import org.project.openbaton.catalogue.mano.common.LifecycleEvent; import org.project.openbaton.catalogue.mano.record.VNFCInstance; import org.project.openbaton.catalogue.nfvo.VimInstance; import org.project.openbaton.catalogue.util.IdGenerator; import javax.persistence.*; import java.io.Serializable; import java.util.Set; @Entity public class VirtualDeploymentUnit implements Serializable { @Id private String id; @Version private int version = 0; /** * This provides a reference to a VM image * NOTE: A cardinality of zero allows for creating empty virtualisation containers as per (ETSI GS NFV-SWA 001 [i.8]). */ @ElementCollection(fetch = FetchType.EAGER) private Set<String> vm_image; /** * Describe the required computation resources characteristics (e.g. processing power, number of virtual CPUs, etc.), * including Key Quality Indicators (KQIs) for performance and reliability/availability. */ private String computation_requirement; /** * This represents the virtual memory needed for the VDU. */ private String virtual_memory_resource_element; /** * This represents the requirements in terms of the virtual network bandwidth needed for the VDU. */ private String virtual_network_bandwidth_resource; /** * Defines VNF component functional scripts/workflows for specific lifecycle events(e.g. initialization, termination, * graceful shutdown, scaling out/in). */ @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.EAGER) private Set<LifecycleEvent> lifecycle_event; /** * Placeholder for other constraints. */ private String vdu_constraint; /** * Defines redundancy model to ensure high availability examples include: ActiveActive: Implies that two instance of * the same VDU will co-exists with continuous data synchronization. ActivePassive: Implies that two instance of * the same VDU will co-exists without any data synchronization. */ @Enumerated(EnumType.STRING) private HighAvailability high_availability; /** * Defines minimum and maximum number of instances which can be created to support scale out/in. */ private int scale_in_out; /** * Contains information that is distinct for each VNFC created based on this VDU. */ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<VNFComponent> vnfc; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<VNFCInstance> vnfc_instance; /** * Monitoring parameter, which can be tracked for a VNFC based on this VDU. Examples include: memory-consumption, * CPU-utilisation, bandwidth-consumption, VNFC downtime, etc. */ @ElementCollection(fetch = FetchType.EAGER) private Set<String> monitoring_parameter; @JsonIgnore @OneToOne(fetch = FetchType.EAGER, cascade = {CascadeType.REFRESH /*TODO sure about this?*/}) private VimInstance vimInstance; private String hostname; @Column(nullable = false) private String vimInstanceName; public VirtualDeploymentUnit() { } public Set<VNFCInstance> getVnfc_instance() { return vnfc_instance; } public void setVnfc_instance(Set<VNFCInstance> vnfc_instance) { this.vnfc_instance = vnfc_instance; } @PrePersist public void ensureId() { id = IdGenerator.createUUID(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Set<String> getVm_image() { return vm_image; } public void setVm_image(Set<String> vm_image) { this.vm_image = vm_image; } public String getComputation_requirement() { return computation_requirement; } public void setComputation_requirement(String computation_requirement) { this.computation_requirement = computation_requirement; } public String getVirtual_memory_resource_element() { return virtual_memory_resource_element; } public void setVirtual_memory_resource_element(String virtual_memory_resource_element) { this.virtual_memory_resource_element = virtual_memory_resource_element; } public String getVirtual_network_bandwidth_resource() { return virtual_network_bandwidth_resource; } public void setVirtual_network_bandwidth_resource(String virtual_network_bandwidth_resource) { this.virtual_network_bandwidth_resource = virtual_network_bandwidth_resource; } public Set<LifecycleEvent> getLifecycle_event() { return lifecycle_event; } public void setLifecycle_event(Set<LifecycleEvent> lifecycle_event) { this.lifecycle_event = lifecycle_event; } public String getVdu_constraint() { return vdu_constraint; } public void setVdu_constraint(String vdu_constraint) { this.vdu_constraint = vdu_constraint; } public HighAvailability getHigh_availability() { return high_availability; } public void setHigh_availability(HighAvailability high_availability) { this.high_availability = high_availability; } public int getScale_in_out() { return scale_in_out; } public void setScale_in_out(int scale_in_out) { this.scale_in_out = scale_in_out; } public Set<VNFComponent> getVnfc() { return vnfc; } public void setVnfc(Set<VNFComponent> vnfc) { this.vnfc = vnfc; } public Set<String> getMonitoring_parameter() { return monitoring_parameter; } public void setMonitoring_parameter(Set<String> monitoring_parameter) { this.monitoring_parameter = monitoring_parameter; } @Override public String toString() { return "VirtualDeploymentUnit{" + "id='" + id + '\'' + ", version=" + version + ", vm_image=" + vm_image + ", computation_requirement='" + computation_requirement + '\'' + ", virtual_memory_resource_element='" + virtual_memory_resource_element + '\'' + ", virtual_network_bandwidth_resource='" + virtual_network_bandwidth_resource + '\'' + ", lifecycle_event=" + lifecycle_event + ", vdu_constraint='" + vdu_constraint + '\'' + ", high_availability=" + high_availability + ", scale_in_out=" + scale_in_out + ", vnfc=" + vnfc + ", monitoring_parameter=" + monitoring_parameter + '}'; } public VimInstance getVimInstance() { return vimInstance; } public void setVimInstance(VimInstance vimInstance) { this.vimInstance = vimInstance; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public String getVimInstanceName() { return vimInstanceName; } public void setVimInstanceName(String vimInstanceName) { this.vimInstanceName = vimInstanceName; } }
// BUI - a user interface library for the JME 3D engine // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.jme.bui.event; import java.awt.Canvas; import com.jme.scene.Node; import com.jme.bui.BComponent; import com.jme.bui.Log; /** * Bridges between the AWT and the BUI input event system when we are * being used in an AWT canvas. */ public class CanvasInputDispatcher extends InputDispatcher implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener { public CanvasInputDispatcher (Node rootNode, Canvas canvas) { super(rootNode); _canvas = canvas; // we want to hear about mouse movement and clicking canvas.addMouseListener(this); canvas.addMouseMotionListener(this); canvas.addMouseWheelListener(this); } // documentation inherited from interface MouseListener public void mouseClicked (java.awt.event.MouseEvent e) { } // documentation inherited from interface MouseListener public void mouseEntered (java.awt.event.MouseEvent e) { } // documentation inherited from interface MouseListener public void mouseExited (java.awt.event.MouseEvent e) { } // documentation inherited from interface MouseListener public void mousePressed (java.awt.event.MouseEvent e) { updateState(e); BComponent tcomponent = getTargetComponent(); if (tcomponent != null) { _ccomponent = tcomponent; tcomponent.dispatchEvent( new MouseEvent(this, e.getWhen(), _modifiers, MouseEvent.MOUSE_PRESSED, convertButton(e), _mouseX, _mouseY)); } } // documentation inherited from interface MouseListener public void mouseReleased (java.awt.event.MouseEvent e) { updateState(e); BComponent tcomponent = getTargetComponent(); if (tcomponent != null) { tcomponent.dispatchEvent( new MouseEvent(this, e.getWhen(), _modifiers, MouseEvent.MOUSE_RELEASED, convertButton(e), _mouseX, _mouseY)); } _ccomponent = null; } // documentation inherited from interface MouseMotionListener public void mouseDragged (java.awt.event.MouseEvent e) { mouseMoved(e); } // documentation inherited from interface MouseMotionListener public void mouseMoved (java.awt.event.MouseEvent e) { boolean mouseMoved = updateState(e); // if the mouse has moved, generate a moved or dragged event if (mouseMoved) { BComponent tcomponent = getTargetComponent(); if (tcomponent != null) { int type = (tcomponent == _ccomponent) ? MouseEvent.MOUSE_DRAGGED : MouseEvent.MOUSE_MOVED; tcomponent.dispatchEvent( new MouseEvent(this, e.getWhen(), _modifiers, type, _mouseX, _mouseY)); } } } // documentation inherited from interface MouseWheelListener public void mouseWheelMoved (java.awt.event.MouseWheelEvent e) { updateState(e); BComponent tcomponent = getTargetComponent(); if (tcomponent != null) { tcomponent.dispatchEvent( new MouseEvent(this, e.getWhen(), _modifiers, MouseEvent.MOUSE_WHEELED, convertButton(e), _mouseX, _mouseY, e.getWheelRotation())); } } protected boolean updateState (java.awt.event.MouseEvent e) { // update our modifiers _modifiers = convertModifiers(e.getModifiers()); // determine whether the mouse moved int mx = e.getX(), my = _canvas.getHeight() - e.getY(); if (_mouseX != mx || _mouseY != my) { _mouseX = mx; _mouseY = my; computeHoverComponent(mx, my); return true; } return false; } protected BComponent getTargetComponent () { // mouse press and mouse motion events do not necessarily go to // the component under the mouse. when the mouse is clicked down // on a component (any button), it becomes the "clicked" // component, the target for all subsequent click and motion // events (which become drag events) until all buttons are // released if (_ccomponent != null) { return _ccomponent; } // if there's no clicked component, use the hover component if (_hcomponent != null) { return _hcomponent; } // if there's no hover component, use the default event target return _dcomponent; } protected int convertModifiers (int modifiers) { // TODO return modifiers; } protected int convertButton (java.awt.event.MouseEvent e) { // OpenGL and the AWT disagree about mouse button numbering switch (e.getButton()) { case 2: return 3; case 3: return 2; default: return e.getButton(); } } protected Canvas _canvas; }
package wyc.io; import static wyc.lang.WhileyFile.internalFailure; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.List; import java.util.Map; import wybs.util.Pair; import wyc.lang.Expr; import wyc.lang.Stmt; import wyc.lang.SyntacticType; import wyc.lang.WhileyFile; import wyil.lang.*; /** * Responsible for "pretty printing" a Whiley File. This is useful for * formatting Whiley Files. Also, it can be used to programatically generate * Whiley Files. * * @author David J. Pearce * */ public class WhileyFilePrinter { private PrintWriter out; public WhileyFilePrinter(PrintWriter writer) { this.out = writer; } public WhileyFilePrinter(OutputStream stream) { this.out = new PrintWriter(new OutputStreamWriter(stream)); } public void print(WhileyFile wf) { for(WhileyFile.Declaration d : wf.declarations) { print(d); } out.flush(); } public void print(WhileyFile.Declaration decl) { if(decl instanceof WhileyFile.Import) { print((WhileyFile.Import)decl); } else if(decl instanceof WhileyFile.Constant) { print((WhileyFile.Constant)decl); } else if(decl instanceof WhileyFile.FunctionOrMethod) { print((WhileyFile.FunctionOrMethod)decl); } else { throw new RuntimeException("Unknown construct encountered: " + decl.getClass().getName()); } } public void print(WhileyFile.FunctionOrMethod m) { print(m.modifiers); print(m.ret); out.print(" "); out.print(m.name); out.print("("); boolean firstTime = true; for(WhileyFile.Parameter p : m.parameters) { if(!firstTime) { out.print(", "); } firstTime=false; print(p.type); out.print(" "); out.print(p.name); } out.println("):"); print(m.statements,1); } public void print(WhileyFile.Import decl) { out.print("import "); if(decl.name != null) { out.print(decl.name); out.print(" from "); } out.println(decl.filter.toString().replace('/','.')); } public void print(WhileyFile.Constant decl) { out.print("define "); out.print(decl.name); out.print(" as "); print(decl.constant); out.println(); } public void print(List<Stmt> statements, int indent) { for(Stmt s : statements) { print(s,indent); } } public void print(Stmt stmt, int indent) { indent(indent); if(stmt instanceof Stmt.Assert) { // TODO } else if(stmt instanceof Stmt.Assign) { // TODO } else if(stmt instanceof Stmt.Assume) { // TODO } else if(stmt instanceof Stmt.Break) { // TODO } else if(stmt instanceof Stmt.Debug) { // TODO } else if(stmt instanceof Stmt.DoWhile) { // TODO } else if(stmt instanceof Stmt.ForAll) { // TODO } else if(stmt instanceof Stmt.IfElse) { // TODO } else if(stmt instanceof Stmt.Return) { print((Stmt.Return) stmt); } else if(stmt instanceof Stmt.Skip) { // TODO } else if(stmt instanceof Stmt.Switch) { // TODO } else if(stmt instanceof Stmt.Return) { // TODO } else if(stmt instanceof Stmt.Throw) { // TODO } else if(stmt instanceof Stmt.TryCatch) { // TODO } else if(stmt instanceof Stmt.While) { // TODO } else { // should be dead-code throw new RuntimeException("Unknown statement kind encountered: " + stmt.getClass().getName()); } } public void print(Stmt.Return s) { out.print("return"); if(s.expr != null) { out.print(" "); print(s.expr); } out.println(); } public void print(Expr expression) { if (expression instanceof Expr.Constant) { print ((Expr.Constant) expression); } else if (expression instanceof Expr.AbstractVariable) { print ((Expr.AbstractVariable) expression); } else if (expression instanceof Expr.ConstantAccess) { print ((Expr.ConstantAccess) expression); } else if (expression instanceof Expr.Set) { print ((Expr.Set) expression); } else if (expression instanceof Expr.List) { print ((Expr.List) expression); } else if (expression instanceof Expr.SubList) { print ((Expr.SubList) expression); } else if (expression instanceof Expr.SubString) { print ((Expr.SubString) expression); } else if (expression instanceof Expr.BinOp) { print ((Expr.BinOp) expression); } else if (expression instanceof Expr.LengthOf) { print ((Expr.LengthOf) expression); } else if (expression instanceof Expr.Dereference) { print ((Expr.Dereference) expression); } else if (expression instanceof Expr.Convert) { print ((Expr.Convert) expression); } else if (expression instanceof Expr.IndexOf) { print ((Expr.IndexOf) expression); } else if (expression instanceof Expr.UnOp) { print ((Expr.UnOp) expression); } else if (expression instanceof Expr.FunctionCall) { print ((Expr.FunctionCall) expression); } else if (expression instanceof Expr.MethodCall) { print ((Expr.MethodCall) expression); } else if (expression instanceof Expr.IndirectFunctionCall) { print ((Expr.IndirectFunctionCall) expression); } else if (expression instanceof Expr.IndirectMethodCall) { print ((Expr.IndirectMethodCall) expression); } else if (expression instanceof Expr.Comprehension) { print ((Expr.Comprehension) expression); } else if (expression instanceof Expr.RecordAccess) { print ((Expr.RecordAccess) expression); } else if (expression instanceof Expr.Record) { print ((Expr.Record) expression); } else if (expression instanceof Expr.Tuple) { print ((Expr.Tuple) expression); } else if (expression instanceof Expr.Map) { print ((Expr.Map) expression); } else if (expression instanceof Expr.FunctionOrMethod) { print ((Expr.FunctionOrMethod) expression); } else if (expression instanceof Expr.Lambda) { print ((Expr.Lambda) expression); } else if (expression instanceof Expr.New) { print ((Expr.New) expression); } else { // should be dead-code throw new RuntimeException("Unknown expression kind encountered: " + expression.getClass().getName()); } } public void print(Expr.Constant c) { out.print(c.value); } public void print(Expr.AbstractVariable v) { out.print(v); } public void print(Expr.ConstantAccess v) { out.print(v.nid); } public void print(Expr.Set e) { out.print("{"); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print("}"); } public void print(Expr.List e) { out.print("["); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print("]"); } public void print(Expr.SubList e) { print(e.src); out.print("["); print(e.start); out.print(".."); print(e.end); out.print("]"); } public void print(Expr.SubString e) { print(e.src); out.print("["); print(e.start); out.print(".."); print(e.end); out.print("]"); } public void print(Expr.BinOp e) { print(e.lhs); out.print(" "); out.print(e.op); out.print(" "); print(e.rhs); } public void print(Expr.LengthOf e) { out.print("|"); print(e.src); out.print("|"); } public void print(Expr.Dereference e) { out.print("*"); print(e.src); } public void print(Expr.Convert e) { // TODO throw new RuntimeException("TODO: " + e.getClass().getName()); } public void print(Expr.IndexOf e) { print(e.src); out.print("["); print(e.index); out.print("]"); } public void print(Expr.UnOp e) { out.print(e.op); print(e.mhs); } public void print(Expr.FunctionCall e) { out.print(e.name); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.MethodCall e) { out.print(e.name); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.IndirectFunctionCall e) { print(e.src); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.IndirectMethodCall e) { print(e.src); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.Comprehension e) { // TODO throw new RuntimeException("TODO: " + e.getClass().getName()); } public void print(Expr.RecordAccess e) { print(e.src); out.print("."); out.print(e.name); } public void print(Expr.Record e) { out.print("{"); boolean firstTime = true; for(Map.Entry<String,Expr> i : e.fields.entrySet()) { if(!firstTime) { out.print(", "); } firstTime=false; out.print(i.getKey()); out.print(": "); print(i.getValue()); } out.print("}"); } public void print(Expr.Tuple e) { out.print("("); boolean firstTime = true; for(Expr i : e.fields) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.Map e) { out.print("{"); boolean firstTime = true; for(Pair<Expr,Expr> p : e.pairs) { if(!firstTime) { out.print(", "); } firstTime=false; print(p.first()); out.print("=>"); print(p.second()); } out.print("}"); } public void print(Expr.FunctionOrMethod e) { // TODO throw new RuntimeException("TODO: " + e.getClass().getName()); } public void print(Expr.Lambda e) { // TODO throw new RuntimeException("TODO: " + e.getClass().getName()); } public void print(Expr.New e) { out.print("new "); print(e.expr); } public void print(List<Modifier> modifiers) { for(Modifier m : modifiers) { out.print(m); out.print(" "); } } public void print(SyntacticType t) { if(t instanceof SyntacticType.Any) { out.print("any"); } else if(t instanceof SyntacticType.Bool) { out.print("bool"); } else if(t instanceof SyntacticType.Byte) { out.print("byte"); } else if(t instanceof SyntacticType.Char) { out.print("char"); } else if(t instanceof SyntacticType.Int) { out.print("int"); } else if(t instanceof SyntacticType.Null) { out.print("null"); } else if(t instanceof SyntacticType.Strung) { out.print("string"); } else if(t instanceof SyntacticType.Real) { out.print("real"); } else if(t instanceof SyntacticType.Void) { out.print("void"); } else { // should be dead-code throw new RuntimeException("Unknown type kind encountered: " + t.getClass().getName()); } } public void indent(int level) { for(int i=0;i!=level;++i) { out.print(" "); } } }
package io.wia; import java.util.List; /** * Represents an event query item. */ public class WiaEventQueryItem extends WiaResource { double avg; int count; double max; double min; double sum; String created_at; /** * @return avg of this event query item. */ public double avg() { return avg; } /** * @return count of this event query item. */ public int count() { return count; } /** * @return max of this event query item. */ public double max() { return max; } /** * @return min of this event query item. */ public double min() { return min; } /** * @return sum of this event query item. */ public double sum() { return sum; } /** * @return created_at of this event query item. */ public String created_at() { return created_at; } }
package org.jsimpledb.kv.leveldb; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.Closeable; import java.io.IOException; import java.util.AbstractMap; import java.util.Map; import java.util.NoSuchElementException; import org.iq80.leveldb.DB; import org.iq80.leveldb.DBException; import org.iq80.leveldb.DBIterator; import org.iq80.leveldb.ReadOptions; import org.iq80.leveldb.WriteBatch; import org.iq80.leveldb.WriteOptions; import org.jsimpledb.kv.AbstractKVStore; import org.jsimpledb.kv.CloseableKVStore; import org.jsimpledb.kv.KVPair; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.kv.mvcc.Mutations; import org.jsimpledb.util.ByteUtil; import org.jsimpledb.util.CloseableTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An {@link AtomicKVStore} view of a LevelDB database. * * <p> * Instances must be {@link #close}'d when no longer needed to avoid leaking resources associated with iterators. * </p> */ public class LevelDBKVStore extends AbstractKVStore implements AtomicKVStore, CloseableKVStore { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final CloseableTracker cursorTracker = new CloseableTracker(); private final ReadOptions readOptions; private final WriteBatch writeBatch; private final DB db; private boolean closed; // Constructors /** * Convenience constructor. Uses default read options and no write batching. * * @param db database */ public LevelDBKVStore(DB db) { this(db, null, null); } public LevelDBKVStore(DB db, ReadOptions readOptions, WriteBatch writeBatch) { if (db == null) throw new IllegalArgumentException("null db"); this.db = db; this.readOptions = readOptions != null ? readOptions : new ReadOptions(); this.writeBatch = writeBatch; if (this.log.isTraceEnabled()) this.log.trace("created " + this); } // Accessors /** * Get the {@link DB} underlying this instance. * * @return underlying database */ public DB getDB() { return this.db; } // KVStore @Override public synchronized byte[] get(byte[] key) { key.getClass(); if (this.closed) throw new IllegalStateException("the store is closed"); this.cursorTracker.poll(); return this.db.get(key, this.readOptions); } @Override public synchronized java.util.Iterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) { if (this.closed) throw new IllegalStateException("the store is closed"); this.cursorTracker.poll(); return new Iterator(this.db.iterator(this.readOptions), minKey, maxKey, reverse); } @Override public synchronized void put(byte[] key, byte[] value) { key.getClass(); value.getClass(); if (this.closed) throw new IllegalStateException("the store is closed"); this.cursorTracker.poll(); if (this.writeBatch != null) this.writeBatch.put(key, value); else this.db.put(key, value); } @Override public synchronized void remove(byte[] key) { key.getClass(); if (this.closed) throw new IllegalStateException("the store is closed"); this.cursorTracker.poll(); if (this.writeBatch != null) this.writeBatch.delete(key); else this.db.delete(key); } // AtomicKVStore @Override public synchronized CloseableKVStore snapshot() { return new SnapshotLevelDBKVStore(this.db, this.readOptions.verifyChecksums()); } @Override public synchronized void mutate(Mutations mutations, boolean sync) { Preconditions.checkArgument(mutations != null, "null mutations"); // Apply mutations in a batch try (WriteBatch batch = this.db.createWriteBatch()) { // Apply removes final ReadOptions iteratorOptions = new ReadOptions() .verifyChecksums(this.readOptions.verifyChecksums()) .snapshot(this.readOptions.snapshot()) .fillCache(false); for (KeyRange range : mutations.getRemoveRanges()) { final byte[] min = range.getMin(); final byte[] max = range.getMax(); if (min != null && max != null && ByteUtil.compare(max, ByteUtil.getNextKey(min)) == 0) batch.delete(min); else { try (Iterator i = new Iterator(this.db.iterator(iteratorOptions), min, max, false)) { while (i.hasNext()) batch.delete(i.next().getKey()); } } } // Apply puts for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) batch.put(entry.getKey(), entry.getValue()); // Convert counter adjustments into puts final Function<Map.Entry<byte[], Long>, Map.Entry<byte[], byte[]>> counterPutFunction = new Function<Map.Entry<byte[], Long>, Map.Entry<byte[], byte[]>>() { @Override public Map.Entry<byte[], byte[]> apply(Map.Entry<byte[], Long> adjust) { // Decode old value final byte[] key = adjust.getKey(); final long diff = adjust.getValue(); byte[] oldBytes = LevelDBKVStore.this.db.get(key, LevelDBKVStore.this.readOptions); if (oldBytes == null) oldBytes = new byte[8]; final long oldValue; try { oldValue = LevelDBKVStore.this.decodeCounter(oldBytes); } catch (IllegalArgumentException e) { return null; } // Add adjustment and re-encode it return new AbstractMap.SimpleEntry<byte[], byte[]>(key, LevelDBKVStore.this.encodeCounter(oldValue + diff)); } }; // Apply counter adjustments for (Map.Entry<byte[], byte[]> entry : Iterables.transform(mutations.getAdjustPairs(), counterPutFunction)) { if (entry != null) batch.put(entry.getKey(), entry.getValue()); } // Write the batch this.db.write(batch, new WriteOptions().sync(sync)); } catch (IOException e) { throw new DBException("error applying changes to LevelDB", e); } } // Object /** * Finalize this instance. Invokes {@link #close} to close any unclosed iterators. */ @Override protected void finalize() throws Throwable { try { if (!this.closed) this.log.warn(this + " leaked without invoking close()"); this.close(); } finally { super.finalize(); } } @Override public String toString() { return this.getClass().getSimpleName() + "[db=" + this.db + ",options=" + this.readOptions + (this.writeBatch != null ? ",writeBatch=" + this.writeBatch : "") + "]"; } // Closeable /** * Close this instance. * * <p> * This closes any unclosed iterators returned from {@link #getRange getRange()}. * This does not close the underlying {@link DB} or any associated {@link WriteBatch}. */ @Override public synchronized void close() { if (this.closed) return; this.closed = true; if (this.log.isTraceEnabled()) this.log.trace("closing " + this); this.cursorTracker.close(); } // Iterator private final class Iterator implements java.util.Iterator<KVPair>, Closeable { private final DBIterator cursor; private final byte[] minKey; private final byte[] maxKey; private final boolean reverse; private KVPair next; private byte[] removeKey; private boolean finished; private boolean closed; Iterator(DBIterator cursor, byte[] minKey, byte[] maxKey, boolean reverse) { // Make sure we eventually close the iterator LevelDBKVStore.this.cursorTracker.add(this, cursor); // Sanity checks assert Thread.holdsLock(LevelDBKVStore.this); if (minKey != null && maxKey != null && ByteUtil.compare(minKey, maxKey) > 0) throw new IllegalArgumentException("minKey > maxKey"); // Initialize this.cursor = cursor; this.minKey = minKey; this.maxKey = maxKey; this.reverse = reverse; if (reverse) { if (maxKey != null) this.cursor.seek(maxKey); else this.cursor.seekToLast(); } else { if (minKey != null) this.cursor.seek(minKey); } // Debug if (LevelDBKVStore.this.log.isTraceEnabled()) LevelDBKVStore.this.log.trace("created " + this); } // Iterator @Override public synchronized boolean hasNext() { if (this.closed) throw new IllegalStateException(); return this.next != null || this.findNext(); } @Override public synchronized KVPair next() { if (this.closed) throw new IllegalStateException(); if (this.next == null && !this.findNext()) throw new NoSuchElementException(); assert this.next != null; final KVPair pair = this.next; this.removeKey = pair.getKey(); this.next = null; return pair; } @Override public synchronized void remove() { if (this.closed || this.removeKey == null) throw new IllegalStateException(); LevelDBKVStore.this.remove(this.removeKey); this.removeKey = null; } private synchronized boolean findNext() { // Sanity check assert this.next == null; if (this.finished) return false; // Advance LevelDB cursor try { this.next = new KVPair(this.reverse ? this.cursor.prev() : this.cursor.next()); } catch (NoSuchElementException e) { this.finished = true; return false; } // Check limit bound if (this.reverse ? (this.minKey != null && ByteUtil.compare(this.next.getKey(), this.minKey) < 0) : (this.maxKey != null && ByteUtil.compare(this.next.getKey(), this.maxKey) >= 0)) { this.next = null; this.finished = true; return false; } // Done return true; } // Closeable @Override public synchronized void close() { if (this.closed) return; this.closed = true; if (LevelDBKVStore.this.log.isTraceEnabled()) LevelDBKVStore.this.log.trace("closing " + this); try { this.cursor.close(); } catch (Throwable e) { LevelDBKVStore.this.log.debug("caught exception closing db iterator (ignoring)", e); } } // Object @Override public String toString() { return LevelDBKVStore.class.getSimpleName() + "." + this.getClass().getSimpleName() + "[minKey=" + ByteUtil.toString(this.minKey) + ",maxKey=" + ByteUtil.toString(this.maxKey) + (this.reverse ? ",reverse" : "") + "]"; } } }
package hm.binkley.dao; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Nonnull; import javax.inject.Inject; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Optional; /** * A very simple DAO wrapper for using Spring transactions and JDBC template, designed for lambda * use. Example: * * <pre> * SimpleDAO&lt;String&gt; someColumn = new SimpleDAO(transactionManager); * String columnValue = someColumn.dao( * (jdbcTemplate, status) -&gt; jdbcTemplate.queryForObject("sql here", String.class);</pre> * * @author <a href="binkley@alumni.rice.edu">B. K. Oxley (binkley)</a> */ public class SimpleDAO { private final DataSourceTransactionManager transactionManager; /** * Constructs a new {@code SimpleDAO} with the given data source <var>transactionManager</var>. * * @param transactionManager the transaction manager, never missing */ @Inject public SimpleDAO(@Nonnull final DataSourceTransactionManager transactionManager) { this.transactionManager = transactionManager; } /** * Gets the JDBC URL for management. */ public final String jdbcURL() throws SQLException { try (final Connection conn = transactionManager.getDataSource().getConnection()) { return conn.getMetaData().getURL(); } } /** * Runs the given <var>dao</var> within Spring transaction. * * @param dao the dao callback, never missing * @param <T> the return type of the callback * * @return the callback result */ public final <T> T dao(@Nonnull final Dao<T> dao) { return dao.using(transactionManager); } /** * Runs the given <var>dao</var> within Spring transaction, requiring 0 or 1 results. * * @param dao the dao callback, never missing * @param wrongSize the exception factory for more than 0 or 1 results, never missing * @param <T> the return type of the callback * * @return an optional of the return * * @throws DataAccessException if the results are the wrong size */ public final <T> Optional<T> daoMaybe(@Nonnull final Dao<List<T>> dao, @Nonnull final WrongSize wrongSize) { final List<T> result = dao(dao); final int size = result.size(); switch (size) { case 0: return Optional.empty(); case 1: return Optional.of(result.get(0)); default: throw wrongSize.fail(size); } } /** * The functional interface for {@link #dao(Dao)}. * * @param <T> the callback return type */ @FunctionalInterface public interface Dao<T> { /** * Manages the JDBC callback, wrapping it in a Spring transaction. The JDBC template passed * to the callback shares the data source of the transaction manager, and executes within a * transaction template. * * @param transactionManager the transaction manager, never missing * * @return the callback result */ default T using(@Nonnull final DataSourceTransactionManager transactionManager) { return new TransactionTemplate(transactionManager).execute( status -> with(new JdbcTemplate(transactionManager.getDataSource()), status)); } /** * Executes the callback, passing in the given <var>jdbcTemplate</var> and transaction * <var>status</var>. This is typically implemented as a lambda. * * @param jdbcTemplate the JDBC template, never missing * @param status the transaction status, never missing * * @return the callback result */ T with(@Nonnull final JdbcTemplate jdbcTemplate, @Nonnull final TransactionStatus status); } @FunctionalInterface public interface WrongSize { DataAccessException fail(final int size); } }
package com.battleejb.entities; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the Competition database table. * */ @Entity @NamedQueries({ @NamedQuery(name = "Competition.findCurrentYearCompetition", query = "SELECT c FROM Competition c WHERE c.type = :type AND c.dateStart <= :currentDate AND c.dateEnd >= :currentDate") }) public class Competition implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Temporal( TemporalType.DATE) private Date dateEnd; @Temporal( TemporalType.DATE) private Date dateStart; private String description; private String name; @Temporal( TemporalType.DATE) private Date registerDeadline; @ManyToOne(fetch=FetchType.EAGER, cascade = CascadeType.PERSIST) private CompetitionType type; @ManyToOne(fetch=FetchType.EAGER, cascade = CascadeType.PERSIST) private User user; @OneToMany(mappedBy="competition") private List<Project> projects; public Competition() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Date getDateEnd() { return this.dateEnd; } public void setDateEnd(Date dateEnd) { this.dateEnd = dateEnd; } public Date getDateStart() { return this.dateStart; } public void setDateStart(Date dateStart) { this.dateStart = dateStart; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Date getRegisterDeadline() { return this.registerDeadline; } public void setRegisterDeadline(Date registerDeadline) { this.registerDeadline = registerDeadline; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } public CompetitionType getType() { return type; } public void setType(CompetitionType type) { this.type = type; } public List<Project> getProjects() { return this.projects; } public void setProjects(List<Project> projects) { this.projects = projects; } }
package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.Test; public class SystemTimeTest { @Test public void testDefaultTimeSource() { final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } return (lower <= tested) && (tested <= upper); } }
package org.aktin.broker; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.aktin.broker.client.AuthFilterImpl; import org.aktin.broker.client.BrokerAdmin; import org.aktin.broker.client.ClientWebsocket; import org.aktin.broker.client.TestClient; import org.aktin.broker.client2.AdminNotificationListener; import org.aktin.broker.client2.AuthFilter; import org.aktin.broker.client2.BrokerAdmin2; import org.aktin.broker.client2.BrokerClient2; import org.aktin.broker.client2.NotificationListener; import org.aktin.broker.util.AuthFilterSSLHeaders; import org.aktin.broker.xml.RequestInfo; import org.aktin.broker.xml.RequestStatus; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestWebsockets extends AbstractTestBroker{ private static final String CLIENT_01_SERIAL = "01"; private static final String CLIENT_01_DN = "CN=Test 1,ST=Hessen,C=DE,O=AKTIN,OU=Uni Giessen"; private static final String CLIENT_02_SERIAL = "02"; private static final String CLIENT_02_DN = "CN=Test 2,ST=Hessen,C=DE,O=AKTIN,OU=Uni Giessen"; private static final String ADMIN_00_DN = "CN=Test Adm,ST=Hessen,C=DE,O=AKTIN,OU=Uni Giessen,OU=admin"; private static final String ADMIN_00_SERIAL = "00"; @Override public BrokerClient2 initializeClient(String arg) { AuthFilter auth; switch( arg ) { case CLIENT_01_SERIAL: auth = new AuthFilterImpl(CLIENT_01_SERIAL, CLIENT_01_DN); break; case CLIENT_02_SERIAL: auth = new AuthFilterImpl(CLIENT_02_SERIAL, CLIENT_02_DN); break; default: throw new IllegalArgumentException(); } BrokerClient2 c = new BrokerClient2(server.getBrokerServiceURI()); c.setAuthFilter(auth); return c; } @Override public BrokerAdmin2 initializeAdmin() { BrokerAdmin2 a = new BrokerAdmin2(server.getBrokerServiceURI()); a.setAuthFilter(new AuthFilterImpl(ADMIN_00_SERIAL, ADMIN_00_DN)); return a; } @Before public void setupServer() throws Exception{ server = new BrokerTestServer(new AuthFilterSSLHeaders()); server.start_local(0); // TODO reset database } @After public void shutdownServer() throws Exception{ server.stop(); server.destroy(); } private static final void sleepForWebsocketAction() { try { Thread.sleep(300); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Make sure that request notifications are recieved via websocket using the client library. * Clients not targeted by the request should not receive notifications. * @throws IOException unexpected test failure */ @Test public void clientRequestNotificationsOnlyForTargetedNodes() throws IOException { BrokerClient2 c1 = initializeClient(CLIENT_01_SERIAL); BrokerClient2 c2 = initializeClient(CLIENT_02_SERIAL); // make sure that the clients are known by the broker, // by contacting the broker first c1.listMyRequests(); c2.listMyRequests(); // initialize async variables AtomicInteger publishedId = new AtomicInteger(-1); AtomicInteger closedId = new AtomicInteger(-1); AtomicBoolean thirdPartyNotification = new AtomicBoolean(false); // receive expected notifications c1.openWebsocket(new NotificationListener() { @Override public void onResourceChanged(String resourceName) {} @Override public void onRequestPublished(int requestId) { publishedId.set(requestId); } @Override public void onRequestClosed(int requestId) { closedId.set(requestId); } @Override public void onWebsocketClosed(int statusCode, String reason) { } }); // fail with unwanted notifications of third party c2.openWebsocket(new NotificationListener() { @Override public void onResourceChanged(String resourceName) { thirdPartyNotification.set(true); } @Override public void onRequestPublished(int requestId) { thirdPartyNotification.set(true); } @Override public void onRequestClosed(int requestId) { thirdPartyNotification.set(true); } @Override public void onWebsocketClosed(int statusCode, String reason) { } }); BrokerAdmin a = initializeAdmin(); int qid = a.createRequest("text/x-test-1", "test1"); sleepForWebsocketAction(); // make sure the publication was not sent yet Assert.assertEquals(-1, publishedId.get()); Assert.assertFalse(thirdPartyNotification.get()); // make sure selected node is c1 int selectedNode = 0; Assert.assertEquals(CLIENT_01_DN, a.getNode(selectedNode).clientDN); // limit request to only c1 a.setRequestTargetNodes(qid, new int[] {selectedNode}); // publish request a.publishRequest(qid); sleepForWebsocketAction(); // make sure the publication was broadcast Assert.assertEquals(qid, publishedId.get()); Assert.assertEquals(-1, closedId.get()); // same with closed id a.closeRequest(qid); sleepForWebsocketAction(); Assert.assertEquals(qid, closedId.get()); // make sure that other nodes did not get any notification if the request was not targeted for them Assert.assertFalse(thirdPartyNotification.get()); } @Test public void adminNotificationsForAllClientActions() throws IOException{ BrokerAdmin2 a = initializeAdmin(); // initialize async variables AtomicReference<String> action = new AtomicReference<>(); AtomicReference<List<Object>> args = new AtomicReference<>(); // open websocket a.openWebsocket(new AdminNotificationListener() { @Override public void onResourceUpdate(int nodeId, String resourceId) { action.set("resource"); args.set(Arrays.asList(nodeId, resourceId)); } @Override public void onRequestStatusUpdate(int requestId, int nodeId, String status) { action.set("status"); args.set(Arrays.asList(requestId, nodeId, RequestStatus.valueOf(status))); } @Override public void onRequestResultUpdate(int requestId, int nodeId, String mediaType) { action.set("result"); args.set(Arrays.asList(requestId, nodeId, mediaType)); } @Override public void onRequestPublished(int requestId) { action.set("published"); args.set(Collections.singletonList(requestId)); } @Override public void onRequestCreated(int requestId) { action.set("created"); args.set(Collections.singletonList(requestId)); } @Override public void onRequestClosed(int requestId) { action.set("closed"); args.set(Collections.singletonList(requestId)); } @Override public void onWebsocketClosed(int statusCode, String reason) { } }); BrokerClient2 c1 = initializeClient(CLIENT_01_SERIAL); BrokerClient2 c2 = initializeClient(CLIENT_02_SERIAL); // make sure that the clients are known by the broker, // by contacting the broker first c1.listMyRequests(); c2.listMyRequests(); // create request int rid = a.createRequest(); sleepForWebsocketAction(); Assert.assertEquals("created", action.get()); Assert.assertEquals(rid, args.get().get(0)); // add request definitions a.putRequestDefinition(rid, "application/xml", "<xml/>"); a.putRequestDefinition(rid, "application/json", "{}"); sleepForWebsocketAction(); // make sure there were no other notifications for adding request definitions Assert.assertEquals("created", action.get()); // publish request a.publishRequest(rid); sleepForWebsocketAction(); Assert.assertEquals("published", action.get()); Assert.assertEquals(rid, args.get().get(0)); // fetch requests List<RequestInfo> l = c2.listMyRequests(); Assert.assertEquals(1, l.size()); l = c1.listMyRequests(); Assert.assertEquals(1, l.size()); RequestInfo ri = l.get(0); // listing should not generate a notification sleepForWebsocketAction(); Assert.assertEquals("published", action.get()); // post retrieved status for node 0 c1.postRequestStatus(ri.getId(), RequestStatus.retrieved); sleepForWebsocketAction(); Assert.assertEquals("status", action.get()); Assert.assertEquals(rid, args.get().get(0)); Assert.assertEquals(0, args.get().get(1)); // should be node 0 Assert.assertEquals(RequestStatus.retrieved, args.get().get(2)); // should be node 0 // no need to test all statuses. they are processed on the server in the same method // post failed status for node 1 c2.postRequestFailed(ri.getId(), "failed", new RuntimeException("bla")); sleepForWebsocketAction(); Assert.assertEquals("status", action.get()); Assert.assertEquals(rid, args.get().get(0)); Assert.assertEquals(1, args.get().get(1)); // should be node 1 Assert.assertEquals(RequestStatus.failed, args.get().get(2)); // should be node 0 // post result c1.putRequestResult(ri.getId(), "text/plain+result", "result-content"); sleepForWebsocketAction(); Assert.assertEquals("result", action.get()); Assert.assertEquals(rid, args.get().get(0)); Assert.assertEquals(0, args.get().get(1)); // should be node 1 Assert.assertEquals("text/plain+result", args.get().get(2)); // posted media type // close result a.closeRequest(rid); sleepForWebsocketAction(); Assert.assertEquals("closed", action.get()); Assert.assertEquals(rid, args.get().get(0)); // verify resource updates c1.putMyResource("bla", "application/json", "{}"); sleepForWebsocketAction(); Assert.assertEquals("resource", action.get()); Assert.assertEquals(0, args.get().get(0)); // should be node 0 Assert.assertEquals("bla", args.get().get(1)); // should be node 0 } /** * Test basic websocket functionality without using the broker-client libraries * @throws Exception unexpected test failure */ @Test public void testWebsocket() throws Exception{ WebSocketClient client = new WebSocketClient(); ClientWebsocket websocket = new ClientWebsocket(); ClientUpgradeRequest req = new ClientUpgradeRequest(); // set authentication headers for socket handshake TestClient.setAuthenticatedHeaders(req::setHeader, CLIENT_01_SERIAL, CLIENT_01_DN); websocket.prepareForMessages(1); client.start(); Future<Session> f = client.connect(websocket, new URI("ws://localhost:"+server.getLocalPort()+"/broker/my/websocket"), req); System.out.println("Connecting.."); Session s = f.get(5, TimeUnit.SECONDS); s.getClass(); // don't need the session // connected, wait for messages websocket.waitForMessages(5, TimeUnit.SECONDS); Assert.assertEquals("Welcome message expected from after websocket connect", 1, websocket.messages.size()); // add request BrokerAdmin a = initializeAdmin(); int qid = a.createRequest("text/x-test-1", "test1"); // expect notification for published request websocket.messages.clear(); websocket.prepareForMessages(1); // publish request a.publishRequest(qid); // wait for notification websocket.waitForMessages(5, TimeUnit.SECONDS); Assert.assertEquals("request notification expected", 1, websocket.messages.size()); Assert.assertEquals("published 0", websocket.messages.get(0)); // expect notification for closed request websocket.messages.clear(); websocket.prepareForMessages(1); // close request a.closeRequest(qid); // wait for notification websocket.waitForMessages(5, TimeUnit.SECONDS); Assert.assertEquals("request notification expected", 1, websocket.messages.size()); Assert.assertEquals("closed 0", websocket.messages.get(0)); // terminate websocket client client.stop(); } }
package ch.elexis.dialogs; import java.util.ArrayList; import java.util.Comparator; import java.util.Hashtable; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.eclipse.core.commands.Category; import org.eclipse.core.commands.Command; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; 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.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Hyperlink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tiff.common.ui.datepicker.DatePicker; import ch.elexis.actions.Activator; import ch.elexis.agenda.Messages; import ch.elexis.agenda.acl.ACLContributor; import ch.elexis.agenda.data.IPlannable; import ch.elexis.agenda.data.Termin; import ch.elexis.agenda.data.Termin.Free; import ch.elexis.agenda.preferences.PreferenceConstants; import ch.elexis.agenda.util.Plannables; import ch.elexis.agenda.util.TimeInput; import ch.elexis.agenda.util.TimeInput.TimeInputListener; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.service.ContextServiceHolder; import ch.elexis.core.jdt.NonNull; import ch.elexis.core.services.holder.ConfigServiceHolder; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.dialogs.KontaktSelektor; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.locks.AcquireLockBlockingUi; import ch.elexis.core.ui.locks.ILockHandler; import ch.elexis.core.ui.util.NumberInput; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.data.Kontakt; import ch.elexis.data.Patient; import ch.elexis.data.Query; import ch.rgw.tools.ExHandler; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeSpan; import ch.rgw.tools.TimeTool; import edu.emory.mathcs.backport.java.util.Collections; /** * Dialog zur Eingabe eines oder mehrerer Termine in die Agenda. * * @author gerry * */ public class TerminDialog extends TitleAreaDialog { private static final Logger logger = LoggerFactory.getLogger(TerminDialog.class); private static ICommandService cmdService = (ICommandService) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getService(ICommandService.class); private static Category cmdCategory = cmdService.getCategory("ch.elexis.agenda.commands"); public enum CollisionErrorLevel { ERROR, WARNING } DatePicker dp; TimeInput tiVon; TimeInput tiBis; int ts = ConfigServiceHolder.getUser("agenda/dayView/Start", 7); //$NON-NLS-1$ int te = ConfigServiceHolder.getUser("agenda/dayView/End", 19); //$NON-NLS-1$ int tagStart = ts * 60; // 7 Uhr int tagEnd = te * 60; int[] rasterValues = new int[] { 5, 10, 15, 30 }; int rasterIndex = ConfigServiceHolder.getUser("agenda/dayView/raster", 3); //$NON-NLS-1$ Hashtable<String, String> tMap; double minutes; double pixelPerMinute; NumberInput niDauer; ArrayList<Termin> lTermine; List lTerminListe; // Button bPrev,bNext; Button bLocked, bSerie; Button bSave, bDelete, bChange, bPrint, bFuture, bEmergency; Slider slider; DayOverview dayBar; Kontakt actKontakt; IPlannable actPlannable; // TagesView base; // String[] bereiche; Text tNr, tName, tBem; Combo cbTyp, cbStatus, cbMandant; Text tGrund; Activator agenda = Activator.getDefault(); boolean bModified; private String msg; private CollisionErrorLevel collisionErrorLevel = CollisionErrorLevel.ERROR; public TerminDialog(IPlannable act){ super(UiDesk.getTopShell()); // base=parent; if (act == null) { act = new Termin.Free(agenda.getActDate().toString(TimeTool.DATE_COMPACT), 0, 30); } if (act instanceof Termin) { Termin lact = (Termin) act; actKontakt = lact.getKontakt(); } else { actKontakt = ElexisEventDispatcher.getSelectedPatient(); } Color green = UiDesk.getColor(UiDesk.COL_GREEN); if (green == null) { UiDesk.getColorRegistry().put(UiDesk.COL_GREEN, new RGB(0, 255, 0)); } actPlannable = act; tMap = Plannables.getTimePrefFor(agenda.getActResource()); tMap.put(Termin.typFrei(), "0"); //$NON-NLS-1$ tMap.put(Termin.typReserviert(), "0"); //$NON-NLS-1$ } /** * Use this constructor for creating a new {@link Termin} from a date and for a resource. * * @param date * @param resource * @param patient */ public TerminDialog(@NonNull TimeTool date, @NonNull String resource, Patient patient){ super(UiDesk.getTopShell()); Free act = new Termin.Free(date.toString(TimeTool.DATE_COMPACT), date.get(TimeTool.HOUR_OF_DAY) * 60 + date.get(TimeTool.MINUTE), 30); actKontakt = patient; Color green = UiDesk.getColor(UiDesk.COL_GREEN); if (green == null) { UiDesk.getColorRegistry().put(UiDesk.COL_GREEN, new RGB(0, 255, 0)); } actPlannable = act; agenda.setActResource(resource); tMap = Plannables.getTimePrefFor(agenda.getActResource()); tMap.put(Termin.typFrei(), "0"); //$NON-NLS-1$ tMap.put(Termin.typReserviert(), "0"); //$NON-NLS-1$ } public static void setActResource(String resource){ Activator.getDefault().setActResource(resource); } @Override protected Control createDialogArea(final Composite parent){ ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); sc.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Composite ret = new Composite(sc, SWT.NONE); sc.setContent(ret); // ret.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); ret.setLayout(new GridLayout()); Composite topRow = new Composite(ret, SWT.BORDER); topRow.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); topRow.setLayout(new GridLayout(3, true)); // oben links dp = new DatePicker(topRow, SWT.NONE); dp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); dp.setDate(agenda.getActDate().getTime()); // actDate.setTime(dp.getDate()); dp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ // actDate.setTime(dp.getDate()); agenda.setActDate(new TimeTool(dp.getDate().getTime())); dayBar.redraw(); slider.set(); } }); // oben mitte Composite topCenter = new Composite(topRow, SWT.NONE); topCenter.setLayout(new GridLayout(3, true)); topCenter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true)); tiVon = new TimeInput(topCenter, Messages.TerminDialog_startTime); tiVon.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); tiVon.addListener(new TimeInputListener() { public void changed(){ slider.set(); } }); niDauer = new NumberInput(topCenter, Messages.TerminDialog_duration); niDauer.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); niDauer.getControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ slider.set(); } }); tiBis = new TimeInput(topCenter, Messages.TerminDialog_endTime); tiBis.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); tiBis.addListener(new TimeInputListener() { public void changed(){ int mVon = tiVon.getTimeAsMinutes(); int mBis = tiBis.getTimeAsMinutes(); niDauer.setValue(mBis - mVon); slider.set(); } }); lTermine = new ArrayList<Termin>(); lTerminListe = new List(topCenter, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL); lTerminListe.setLayoutData(SWTHelper.getFillGridData(3, true, 1, true)); lTerminListe.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ int idx = lTerminListe.getSelectionIndex(); if ((idx > -1) && (idx < lTermine.size())) { actPlannable = lTermine.get(idx); setAll(); } } }); // oben rechts Composite topRight = new Composite(topRow, SWT.NONE); topRight.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); topRight.setLayout(new GridLayout(2, true)); Label sep = new Label(topRight, SWT.NONE); sep.setText(" "); //$NON-NLS-1$ sep.setLayoutData(SWTHelper.getFillGridData(2, false, 1, false)); /* * bPrev=new Button(topRight,SWT.PUSH); bPrev.setText("<--"); //$NON-NLS-1$ * bPrev.setToolTipText(Messages.TerminDialog_earlier); bNext=new Button(topRight,SWT.PUSH); * bNext.setText("-->"); //$NON-NLS-1$ bNext.setToolTipText(Messages.TerminDialog_later); */ bLocked = new Button(topRight, SWT.CHECK); bLocked.setText(Messages.TerminDialog_locked); bLocked.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ if (actPlannable instanceof Termin) { ((Termin) actPlannable).setLocked(bLocked.getSelection()); } setEnablement(); } }); if (CoreHub.acl.request(ACLContributor.CHANGE_APPLOCK) == false) { bLocked.setEnabled(false); } bSerie = new Button(topRight, SWT.CHECK); bSerie.setText(Messages.TerminDialog_serie); bSave = new Button(topRight, SWT.PUSH); bSave.setText(Messages.TerminDialog_set); bSave.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); bSave.setToolTipText(Messages.TerminDialog_createTermin); bSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ createTermin(true); } }); Point s = bSave.computeSize(SWT.DEFAULT, SWT.DEFAULT); bChange = new Button(topRight, SWT.PUSH); bChange.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); bChange.setText(Messages.TerminDialog_change); bChange.setToolTipText(Messages.TerminDialog_changeTermin); bDelete = new Button(topRight, SWT.PUSH); bDelete.setText(Messages.TerminDialog_delete); bDelete.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); bDelete.setToolTipText(Messages.TerminDialog_deleteTermin); bDelete.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ if (actPlannable instanceof Termin) { lTerminListe.remove(lTerminListe.getSelectionIndex()); lTermine.remove(actPlannable); ((Termin) actPlannable).delete(); ElexisEventDispatcher.reload(Termin.class); dayBar.recalc(); setEnablement(); } super.widgetSelected(e); } }); Button bSearch = new Button(topRight, SWT.PUSH); bSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); bSearch.setText(Messages.TerminDialog_find); bSearch.setToolTipText(Messages.TerminDialog_findTermin); bSearch.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ if (actKontakt != null) { Query<Termin> qbe = new Query<Termin>(Termin.class); qbe.add("Wer", "=", actKontakt.getId()); qbe.add("deleted", "<>", "1"); if (bFuture.getSelection() == false) { qbe.add("Tag", ">", new TimeTool().toString(TimeTool.DATE_COMPACT)); } java.util.List<Termin> list = qbe.execute(); // if past events are included, list future events first (sort desc) // if past events not included, list nearest future event first (sort asc) if (bFuture.getSelection()) { list.sort(new Comparator<Termin>() { @Override public int compare(Termin t1, Termin t2){ return t2.getStartTime().compareTo(t1.getStartTime()); } }); } else { list.sort(new Comparator<Termin>() { @Override public int compare(Termin t1, Termin t2){ return t1.getStartTime().compareTo(t2.getStartTime()); } }); } lTermine.clear(); lTerminListe.removeAll(); if ((list != null) && (list.size() > 0)) { for (Termin t : list) { lTermine.add(t); String label = t.getLabel(); logger.info(label); lTerminListe.add(label); } lTerminListe.select(0); } } } }); bPrint = new Button(topRight, SWT.PUSH); bPrint.setText(Messages.TerminDialog_print); bPrint.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); bPrint.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ Command cmd = cmdService.getCommand("ch.elexis.agenda.commands.printAppointmentLabel"); if (!cmd.isDefined()) { cmd.define("Print Appointment", "Print Appointment Command", cmdCategory); } try { ExecutionEvent ee = new ExecutionEvent(cmd, Collections.singletonMap("ch.elexis.agenda.param.appointmentids", lTermine.stream().map(t -> t.getId()).collect(Collectors.joining(","))), null, null); cmd.executeWithChecks(ee); } catch (Exception ex) { ExHandler.handle(ex); logger.error("Failed to execute command ch.elexis.agenda.commands.printAppointmentLabel", ex); } } }); bFuture = new Button(topRight, SWT.CHECK); bFuture.setText(Messages.TerminDialog_past); bEmergency = new Button(topRight, SWT.CHECK); bEmergency.setText(Messages.TerminDialog_emergency); // Balken Composite cBar = new Composite(ret, SWT.BORDER); cBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); cBar.setLayout(new GridLayout()); dayBar = new DayOverview(cBar); dayBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); slider = new Slider(dayBar); // unten Composite cBottom = new Composite(ret, SWT.BORDER); cBottom.setLayout(new GridLayout(3, false)); cBottom.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); // Zeile 1 new Label(cBottom, SWT.NONE).setText("PatientID"); //$NON-NLS-1$ Composite cLinks = new Composite(cBottom, SWT.NONE); cLinks.setLayout(new RowLayout(SWT.HORIZONTAL)); new Label(cLinks, SWT.NONE).setText("Personalien "); Hyperlink hlText = new Hyperlink(cLinks, SWT.NONE); hlText.setText(Messages.TerminDialog_enterPersonalia); hlText.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(final HyperlinkEvent e){ InputDialog inp = new InputDialog(getShell(), Messages.TerminDialog_enterText, Messages.TerminDialog_enterFreeText, "", null); //$NON-NLS-1$ if (inp.open() == Dialog.OK) { tName.setText(inp.getValue()); tNr.setText(""); //$NON-NLS-1$ actKontakt = null; } } }); hlText.setForeground(UiDesk.getColor(UiDesk.COL_BLUE)); // new Label(cLinks,SWT.SEPARATOR|SWT.VERTICAL); Hyperlink hlSelect = new Hyperlink(cLinks, SWT.NONE); hlSelect.setForeground(UiDesk.getColor(UiDesk.COL_BLUE)); hlSelect.setText("(Kontakt auswählen)"); hlSelect.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(final HyperlinkEvent e){ KontaktSelektor ksl = new KontaktSelektor(getShell(), Kontakt.class, "Termin zuordnen", "Bitte suchen Sie aus, wer den Termin hat", Kontakt.DEFAULT_SORT); if (ksl.open() == Dialog.OK) { actKontakt = (Kontakt) ksl.getSelection(); if (actKontakt != null) { String phoneEnhancedLabel = getPhoneEnhancedLabel(actKontakt); tName.setText(phoneEnhancedLabel); tNr.setText(actKontakt.get(Kontakt.FLD_SHORT_LABEL)); } setEnablement(); } } }); new Label(cBottom, SWT.NONE).setText(Messages.TerminDialog_Mandator); // Zeile 2 tNr = new Text(cBottom, SWT.BORDER | SWT.READ_ONLY); tName = new Text(cBottom, SWT.BORDER | SWT.READ_ONLY); tName.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); cbMandant = new Combo(cBottom, SWT.SINGLE); cbMandant.setItems(agenda.getResources()); cbMandant.setText(agenda.getActResource()); cbMandant.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ setAll(); } }); // Zeile 3 Label lBem = new Label(cBottom, SWT.NONE); lBem.setText(Messages.TerminDialog_remarks); lBem.setLayoutData(SWTHelper.getFillGridData(3, false, 1, false)); // Zeile 4 tBem = new Text(cBottom, SWT.BORDER | SWT.READ_ONLY); tBem.setLayoutData(SWTHelper.getFillGridData(3, true, 1, true)); new Label(cBottom, SWT.NONE).setText(Messages.TerminDialog_typeandstate); Label lGrund = new Label(cBottom, SWT.NONE); lGrund.setText(Messages.TerminDialog_reason); lGrund.setLayoutData(SWTHelper.getFillGridData(2, false, 1, false)); cbTyp = new Combo(cBottom, SWT.SINGLE | SWT.READ_ONLY); setItemTypes(); Point pTyp = cbTyp.computeSize(SWT.DEFAULT, SWT.DEFAULT); tGrund = new Text(cBottom, SWT.BORDER | SWT.MULTI); tGrund.setLayoutData(SWTHelper.getFillGridData(2, true, 2, true)); cbStatus = new Combo(cBottom, SWT.SINGLE | SWT.READ_ONLY); cbStatus.setItems(Termin.TerminStatus); Point pStatus = cbStatus.computeSize(SWT.DEFAULT, SWT.DEFAULT); int xMax = Math.max(pTyp.x, pStatus.x); cbTyp.setLayoutData(new GridData(xMax, SWT.DEFAULT)); cbStatus.setLayoutData(new GridData(xMax, SWT.DEFAULT)); StatusTypListener statusTypListener = new StatusTypListener(); cbTyp.addSelectionListener(statusTypListener); cbStatus.addSelectionListener(statusTypListener); String val = tMap.get(Termin.TerminTypes[1]); if (val == null) { val = tMap.get(Messages.TerminDialog_32); } niDauer.setValue(Integer.parseInt(val)); bSerie.setEnabled(false); // bSearch.setEnabled(false); // bNext.setEnabled(false); // bPrev.setEnabled(false); ret.setSize(ret.computeSize(SWT.DEFAULT, SWT.DEFAULT)); return sc; } private void setItemTypes(){ cbTyp.removeAll(); for (String t : Termin.TerminTypes) { String ts = tMap.get(t); if ((ts != null) && (ts.equals("0"))) { //$NON-NLS-1$ continue; } cbTyp.add(t); } } class StatusTypListener extends SelectionAdapter { @Override public void widgetSelected(final SelectionEvent e){ if (e.getSource().equals(cbTyp)) { String type = cbTyp.getItem(cbTyp.getSelectionIndex()); if (actPlannable instanceof Termin) { ((Termin) actPlannable).setType(type); bModified = true; } else if (actPlannable instanceof Termin.Free) { Hashtable<String, String> map = Plannables.getTimePrefFor(agenda.getActResource()); String nt = map.get(type); if (nt == null) { nt = map.get("std"); //$NON-NLS-1$ if (nt == null) { nt = "10"; //$NON-NLS-1$ } } int en = Integer.parseInt(nt); niDauer.setValue(en); slider.set(); } } else if (e.getSource().equals(cbStatus)) { if (actPlannable instanceof Termin) { ((Termin) actPlannable) .setStatus(cbStatus.getItem(cbStatus.getSelectionIndex())); bModified = true; } } setEnablement(); } } @Override public void create(){ setShellStyle(getShellStyle() | SWT.RESIZE); super.create(); setMessage(Messages.TerminDialog_editTermins); setTitleImage(Images.IMG_LOGO.getImage()); getShell().setText(Messages.TerminDialog_termin); dayBar.recalc(); if (actPlannable instanceof Termin) { lTerminListe.add(((Termin) actPlannable).getLabel()); lTermine.add((Termin) actPlannable); lTerminListe.select(0); } if (actKontakt == null) { setTitle(Messages.TerminDialog_noPatSelected); tNr.setText(""); //$NON-NLS-1$ if (actPlannable instanceof Termin) { tName.setText(((Termin) actPlannable).getPersonalia()); } else { tName.setText(""); //$NON-NLS-1$ } tBem.setText(""); //$NON-NLS-1$ } else { setTitle(actKontakt.getLabel()); tNr.setText(Kontakt.FLD_SHORT_LABEL); String phoneEnhancedLabel = getPhoneEnhancedLabel(actKontakt); tName.setText(phoneEnhancedLabel); tBem.setText(actKontakt.getBemerkung()); } setAll(); } private void setAll(){ tiVon.setTimeInMinutes(actPlannable.getStartMinute()); dp.setDate(new TimeTool(actPlannable.getDay()).getTime()); // actDate.setTime(dp.getDate()); agenda.setActDate(new TimeTool(dp.getDate().getTime())); agenda.setActResource(cbMandant.getText()); // actBereich = cbMandant.getText(); if (actPlannable instanceof Termin.Free) { setCombo(cbTyp, Termin.typStandard(), 0); setCombo(cbStatus, Termin.statusStandard(), 0); bChange.setEnabled(false); String dauer = tMap.get(Termin.typStandard()); if (dauer == null) { dauer = tMap.get(Messages.TerminDialog_40); } if (dauer == null) { dauer = "15"; //$NON-NLS-1$ } niDauer.setValue(Integer.parseInt(dauer)); } else { Termin actTermin = (Termin) actPlannable; tGrund.setText(actTermin.getGrund()); setCombo(cbTyp, actTermin.getType(), 0); setCombo(cbStatus, actTermin.getStatus(), 0); bLocked.setSelection(actTermin.getFlag(Termin.SW_LOCKED)); niDauer.getControl().setSelection(actPlannable.getDurationInMinutes()); bEmergency.setSelection(StringUtils.equals(actTermin.get(Termin.FLD_PRIORITY), "1")); } dayBar.redraw(); slider.set(); } public void setCollisionErrorLevel(CollisionErrorLevel level){ this.collisionErrorLevel = level; } private void enable(final boolean mode){ msg = Messages.TerminDialog_editTermins; if (collisionErrorLevel == CollisionErrorLevel.ERROR) { bChange.setEnabled(mode); bSave.setEnabled(mode); getButton(IDialogConstants.OK_ID).setEnabled(mode); } slider.setBackground(UiDesk.getColor(UiDesk.COL_LIGHTGREY)); //$NON-NLS-1$ if (!mode) { slider.setBackground(UiDesk.getColor(UiDesk.COL_DARKGREY)); //$NON-NLS-1$ msg = Messages.TerminDialog_editTermins + "\n\t" + Messages.TerminDialog_collision; } getShell().getDisplay().asyncExec(new Runnable() { @Override public void run(){ if (collisionErrorLevel == CollisionErrorLevel.ERROR) { setMessage(msg, mode ? IMessageProvider.NONE : IMessageProvider.ERROR); } else if (collisionErrorLevel == CollisionErrorLevel.WARNING) { setMessage(msg, mode ? IMessageProvider.NONE : IMessageProvider.WARNING); } } }); } private void setEnablement(){ TimeSpan ts = new TimeSpan(tiVon.setTimeTool(agenda.getActDate()), niDauer.getValue()); if (actPlannable instanceof Termin.Free) { if (Plannables.collides(ts, dayBar.list, null) || terminOverlaps(agenda.getActDate(), ts)) { enable(false); } else { enable(true); } // bLocked.setEnabled(false); } else { if (Plannables.collides(ts, dayBar.list, (Termin) actPlannable)) { enable(false); } else { if (bModified) { if (actKontakt != null && terminOverlaps(agenda.getActDate(), ts)) { enable(false); return; } enable(true); } else { enable(false); } } // bLocked.setEnabled(true); } } private void setCombo(final Combo combo, final String value, final int def){ String[] elems = combo.getItems(); int idx = StringTool.getIndex(elems, value); if (idx == -1) { idx = def; } combo.select(idx); } class DayOverview extends Composite implements PaintListener { Point d; int sep; java.util.List<IPlannable> list; DayOverview(final Composite parent){ super(parent, SWT.NONE); addPaintListener(this); addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent e){ if (e.y > sep + 2) { rasterIndex = (rasterIndex >= rasterValues.length) ? 0 : rasterIndex + 1; ConfigServiceHolder.setUser("agenda/dayView/raster", rasterIndex); //$NON-NLS-1$ redraw(); } else { // super.mouseDown(e); Point loc = slider.getLocation(); slider.setLocation(e.x, loc.y); slider.updateTimes(); } } }); } /** * Tagesbalken neu kalkulieren (Startzeit, Endzeit, pixel pro Minute etc.) * */ void recalc(){ list = Plannables.loadTermine(agenda.getActResource(), agenda.getActDate()); tagStart = ts * 60; tagEnd = te * 60; int i = 0; IPlannable pi = list.get(i); // Tagesanzeige ca. eine halbe Stunde vor dem ersten reservierten // Zeitraum anfangen if (pi.getType().equals(Termin.typReserviert())) { tagStart = pi.getDurationInMinutes() < 31 ? 0 : pi.getDurationInMinutes() - 30; } else { tagStart = 0; } i = list.size() - 1; pi = list.get(i); int end = pi.getStartMinute() + pi.getDurationInMinutes(); if (end < 1408) { tagEnd = 1439; } if (tagStart != 0) { tagStart = tagStart / 60 * 60; } if (tagEnd < 1439) { tagEnd = (tagEnd + 30) / 60 * 60; } minutes = tagEnd - tagStart; d = this.getSize(); pixelPerMinute = d.x / minutes; sep = d.y / 2; /* * double minutes=(tagEnd-tagStart); minutewidth=d.x/minutes; */ } @Override public Point computeSize(final int wHint, final int hHint, final boolean changed){ return new Point(getParent().getSize().x, 40); } /** * Tagesbalken zeichnen */ public void paintControl(final PaintEvent pe){ recalc(); GC g = pe.gc; Color def = g.getBackground(); // Balken zeichnen g.setBackground(UiDesk.getColor(UiDesk.COL_GREEN)); Rectangle r = new Rectangle(0, 0, d.x, sep - 2); g.fillRectangle(r); // Termine darauf zeichnen for (IPlannable p : list) { Plannables.paint(g, p, r, tagStart, tagEnd); } // Lineal zeichnen g.setBackground(def); g.setFont(UiDesk.getFont(Preferences.USR_SMALLFONT)); g.drawLine(0, sep, d.x, sep); if (rasterIndex >= rasterValues.length) { rasterIndex = 0; ConfigServiceHolder.setUser("agenda/dayView/raster", rasterIndex); //$NON-NLS-1$ } double chunkwidth = rasterValues[rasterIndex] * pixelPerMinute; int chunksPerHour = 60 / rasterValues[rasterIndex]; int ch = chunksPerHour - 1; int hr = tagStart / 60; if (chunkwidth < 0.1) { return; } for (double x = 0; x <= d.x; x += chunkwidth) { int lx = (int) Math.round(x); if (++ch == chunksPerHour) { g.drawLine(lx, sep - 1, lx, sep + 6); g.drawString(Integer.toString(hr++), lx, sep + 6); ch = 0; } else { g.drawLine(lx, sep, lx, sep + 4); } } slider.redraw(); } } private class Slider extends Composite implements MouseListener, MouseMoveListener { boolean isDragging; Slider(final Composite parent){ super(parent, SWT.BORDER); setBackground(UiDesk.getColor(UiDesk.COL_RED)); //$NON-NLS-1$ addMouseListener(this); addMouseMoveListener(this); } void set(){ int v = tiVon.getTimeAsMinutes(); int d = niDauer.getValue(); Rectangle r = getParent().getBounds(); int x = (int) Math.round((v - tagStart) * pixelPerMinute); int w = (int) Math.round(d * pixelPerMinute); setBounds(x, 0, w, r.height / 2); tiBis.setTimeInMinutes(v + d); bModified = true; setEnablement(); } public void mouseDoubleClick(final MouseEvent e){} public void mouseDown(final MouseEvent e){ isDragging = true; } public void mouseUp(final MouseEvent e){ if (isDragging) { isDragging = false; updateTimes(); } } public void mouseMove(final MouseEvent e){ if (isDragging) { Point loc = getLocation(); int x = loc.x + e.x; setLocation(x, loc.y); } } public void updateTimes(){ Point loc = getLocation(); Rectangle rec = getParent().getBounds(); double minutes = tagEnd - tagStart; double minutesPerPixel = minutes / rec.width; int minute = (int) Math.round(loc.x * minutesPerPixel) + tagStart; int raster = rasterValues[rasterIndex]; minute = ((minute + (raster >> 1)) / raster) * raster; tiVon.setTimeInMinutes(minute); set(); } } public void setTime(TimeTool time){ tiVon.setText(time.toString(TimeTool.TIME_SMALL)); slider.set(); } @Override protected void okPressed(){ createTermin(false); super.okPressed(); } private void createTermin(final boolean bMulti){ int von = tiVon.getTimeAsMinutes(); int bis = von + niDauer.getValue(); String typ = cbTyp.getItem(cbTyp.getSelectionIndex()); String status = cbStatus.getItem(cbStatus.getSelectionIndex()); String priority = bEmergency.getSelection() ? "1" : "0"; Termin actTermin = null; if (actPlannable instanceof Termin.Free) { Termin newTermin = new Termin(agenda.getActResource(), agenda.getActDate().toString(TimeTool.DATE_COMPACT), von, bis, typ, status, priority); actTermin = newTermin; } else { actTermin = (Termin) actPlannable; if (bMulti) { Termin clonedTermin = (Termin) actTermin.clone(); AcquireLockBlockingUi.aquireAndRun(clonedTermin, new ILockHandler() { @Override public void lockFailed(){ clonedTermin.delete(); } @Override public void lockAcquired(){ // do nothing } }); actTermin = clonedTermin; } actTermin.set(new String[] { "BeiWem", "Tag", "Beginn", "Dauer", "Typ", "Status", Termin.FLD_PRIORITY }, new String[] { agenda.getActResource(), agenda.getActDate().toString(TimeTool.DATE_COMPACT), Integer.toString(von), Integer.toString(bis - von), typ, status, priority }); } lTerminListe.add(actTermin.getLabel()); lTermine.add(actTermin); if (actKontakt != null) { actTermin.setKontakt(actKontakt); } else { actTermin.set("Wer", tName.getText()); //$NON-NLS-1$ } actTermin.setGrund(tGrund.getText()); actTermin.set(Termin.FLD_CREATOR, ContextServiceHolder.get().getActiveUser().get().getLabel()); if (bLocked.getSelection()) { actTermin.setFlag(Termin.SW_LOCKED); } ElexisEventDispatcher.reload(Termin.class); dayBar.recalc(); actPlannable = actTermin; setEnablement(); } /** * checks if the given appointment overlaps with any other appointment of this patient * * @param actDate * date of the appointment * @param terminTS * timespan of the appointment * @return true if there is a collision */ private boolean terminOverlaps(TimeTool actDate, TimeSpan terminTS){ boolean avoidPatientDoubleBooking = CoreHub.localCfg.get(PreferenceConstants.AG_AVOID_PATIENT_DOUBLE_BOOKING, PreferenceConstants.AG_AVOID_PATIENT_DOUBLE_BOOKING_DEFAULT); if (avoidPatientDoubleBooking && actKontakt != null) { Query<Termin> tQuery = new Query<Termin>(Termin.class); tQuery.add(Termin.FLD_PATIENT, Query.EQUALS, actKontakt.getId()); tQuery.add(Termin.FLD_TAG, Query.EQUALS, actDate.toString(TimeTool.DATE_COMPACT)); java.util.List<Termin> termine = tQuery.execute(); if (actPlannable instanceof Termin.Free) { for (Termin t : termine) { TimeSpan ts = t.getTimeSpan(); if (ts.overlap(terminTS) != null) { return true; } } } else { Termin curTermin = (Termin) actPlannable; for (Termin t : termine) { // only compare if it's not the currently open appointment if (!t.getId().equals(curTermin.getId())) { TimeSpan ts = t.getTimeSpan(); if (ts.overlap(terminTS) != null) { return true; } } } } return false; } return false; } private String getPhoneEnhancedLabel(Kontakt actKontakt){ String telephoneLabel = actKontakt.getTelephoneLabel(); String label = actKontakt.getLabel() + ((telephoneLabel.length() > 0) ? " (" + telephoneLabel + ")" : ""); return label; } }
package io.scif.img; import io.scif.FormatException; import io.scif.Metadata; import io.scif.Plane; import io.scif.Reader; import io.scif.config.SCIFIOConfig; import io.scif.filters.ChannelFiller; import io.scif.filters.MinMaxFilter; import io.scif.filters.PlaneSeparator; import io.scif.filters.ReaderFilter; import io.scif.img.cell.SCIFIOCellImgFactory; import io.scif.img.converters.PlaneConverter; import io.scif.img.converters.PlaneConverterService; import io.scif.services.InitializeService; import io.scif.util.FormatTools; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.img.Img; import net.imglib2.img.ImgFactory; import net.imglib2.img.basictypeaccess.PlanarAccess; import net.imglib2.img.cell.AbstractCellImgFactory; import net.imglib2.meta.Axes; import net.imglib2.meta.AxisType; import net.imglib2.meta.CalibratedAxis; import net.imglib2.meta.ImgPlus; import net.imglib2.type.NativeType; import net.imglib2.type.Type; import net.imglib2.type.numeric.RealType; import org.scijava.Context; import org.scijava.app.StatusService; import org.scijava.plugin.Parameter; /** * Reads in an {@link ImgPlus} using SCIFIO. * * @author Curtis Rueden * @author Mark Hiner * @author Stephan Preibisch * @author Stephan Saalfeld */ public class ImgOpener extends AbstractImgIOComponent { @Parameter private StatusService statusService; @Parameter private PlaneConverterService pcService; @Parameter private InitializeService initializeService; // -- Constructors -- public ImgOpener() { super(); } public ImgOpener(final Context ctx) { super(ctx); } // -- Static methods -- // -- ImgOpener methods -- /** * Reads in an {@link ImgPlus} from the first image of the given source. * * @param source - the location of the dataset to open * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public ImgPlus<?> openImg(final String source) throws ImgIOException { return openImg(source, new SCIFIOConfig()); } /** * Reads in an {@link ImgPlus} from the first image of the given source. * * @param source - the location of the dataset to open * @param type - The {@link Type} T of the output {@link ImgPlus}. * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public <T extends RealType<T> & NativeType<T>> ImgPlus<T> openImg( final String source, final T type) throws ImgIOException { return openImg(source, type, new SCIFIOConfig()); } /** * Reads in an {@link ImgPlus} from the specified index of the given source. * Can specify a variety of options via {@link SCIFIOConfig}. * * @param source - the location of the dataset to open * @param config - {@link SCIFIOConfig} to use when opening this dataset * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public ImgPlus<?> openImg(final String source, final SCIFIOConfig config) throws ImgIOException { final Reader r = createReader(source, config); final RealType t = getType(r, config); final ImgFactoryHeuristic heuristic = getHeuristic(config); ImgFactory imgFactory; try { if (NativeType.class.isAssignableFrom(t.getClass())) imgFactory = heuristic.createFactory(r.getMetadata(), config.imgOpenerGetImgModes(), (NativeType) t); else return null; } catch (final IncompatibleTypeException e) { throw new ImgIOException(e); } return openImg(r, t, imgFactory, config); } /** * Reads in an {@link ImgPlus} from the specified index of the given source. * Can specify the Type that should be opened. * * @param source - the location of the dataset to open * @param type - The {@link Type} T of the output {@link ImgPlus}. * @param config - {@link SCIFIOConfig} to use when opening this dataset * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public <T extends RealType<T> & NativeType<T>> ImgPlus<T> openImg( final String source, final T type, final SCIFIOConfig config) throws ImgIOException { final Reader r = createReader(source, config); return openImg(r, type, config); } /** * @param source - the location of the dataset to open * @param imgFactory - The {@link ImgFactory} to use for creating the * resultant {@link ImgPlus}. * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ @SuppressWarnings("rawtypes") public ImgPlus<?> openImg(final String source, final ImgFactory imgFactory) throws ImgIOException { return openImg(source, imgFactory, new SCIFIOConfig() .imgOpenerSetComputeMinMax(true)); } /** * @param source - the location of the dataset to open * @param imgFactory - The {@link ImgFactory} to use for creating the * resultant {@link ImgPlus}. * @param config - {@link SCIFIOConfig} to use when opening this dataset * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public ImgPlus<?> openImg(final String source, final ImgFactory imgFactory, final SCIFIOConfig config) throws ImgIOException { final Reader r = createReader(source, config); final RealType t = getType(r, config); return openImg(r, t, imgFactory, config); } /** * @param source - the location of the dataset to open * @param imgFactory - The {@link ImgFactory} to use for creating the * resultant {@link ImgPlus}. * @param type - The {@link Type} T of the output {@link ImgPlus}, which must * match the typing of the {@link ImgFactory}. * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public <T extends RealType<T>> ImgPlus<T> openImg(final String source, final ImgFactory<T> imgFactory, final T type) throws ImgIOException { SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetComputeMinMax(true); final Reader r = createReader(source, config); return openImg(r, type, imgFactory, config); } /** * @param reader - An initialized {@link Reader} to use for reading image * data. * @param type - The {@link Type} T of the output {@link ImgPlus}, which must * match the typing of the {@link ImgFactory}. * @param config - {@link SCIFIOConfig} to use when opening this dataset * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public <T extends RealType<T> & NativeType<T>> ImgPlus<T> openImg( final Reader reader, final T type, final SCIFIOConfig config) throws ImgIOException { final ImgFactoryHeuristic heuristic = getHeuristic(config); ImgFactory<T> imgFactory; try { imgFactory = heuristic.createFactory(reader.getMetadata(), config .imgOpenerGetImgModes(), type); } catch (final IncompatibleTypeException e) { throw new ImgIOException(e); } return openImg(reader, type, imgFactory, config); } /** * Reads in an {@link ImgPlus} from the given initialized {@link Reader}, * using the given {@link ImgFactory} to construct the {@link Img}. The * {@link Type} T to read is defined by the third parameter. * <p> * NB: Any Reader provided must be wrapped by a {@link PlaneSeparator} filter. * </p> * * @param reader - An initialized {@link Reader} to use for reading image * data. * @param imgFactory - The {@link ImgFactory} to use for creating the * resultant {@link ImgPlus}. * @param type - The {@link Type} T of the output {@link ImgPlus}, which must * match the typing of the {@link ImgFactory}. * @param config - {@link SCIFIOConfig} to use when opening this dataset * @return - the {@link ImgPlus} or null * @throws ImgIOException if there is a problem reading the image data. */ public <T extends RealType<T>> ImgPlus<T> openImg(final Reader reader, final T type, final ImgFactory<T> imgFactory, final SCIFIOConfig config) throws ImgIOException { final int imageIndex = config.imgOpenerGetIndex(); // create image and read metadata final long[] dimLengths = utils().getConstrainedLengths(reader.getMetadata(), config); if (SCIFIOCellImgFactory.class.isAssignableFrom(imgFactory.getClass())) { ((SCIFIOCellImgFactory<?>) imgFactory).setReader(reader); ((SCIFIOCellImgFactory<?>) imgFactory).setSubRegion(config .imgOpenerGetRegion()); } final Img<T> img = imgFactory.create(dimLengths, type); final ImgPlus<T> imgPlus = makeImgPlus(img, reader, config); final String id = reader.getCurrentFile(); imgPlus.setSource(id); imgPlus.initializeColorTables((int) reader.getPlaneCount(imageIndex)); // If we have a planar img, read the planes now. Otherwise they // will be read on demand. if (AbstractCellImgFactory.class.isAssignableFrom(imgFactory.getClass())) { statusService.showStatus("Created CellImg for dynamic loading"); } else { final float startTime = System.currentTimeMillis(); final long planeCount = reader.getPlaneCount(imageIndex); try { readPlanes(reader, imageIndex, type, imgPlus, config); } catch (final FormatException e) { throw new ImgIOException(e); } catch (final IOException e) { throw new ImgIOException(e); } final long endTime = System.currentTimeMillis(); final float time = (endTime - startTime) / 1000f; statusService.showStatus(id + ": read " + planeCount + " planes in " + time + "s"); } return imgPlus; } // -- Helper methods -- @SuppressWarnings("rawtypes") private RealType getType(final Reader r, final SCIFIOConfig config) { int imageIndex = 0; if (config != null) imageIndex = config.imgOpenerGetIndex(); return utils().makeType(r.getMetadata().get(imageIndex).getPixelType()); } private ImgFactoryHeuristic getHeuristic(final SCIFIOConfig imgOptions) { ImgFactoryHeuristic heuristic = imgOptions.imgOpenerGetImgFactoryHeuristic(); if (heuristic == null) heuristic = new DefaultImgFactoryHeuristic(); return heuristic; } /** * @param source - Dataset source to open * @param config - Options object for opening this dataset * @return A Reader initialized to open the specified id */ private Reader createReader(final String source, final SCIFIOConfig config) throws ImgIOException { final boolean computeMinMax = config.imgOpenerIsComputeMinMax(); statusService.showStatus("Initializing " + source); ReaderFilter r = null; try { r = initializeService.initializeReader(source, config); r.enable(ChannelFiller.class); r.enable(PlaneSeparator.class).separate(axesToSplit(r)); if (computeMinMax) r.enable(MinMaxFilter.class); } catch (final FormatException e) { throw new ImgIOException(e); } catch (final IOException e) { throw new ImgIOException(e); } return r; } /** * Returns a list of all AxisTypes that should be split out. This is a list of * all non-X,Y planar axes. Always tries to split {@link Axes#CHANNEL}. */ private AxisType[] axesToSplit(final ReaderFilter r) { final Set<AxisType> axes = new HashSet<AxisType>(); final Metadata meta = r.getTail().getMetadata(); // Split any non-X,Y axis for (final CalibratedAxis t : meta.get(0).getAxesPlanar()) { final AxisType type = t.type(); if (!(type == Axes.X || type == Axes.Y)) { axes.add(type); } } // Ensure channel is attempted to be split axes.add(Axes.CHANNEL); return axes.toArray(new AxisType[axes.size()]); } private AxisType[] getAxisTypes(final int imageIndex, final Metadata m) { final AxisType[] types = new AxisType[m.get(imageIndex).getAxes().size()]; for (int i = 0; i < types.length; i++) { types[i] = m.get(imageIndex).getAxis(i).type(); } return types; } /** Compiles an N-dimensional list of calibration values. */ private double[] getCalibration(final int imageIndex, final Metadata m) { final double[] calibration = new double[m.get(imageIndex).getAxes().size()]; for (int i = 0; i < calibration.length; i++) { calibration[i] = FormatTools .getScale(m, imageIndex, m.get(imageIndex).getAxis(i).type()); } return calibration; } /** * Wraps the given {@link Img} in an {@link ImgPlus} with metadata * corresponding to the specified initialized {@link Reader}. */ private <T extends RealType<T>> ImgPlus<T> makeImgPlus(final Img<T> img, final Reader r, final SCIFIOConfig config) { final String id = r.getCurrentFile(); final File idFile = new File(id); final String name = idFile.exists() ? idFile.getName() : id; final double[] cal = getCalibration(config.imgOpenerGetIndex(), r.getMetadata()); final AxisType[] dimTypes = getAxisTypes(config.imgOpenerGetIndex(), r.getMetadata()); final Reader base; base = unwrap(r); final Metadata meta = r.getMetadata(); int rgbChannelCount = base.getMetadata().get(0).isMultichannel() ? (int) base.getMetadata() .get(0).getAxisLength(Axes.CHANNEL) : 1; if (base.getMetadata().get(0).isIndexed()) rgbChannelCount = 3; final int validBits = meta.get(0).getBitsPerPixel(); final ImgPlus<T> imgPlus = new SCIFIOImgPlus<T>(img, name, dimTypes, cal); imgPlus.setValidBits(validBits); int compositeChannelCount = rgbChannelCount; if (rgbChannelCount == 1) { // HACK: Support ImageJ color mode embedded in TIFF files. final String colorMode = (String) meta.getTable().get("Color mode"); if ("composite".equals(colorMode)) { compositeChannelCount = (int) meta.get(0).getAxisLength(Axes.CHANNEL); } } imgPlus.setCompositeChannelCount(compositeChannelCount); return imgPlus; } /** * Finds the lowest level wrapped reader, preferably a {@link ChannelFiller}, * but otherwise the base reader. This is useful for determining whether the * input data is intended to be viewed with multiple channels composited * together. */ private Reader unwrap(final Reader r) { if (!(r instanceof ReaderFilter)) return r; final ReaderFilter rf = (ReaderFilter) r; return rf.getTail(); } /** * Reads planes from the given initialized {@link Reader} into the specified * {@link Img}. */ private <T extends RealType<T>> void readPlanes(final Reader r, final int imageIndex, final T type, final ImgPlus<T> imgPlus, final SCIFIOConfig config) throws FormatException, IOException { // TODO - create better container types; either: // 1) an array container type using one byte array per plane // 2) as #1, but with an Reader reference reading planes on demand // 3) as PlanarRandomAccess, but with an Reader reference // reading planes on demand // PlanarRandomAccess is useful for efficient access to pixels in ImageJ // (e.g., getPixels) // #1 is useful for efficient SCIFIO import, and useful for tools // needing byte arrays (e.g., BufferedImage Java3D texturing by reference) // #2 is useful for efficient memory use for tools wanting matching // primitive arrays (e.g., virtual stacks in ImageJ) // #3 is useful for efficient memory use // get container final PlanarAccess<?> planarAccess = utils().getPlanarAccess(imgPlus); @SuppressWarnings("rawtypes") final RealType inputType = utils().makeType(r.getMetadata().get(0).getPixelType()); final T outputType = type; final boolean compatibleTypes = outputType.getClass().isAssignableFrom(inputType.getClass()); // populate planes final boolean isPlanar = planarAccess != null && compatibleTypes; final boolean isArray = utils().getArrayAccess(imgPlus) != null && compatibleTypes; final SubRegion region = config.imgOpenerGetRegion(); final Metadata m = r.getMetadata(); // Starting indices for the planar dimensions final long[] planarMin = new long[m.get(imageIndex).getAxesPlanar().size()]; // Lengths in the planar dimensions final long[] planarLength = new long[m.get(imageIndex).getAxesPlanar().size()]; // Non-planar indices to open final DimRange[] npRanges = new DimRange[m.get(imageIndex).getAxesNonPlanar().size()]; final long[] npIndices = new long[npRanges.length]; // populate plane dimensions int index = 0; for (final CalibratedAxis planarAxis : m.get(imageIndex).getAxesPlanar()) { if (region != null && region.hasRange(planarAxis.type())) { planarMin[index] = region.getRange(planarAxis.type()).head(); planarLength[index] = region.getRange(planarAxis.type()).tail() - planarMin[index] + 1; } else { planarMin[index] = 0; planarLength[index] = m.get(imageIndex).getAxisLength(planarAxis); } index++; } // determine non-planar indices to open index = 0; for (final CalibratedAxis npAxis : m.get(imageIndex).getAxesNonPlanar()) { if (region != null && region.hasRange(npAxis.type())) { npRanges[index++] = region.getRange(npAxis.type()); } else { npRanges[index++] = new DimRange(0l, m.get(imageIndex).getAxisLength(npAxis.type()) - 1); } } PlaneConverter converter = config.imgOpenerGetPlaneConverter(); if (converter == null) { // if we have a PlanarAccess we can use a PlanarAccess converter, // otherwise we can use a more general RandomAccess approach if (isArray) { converter = pcService.getArrayConverter(); } else if (isPlanar) { converter = pcService.getPlanarConverter(); } else converter = pcService.getDefaultConverter(); } read(imageIndex, imgPlus, r, config, converter, planarMin, planarLength, npRanges, npIndices); if (config.imgOpenerIsComputeMinMax()) populateMinMax(r, imgPlus, imageIndex); } @SuppressWarnings("rawtypes") private void read(final int imageIndex, final ImgPlus imgPlus, final Reader r, final SCIFIOConfig config, final PlaneConverter converter, final long[] planarMin, final long[] planarLength, final DimRange[] npRanges, final long[] npIndices) throws FormatException, IOException { read(imageIndex, imgPlus, r, config, converter, null, planarMin, planarLength, npRanges, npIndices, 0, new int[] { 0 }); } @SuppressWarnings({ "unchecked", "rawtypes" }) private Plane read(final int imageIndex, final ImgPlus imgPlus, final Reader r, final SCIFIOConfig config, final PlaneConverter converter, Plane tmpPlane, final long[] planarMin, final long[] planarLength, final DimRange[] npRanges, final long[] npIndices, final int depth, final int[] planeCount) throws FormatException, IOException { if (depth < npRanges.length) { // We need to invert the depth index to get the current non-planar // axis index, to ensure axes are iteratead in fastest to slowest order final int npPosition = npRanges.length - 1 - depth; // Recursive step. Sets the non-planar indices for (int i = 0; i < npRanges[npPosition].indices().size(); i++) { npIndices[npPosition] = npRanges[npPosition].indices().get(i); tmpPlane = read(imageIndex, imgPlus, r, config, converter, tmpPlane, planarMin, planarLength, npRanges, npIndices, depth + 1, planeCount); } } else { // Terminal step. Reads the plane at the rasterized index, given the // non-planar indices final int planeIndex = (int) FormatTools.positionToRaster(0, r, npIndices); if (config.imgOpenerIsComputeMinMax()) { populateMinMax(r, imgPlus, imageIndex); } if (tmpPlane == null) { tmpPlane = r.openPlane(config.imgOpenerGetIndex(), planeIndex, planarMin, planarLength); } else { tmpPlane = r.openPlane(config.imgOpenerGetIndex(), planeIndex, tmpPlane, planarMin, planarLength, config); } // copy the data to the ImgPlus converter.populatePlane(r, imageIndex, planeCount[0], tmpPlane.getBytes(), imgPlus, config); // store color table imgPlus.setColorTable(tmpPlane.getColorTable(), planeCount[0]); // Update plane count planeCount[0]++; } return tmpPlane; } private void populateMinMax(final Reader r, final ImgPlus<?> imgPlus, final int imageIndex) { final int sizeC = (int) r.getMetadata().get(imageIndex).getAxisLength(Axes.CHANNEL); final ReaderFilter rf = (ReaderFilter) r; final MinMaxFilter minMax = rf.enable(MinMaxFilter.class); for (int c = 0; c < sizeC; c++) { final Double min = minMax.getAxisKnownMinimum(imageIndex, Axes.CHANNEL, c); final Double max = minMax.getAxisKnownMinimum(imageIndex, Axes.CHANNEL, c); imgPlus.setChannelMinimum(c, min == null ? Double.NaN : min); imgPlus.setChannelMaximum(c, max == null ? Double.NaN : max); } } }
package ru.job4j.map; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Class User. * * @author Ayuzyak * @since 12.06.2017 * @version 1.0 */ public class User { /** * User name. */ private String name; /** * Number of children. */ private int children; /** * Date of birthday. */ private Calendar birthday; /** * User constructor. * @param name - User name. * @param children - number of children. * @param birthday - date of birthday. */ public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } /** * Overriding method equals(). * @param o - object for compare. * @return true if objects are same. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return children == user.children && Objects.equals(name, user.name) && Objects.equals(birthday, user.birthday); } /** * Return hash code value for object. * @return int value. */ @Override public int hashCode() { return Objects.hash(name, children, birthday); } /** * Main method. * @param args is empty. */ public static void main(String[] args) { Calendar firstBirth = new GregorianCalendar(1900, 0, 10); Calendar secondBirth = new GregorianCalendar(1900, 0, 10); User firstUser = new User("Andr", 2, firstBirth); User secondUser = new User("Andr", 2, secondBirth); Map<User, Object> map = new HashMap<>(); map.put(firstUser, null); map.put(secondUser, null); System.out.println(map); } }
package com.podio.sdk.volley; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.android.volley.AuthFailureError; import com.android.volley.Cache.Entry; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.RequestFuture; import com.podio.sdk.JsonParser; import com.podio.sdk.PodioError; import com.podio.sdk.Session; import com.podio.sdk.internal.Utils; public class VolleyRequest<T> extends Request<T> implements com.podio.sdk.Request<T> { private static final ArrayList<ErrorListener> GLOBAL_ERROR_LISTENERS = new ArrayList<ErrorListener>(); private static final ArrayList<SessionListener> GLOBAL_SESSION_LISTENERS = new ArrayList<SessionListener>(); public static ErrorListener addGlobalErrorListener(ErrorListener errorListener) { return errorListener != null && GLOBAL_ERROR_LISTENERS.add(errorListener) ? errorListener : null; } public static SessionListener addGlobalSessionListener(SessionListener sessionListener) { return sessionListener != null && GLOBAL_SESSION_LISTENERS.add(sessionListener) ? sessionListener : null; } public static ErrorListener removeGlobalErrorListener(ErrorListener errorListener) { int index = GLOBAL_ERROR_LISTENERS.indexOf(errorListener); return GLOBAL_ERROR_LISTENERS.contains(errorListener) ? GLOBAL_ERROR_LISTENERS.remove(index) : null; } public static SessionListener removeGlobalSessionListener(SessionListener sessionListener) { int index = GLOBAL_SESSION_LISTENERS.indexOf(sessionListener); return GLOBAL_SESSION_LISTENERS.contains(sessionListener) ? GLOBAL_SESSION_LISTENERS.remove(index) : null; } static <E> VolleyRequest<E> newRequest(com.podio.sdk.Request.Method method, String url, String body, Class<E> classOfResult) { RequestFuture<E> volleyRequestFuture = RequestFuture.newFuture(); int volleyMethod = parseMethod(method); VolleyRequest<E> request = new VolleyRequest<E>(volleyMethod, url, classOfResult, volleyRequestFuture, false); request.contentType = "application/json; charset=UTF-8"; if (Utils.notEmpty(Session.accessToken())) { request.headers.put("Authorization", "Bearer " + Session.accessToken()); } request.body = body; return request; } static VolleyRequest<Void> newAuthRequest(String url, Map<String, String> params) { RequestFuture<Void> volleyRequestFuture = RequestFuture.newFuture(); int volleyMethod = parseMethod(com.podio.sdk.Request.Method.POST); VolleyRequest<Void> request = new VolleyRequest<Void>(volleyMethod, url, null, volleyRequestFuture, true); request.contentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.params.putAll(params); return request; } protected static int parseMethod(com.podio.sdk.Request.Method method) { switch (method) { case DELETE: return com.android.volley.Request.Method.DELETE; case GET: return com.android.volley.Request.Method.GET; case POST: return com.android.volley.Request.Method.POST; case PUT: return com.android.volley.Request.Method.PUT; default: return com.android.volley.Request.Method.GET; } } private final ArrayList<AuthErrorListener<T>> authErrorListeners; private final ArrayList<ResultListener<T>> resultListeners; private final ArrayList<SessionListener> sessionListeners; private final ArrayList<ErrorListener> errorListeners; private final RequestFuture<T> volleyRequestFuture; private final Class<T> classOfResult; protected HashMap<String, String> headers; protected HashMap<String, String> params; protected String contentType; protected String body; private T result; private Throwable error; private boolean isAuthRequest; private boolean hasSessionChanged; protected VolleyRequest(int method, String url, Class<T> resultType, RequestFuture<T> volleyRequestFuture, boolean isAuthRequest) { super(method, url, volleyRequestFuture); this.authErrorListeners = new ArrayList<AuthErrorListener<T>>(); this.resultListeners = new ArrayList<ResultListener<T>>(); this.sessionListeners = new ArrayList<SessionListener>(); this.errorListeners = new ArrayList<ErrorListener>(); this.volleyRequestFuture = volleyRequestFuture; this.volleyRequestFuture.setRequest(this); this.classOfResult = resultType; this.headers = new HashMap<String, String>(); this.params = new HashMap<String, String>(); this.body = null; this.hasSessionChanged = false; this.isAuthRequest = isAuthRequest; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return volleyRequestFuture.cancel(mayInterruptIfRunning); } @Override public T get() throws InterruptedException, ExecutionException { return volleyRequestFuture.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return volleyRequestFuture.get(timeout, unit); } @Override public boolean isCancelled() { return volleyRequestFuture.isCancelled(); } @Override public boolean isDone() { return volleyRequestFuture.isDone(); } @Override public VolleyRequest<T> withResultListener(ResultListener<T> resultListener) { if (resultListener != null) { resultListeners.add(resultListener); if (isDone() && result != null) { resultListener.onRequestPerformed(result); } } return this; } @Override public VolleyRequest<T> withErrorListener(ErrorListener errorListener) { if (errorListener != null) { errorListeners.add(errorListener); if (isDone() && error != null) { errorListener.onErrorOccured(error); } } return this; } @Override public VolleyRequest<T> withSessionListener(SessionListener sessionListener) { if (sessionListener != null) { sessionListeners.add(sessionListener); if (isDone() && (isAuthRequest || hasSessionChanged)) { sessionListener.onSessionChanged(Session.accessToken(), Session.refreshToken(), Session.expires()); } } return this; } @Override public byte[] getBody() throws AuthFailureError { return body != null ? body.getBytes() : super.getBody(); } @Override public String getBodyContentType() { return contentType; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers; } @Override protected Map<String, String> getParams() throws AuthFailureError { return params; } @Override public void deliverError(VolleyError error) { // This method is executed on the main thread. Extra care should be // taken on what is done here. if (isAuthError(this.error)) { for (AuthErrorListener<T> authErrorListener : authErrorListeners) { if (authErrorListener.onAuthErrorOccured(this)) { return; } } } else { for (ErrorListener errorListener : errorListeners) { if (errorListener.onErrorOccured(this.error)) { // The callback consumed the event, stop the bubbling. return; } } for (ErrorListener errorListener : GLOBAL_ERROR_LISTENERS) { if (errorListener.onErrorOccured(this.error)) { // The callback consumed the event, stop the bubbling. return; } } } } @Override protected void deliverResponse(T result) { // This method is executed on the main thread. Extra care should be // taken on what is done here. this.result = result; if (isAuthRequest || hasSessionChanged) { deliverSession(); } for (ResultListener<T> resultListener : resultListeners) { if (resultListener.onRequestPerformed(result)) { // The callback consumed the event, stop the bubbling. break; } } } @Override protected VolleyError parseNetworkError(VolleyError volleyError) { // This method is executed on the worker thread. It's "safe" to perform // JSON parsing here. try { String charSet = HttpHeaderParser.parseCharset(volleyError.networkResponse.headers); String errorJson = new String(volleyError.networkResponse.data, charSet); error = PodioError.fromJson(errorJson, volleyError.networkResponse.statusCode, error); } catch (UnsupportedEncodingException e) { // The provided error JSON is provided with an unknown char-set. error = volleyError; } catch (NullPointerException e) { // For some reason the VollyError didn't provide a networkResponse. error = volleyError; } return super.parseNetworkError(volleyError); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { // This method is executed on the worker thread. It's "safe" to perform // JSON parsing here. try { Entry cacheHeaders = HttpHeaderParser.parseCacheHeaders(response); String charSet = HttpHeaderParser.parseCharset(response.headers); String json = new String(response.data, charSet); if (isAuthRequest) { Session.set(json); return Response.success(null, cacheHeaders); } else if (classOfResult == null || classOfResult == Void.class) { return Response.success(null, cacheHeaders); } else { T result = JsonParser.fromJson(json, classOfResult); return Response.success(result, cacheHeaders); } } catch (UnsupportedEncodingException e) { // The provided response JSON is provided with an unknown char-set. return Response.error(new ParseError(e)); } } public ResultListener<T> removeResultListener(ResultListener<T> resultListener) { int index = resultListeners.indexOf(resultListener); return resultListeners.contains(resultListener) ? resultListeners.remove(index) : null; } public ErrorListener removeErrorListener(ErrorListener errorListener) { int index = errorListeners.indexOf(errorListener); return errorListeners.contains(errorListener) ? errorListeners.remove(index) : null; } public SessionListener removeSessionListener(SessionListener sessionListener) { int index = sessionListeners.indexOf(sessionListener); return sessionListeners.contains(sessionListener) ? sessionListeners.remove(index) : null; } public void setSessionChanged(boolean hasChanged) { this.hasSessionChanged = hasChanged; } VolleyRequest<T> withAuthErrorListener(AuthErrorListener<T> authErrorListener) { if (authErrorListener != null) { authErrorListeners.add(authErrorListener); if (isDone() && isAuthError(error)) { authErrorListener.onAuthErrorOccured(this); } } return this; } private void deliverSession() { // This method is executed on the main thread. Extra care should be // taken on what is done here. String accessToken = Session.accessToken(); String refreshToken = Session.refreshToken(); long expires = Session.expires(); for (SessionListener sessionListener : sessionListeners) { if (sessionListener.onSessionChanged(accessToken, refreshToken, expires)) { // The callback consumed the event, stop the bubbling. return; } } for (SessionListener sessionListener : GLOBAL_SESSION_LISTENERS) { if (sessionListener.onSessionChanged(accessToken, refreshToken, expires)) { // The callback consumed the event, stop the bubbling. return; } } } private boolean isAuthError(Throwable error) { if (error instanceof PodioError) { PodioError e = (PodioError) error; return e.getStatusCode() == 401; } else if (error instanceof VolleyError) { VolleyError e = (VolleyError) error; return e.networkResponse != null && e.networkResponse.statusCode == 401; } else { return false; } } }
package edu.northwestern.bioinformatics.studycalendar.testing; import edu.nwu.bioinformatics.commons.testing.DbTestCase; import edu.nwu.bioinformatics.commons.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ColumnMapRowMapper; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; import java.util.List; import java.sql.SQLException; import java.sql.ResultSet; /** * @author Rhett Sutphin */ public abstract class DaoTestCase extends DbTestCase { private static ApplicationContext applicationContext = null; protected final Log log = LogFactory.getLog(getClass()); protected MockHttpServletRequest request = new MockHttpServletRequest(); protected MockHttpServletResponse response = new MockHttpServletResponse(); private boolean shouldFlush = true; protected void setUp() throws Exception { super.setUp(); beginSession(); } protected void tearDown() throws Exception { endSession(); super.tearDown(); } public void runBare() throws Throwable { setUp(); try { runTest(); } catch (Throwable throwable) { shouldFlush = false; throw throwable; } finally { tearDown(); } } private void beginSession() { log.info("-- beginning DaoTestCase interceptor session --"); findOpenSessionInViewInterceptor().preHandle(request, response, null); } private void endSession() { log.info("-- ending DaoTestCase interceptor session --"); OpenSessionInViewInterceptor interceptor = findOpenSessionInViewInterceptor(); if (shouldFlush) { interceptor.postHandle(request, response, null, null); } interceptor.afterCompletion(request, response, null, null); } protected void interruptSession() { endSession(); log.info("-- interrupted DaoTestCase session --"); beginSession(); } private OpenSessionInViewInterceptor findOpenSessionInViewInterceptor() { return (OpenSessionInViewInterceptor) getApplicationContext().getBean("openSessionInViewInterceptor"); } protected DataSource getDataSource() { return (DataSource) getApplicationContext().getBean("dataSource"); } public ApplicationContext getApplicationContext() { synchronized (DaoTestCase.class) { if (applicationContext == null) { applicationContext = ContextTools.createDeployedApplicationContext(); } return applicationContext; } } protected final void dumpResults(String sql) { List<Map<String, String>> rows = new JdbcTemplate(getDataSource()).query( sql, new ColumnMapRowMapper() { protected Object getColumnValue(ResultSet rs, int index) throws SQLException { Object value = super.getColumnValue(rs, index); return value == null ? "null" : value.toString(); } } ); StringBuffer dump = new StringBuffer(sql).append('\n'); if (rows.size() > 0) { Map<String, Integer> colWidths = new HashMap<String, Integer>(); for (String colName : rows.get(0).keySet()) { colWidths.put(colName, colName.length()); for (Map<String, String> row : rows) { colWidths.put(colName, Math.max(colWidths.get(colName), row.get(colName).length())); } } for (String colName : rows.get(0).keySet()) { StringUtils.appendWithPadding(colName, colWidths.get(colName), false, dump); dump.append(" "); } dump.append('\n'); for (Map<String, String> row : rows) { for (String colName : row.keySet()) { StringUtils.appendWithPadding(row.get(colName), colWidths.get(colName), false, dump); dump.append(" | "); } dump.append('\n'); } } dump.append(" ").append(rows.size()).append(" row").append(rows.size() != 1 ? "s\n" : "\n"); System.out.print(dump); } }
package com.kaylerrenslow.armaplugin.lang.sqf.syntax; import com.kaylerrenslow.armaplugin.lang.sqf.syntax.ValueType.Lookup; import org.junit.Test; import static com.kaylerrenslow.armaplugin.lang.sqf.syntax.ValueType.typeEquivalent; import static org.junit.Assert.assertEquals; /** * @author Kayler * @since 11/19/2017 */ public class ValueTypeEquivalenceTest { @Test public void typeEqual_code() throws Exception { assertEquals(true, typeEquivalent(Lookup.CODE, Lookup.CODE)); assertEquals(true, typeEquivalent(Lookup.CODE, new ExpandedValueType(Lookup.CODE))); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.CODE), Lookup.CODE)); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.CODE), new ExpandedValueType(Lookup.CODE))); } @Test public void typeEqual_number() throws Exception { assertEquals(true, typeEquivalent(Lookup.NUMBER, Lookup.NUMBER)); assertEquals(true, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(Lookup.NUMBER))); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.NUMBER), Lookup.NUMBER)); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.NUMBER), new ExpandedValueType(Lookup.NUMBER))); } @Test public void typeEqual_object() throws Exception { assertEquals(true, typeEquivalent(Lookup.OBJECT, Lookup.OBJECT)); assertEquals(true, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(Lookup.OBJECT))); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.OBJECT), Lookup.OBJECT)); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.OBJECT), new ExpandedValueType(Lookup.OBJECT))); } @Test public void typeNotEqual_number() throws Exception { assertEquals(false, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(Lookup.ARRAY))); assertEquals(false, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(Lookup.CONFIG))); assertEquals(false, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(Lookup.CODE))); assertEquals(false, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(Lookup.OBJECT))); } @Test public void typeNotEqual_object() throws Exception { assertEquals(false, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(Lookup.ARRAY))); assertEquals(false, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(Lookup.CONFIG))); assertEquals(false, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(Lookup.CODE))); assertEquals(false, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(Lookup.NUMBER))); } @Test public void typeEqual_array_empty() throws Exception { assertEquals(true, typeEquivalent(Lookup.ARRAY, new ExpandedValueType(true))); assertEquals(true, typeEquivalent(new ExpandedValueType(true), Lookup.ARRAY)); } @Test public void typeNotEqual_array_empty() throws Exception { assertEquals(true, typeEquivalent(Lookup.ARRAY, new ExpandedValueType(Lookup.ARRAY))); assertEquals(true, typeEquivalent(new ExpandedValueType(Lookup.ARRAY), Lookup.ARRAY)); } @Test public void typeEqual_emptyUnboundedArray() throws Exception { //these are true because an unbounded array with no elements provided counts as an array of infinitely many things or nothing assertEquals(true, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(true))); assertEquals(true, typeEquivalent(new ExpandedValueType(true), Lookup.NUMBER)); assertEquals(true, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(true))); assertEquals(true, typeEquivalent(new ExpandedValueType(true), Lookup.OBJECT)); } @Test public void typeNotEqual_emptyBoundedExpandedType() throws Exception { try { typeEquivalent(new ExpandedValueType(false), Lookup.NUMBER); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } try { typeEquivalent(new ExpandedValueType(false), Lookup.OBJECT); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } try { typeEquivalent(Lookup.NUMBER, new ExpandedValueType(false)); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } try { typeEquivalent(Lookup.OBJECT, new ExpandedValueType(false)); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } try { typeEquivalent(new ExpandedValueType(false), new ExpandedValueType(false)); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } try { typeEquivalent(new ExpandedValueType(false), new ExpandedValueType(false)); assertEquals("Expected an exception", true, false); } catch (IllegalArgumentException ignore) { } } @Test public void typeEqual_notEmpty_singleton_unboundedArray() throws Exception { assertEquals(true, typeEquivalent(Lookup.NUMBER, new ExpandedValueType(true, Lookup.NUMBER))); assertEquals(true, typeEquivalent(new ExpandedValueType(true, Lookup.NUMBER), Lookup.NUMBER)); assertEquals(true, typeEquivalent(Lookup.OBJECT, new ExpandedValueType(true))); assertEquals(true, typeEquivalent(new ExpandedValueType(true, Lookup.OBJECT), Lookup.OBJECT)); assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.OBJECT), new ExpandedValueType(true, Lookup.OBJECT) )); assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.CODE), new ExpandedValueType(true, Lookup.CODE) )); } @Test public void typeEqual_notEmpty_notSingleton_unboundedArray() throws Exception { assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT) )); assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT, Lookup.OBJECT) )); assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.CODE, Lookup.OBJECT, Lookup.OBJECT), new ExpandedValueType(true, Lookup.CODE, Lookup.OBJECT) )); } @Test public void typeNotEqual_notEmpty_unboundedArray() throws Exception { assertEquals(false, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER, Lookup.NUMBER), new ExpandedValueType(true, Lookup.OBJECT) )); assertEquals(false, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT) )); assertEquals(false, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER, Lookup.NUMBER), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT) )); assertEquals(false, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT, Lookup.CODE) )); } @Test public void typeEqual_notEmpty_array() throws Exception { assertEquals(true, typeEquivalent( new ExpandedValueType(false, Lookup.NUMBER, Lookup.NUMBER), new ExpandedValueType(true, Lookup.NUMBER) )); assertEquals(true, typeEquivalent( new ExpandedValueType(true, Lookup.NUMBER), new ExpandedValueType(false, Lookup.NUMBER, Lookup.NUMBER) )); assertEquals(true, typeEquivalent( new ExpandedValueType(false, Lookup.NUMBER, Lookup.OBJECT), new ExpandedValueType(true, Lookup.NUMBER, Lookup.OBJECT) )); } }
package org.search.nibrs.xml.exporter; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import org.search.nibrs.common.NIBRSError; import org.search.nibrs.model.Arrestee; import org.search.nibrs.model.GroupAIncidentReport; import org.search.nibrs.model.GroupBIncidentReport; import org.search.nibrs.model.NIBRSAge; import org.search.nibrs.model.NIBRSSubmission; import org.search.nibrs.model.Offender; import org.search.nibrs.model.Offense; import org.search.nibrs.model.Person; import org.search.nibrs.model.Property; import org.search.nibrs.model.Report; import org.search.nibrs.model.Victim; import org.search.nibrs.model.ZeroReport; import org.search.nibrs.xml.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class TestXMLExporter { @SuppressWarnings("unused") private static final Logger LOG = LogManager.getLogger(TestXMLExporter.class); @Test public void testDocumentConversion() throws Exception { NIBRSSubmission report = new NIBRSSubmission(); report.addReport(buildBaseGroupAIncident()); List<NIBRSError> errorList = new ArrayList<NIBRSError>(); Document d = new XMLExporter().convertNIBRSSubmissionToDocument(report, errorList); assertTrue(errorList.isEmpty()); //XmlUtils.printNode(d, System.out); } @Test public void testStreamConversion() throws Exception { NIBRSSubmission report = new NIBRSSubmission(); report.addReport(buildBaseGroupAIncident()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); List<NIBRSError> errorList = new ArrayList<NIBRSError>(); new XMLExporter().convertNIBRSSubmissionToStream(report, baos, errorList); assertTrue(errorList.isEmpty()); String xml = baos.toString(); Document d = XmlUtils.toDocument(xml); //XmlUtils.printNode(d); } @Test public void testGroupBExport() throws Exception { NIBRSSubmission report = new NIBRSSubmission(); GroupBIncidentReport baseIncident = buildBaseGroupBIncident(); report.addReport(baseIncident); List<NIBRSError> errorList = new ArrayList<NIBRSError>(); Document d = new XMLExporter().convertNIBRSSubmissionToDocument(report, errorList); //XmlUtils.printNode(d); assertEquals(baseIncident.getYearOfTape() + "-" + new DecimalFormat("00").format(baseIncident.getMonthOfTape()), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportDate/nc:YearMonthDate")); assertEquals(baseIncident.getOri(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportingAgency/j:OrganizationAugmentation/j:OrganizationORIIdentification/nc:IdentificationID")); assertEquals(baseIncident.getReportActionType(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportActionCategoryCode").charAt(0)); assertEquals("GROUP B ARREST REPORT", XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:NIBRSReportCategoryCode")); assertArrestees(d, baseIncident, 1); } private void assertArrestees(Document d, Report baseIncident, int expectedArresteeCount) throws Exception { List<Arrestee> arresteeList = baseIncident.getArrestees(); assertEquals(expectedArresteeCount, arresteeList.size()); NodeList arresteeNodes = XmlUtils.xPathNodeListSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Arrestee"); assertEquals(expectedArresteeCount, arresteeNodes.getLength()); for (int i=0; i < arresteeNodes.getLength();i++) { Node arresteeNode = arresteeNodes.item(i); Arrestee arrestee = arresteeList.get(i); assertEquals(arrestee.getArresteeSequenceNumber(), Integer.valueOf(XmlUtils.xPathStringSearch(arresteeNode, "j:ArrestSequenceID"))); String personId = XmlUtils.xPathStringSearch(arresteeNode, "nc:RoleOfPerson/@s:ref"); Node personNode = XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Person[@s:id='" + personId + "']"); assertEquals(arrestee.getSex(), XmlUtils.xPathStringSearch(personNode, "j:PersonSexCode")); assertEquals(arrestee.getRace(), XmlUtils.xPathStringSearch(personNode, "j:PersonRaceNDExCode")); assertPersonAge(arrestee.getAge(), personNode); Node assnNode = XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:ArrestSubjectAssociation[j:Subject/@s:ref='" + personId + "']"); assertNotNull(assnNode); String arrestId = XmlUtils.xPathStringSearch(assnNode, "nc:Activity/@s:ref"); Node arrestNode = XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Arrest[@s:id='" + arrestId + "']"); assertEquals(arrestee.getArrestTransactionNumber(), XmlUtils.xPathStringSearch(arrestNode, "nc:ActivityIdentification/nc:IdentificationID")); assertEquals(arrestee.getUcrArrestOffenseCode(), XmlUtils.xPathStringSearch(arrestNode, "j:ArrestCharge/nibrs:ChargeUCRCode")); assertEquals(arrestee.getTypeOfArrest(), XmlUtils.xPathStringSearch(arrestNode, "j:ArrestCategoryCode")); } } @Test public void testZeroReportExport() throws Exception { NIBRSSubmission report = new NIBRSSubmission(); ZeroReport baseIncident = buildZeroReport(); report.addReport(baseIncident); List<NIBRSError> errorList = new ArrayList<NIBRSError>(); Document d = new XMLExporter().convertNIBRSSubmissionToDocument(report, errorList); //XmlUtils.printNode(d); assertEquals(baseIncident.getYearOfTape() + "-" + new DecimalFormat("00").format(baseIncident.getMonthOfTape()), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportDate/nc:YearMonthDate")); assertEquals(baseIncident.getOri(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportingAgency/j:OrganizationAugmentation/j:OrganizationORIIdentification/nc:IdentificationID")); assertEquals(baseIncident.getReportActionType(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportActionCategoryCode").charAt(0)); assertEquals("ZERO REPORT", XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:NIBRSReportCategoryCode")); } @Test public void testGroupAExport() throws Exception { NIBRSSubmission report = new NIBRSSubmission(); GroupAIncidentReport baseIncident = buildBaseGroupAIncident(); report.addReport(baseIncident); List<NIBRSError> errorList = new ArrayList<NIBRSError>(); Document d = new XMLExporter().convertNIBRSSubmissionToDocument(report, errorList); assertEquals(baseIncident.getYearOfTape() + "-" + new DecimalFormat("00").format(baseIncident.getMonthOfTape()), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportDate/nc:YearMonthDate")); assertEquals(baseIncident.getOri(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportingAgency/j:OrganizationAugmentation/j:OrganizationORIIdentification/nc:IdentificationID")); assertEquals(baseIncident.getReportActionType(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:ReportActionCategoryCode").charAt(0)); assertEquals("GROUP A INCIDENT REPORT", XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nibrs:ReportHeader/nibrs:NIBRSReportCategoryCode")); assertEquals(baseIncident.getIncidentNumber(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Incident/nc:ActivityIdentification/nc:IdentificationID")); assertEquals(baseIncident.getExceptionalClearanceCode(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Incident/j:IncidentAugmentation/j:IncidentExceptionalClearanceCode")); assertEquals(baseIncident.getReportDateIndicator(), new Boolean(XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Incident/cjis:IncidentAugmentation/cjis:IncidentReportDateIndicator"))); assertEquals(baseIncident.getCargoTheftIndicator(), new Boolean(XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Incident/cjis:IncidentAugmentation/j:OffenseCargoTheftIndicator"))); for (Offense o : baseIncident.getOffenses()) { String ucrCode = o.getUcrOffenseCode(); Element offenseElement = (Element) XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Offense[@s:id='Offense-" + ucrCode + "']"); assertNotNull(offenseElement); assertEquals(ucrCode, XmlUtils.xPathStringSearch(offenseElement, "nibrs:OffenseUCRCode")); for (int i=0; i < o.getPopulatedBiasMotivationCount(); i++) { assertNotNull(XmlUtils.xPathNodeSearch(offenseElement, "j:OffenseFactorBiasMotivationCode[text()='" + XMLExporter.BIAS_MAP.get(o.getBiasMotivation(i)) + "']")); } for (int i=0; i < o.getPopulatedOffendersSuspectedOfUsingCount(); i++) { assertNotNull(XmlUtils.xPathNodeSearch(offenseElement, "j:OffenseFactor/j:OffenseFactorCode[text()='" + o.getOffendersSuspectedOfUsing(i) + "']")); } for (int i=0; i < o.getPopulatedTypeOfWeaponForceInvolvedCount(); i++) { assertNotNull(XmlUtils.xPathNodeSearch(offenseElement, "j:OffenseForce/j:ForceCategoryCode[text()='" + o.getTypeOfWeaponForceInvolved(i) + "']")); } assertEquals(o.getLocationType(), XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report/nc:Location[@s:id='Location-" + ucrCode + "']/j:LocationCategoryCode")); assertNotNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report/j:OffenseLocationAssociation[nc:Location/@s:ref='Location-" + ucrCode + "']")); assertEquals(o.getOffenseAttemptedIndicator(), new Boolean(XmlUtils.xPathStringSearch(offenseElement, "j:OffenseAttemptedIndicator"))); } for (Property p : baseIncident.getProperties()) { String typePropertyLoss = p.getTypeOfPropertyLoss(); for (int i = 0; i < p.getPopulatedPropertyDescriptionCount(); i++) { String propertyDescription = p.getPropertyDescription(i); if (!"10".equals(propertyDescription)) { Element itemElement = (Element) XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Item[j:ItemCategoryNIBRSPropertyCategoryCode='" + propertyDescription + "' and nc:ItemStatus/cjis:ItemStatusCode='" + XMLExporter.ITEM_STATUS_MAP.get(typePropertyLoss) + "']"); assertNotNull(itemElement); assertEquals(p.getValueOfProperty(i), new Integer(XmlUtils.xPathStringSearch(itemElement, "nc:ItemValue/nc:ItemValueAmount/nc:Amount"))); Integer recoveredMotorVehicles = p.getNumberOfRecoveredMotorVehicles(); Integer stolenMotorVehicles = p.getNumberOfStolenMotorVehicles(); if (recoveredMotorVehicles != null || stolenMotorVehicles != null) { assertNotNull(XmlUtils.xPathNodeSearch(itemElement, "nc:ItemQuantity[text()='" + (recoveredMotorVehicles != null ? recoveredMotorVehicles : stolenMotorVehicles) + "']")); } else { assertNull(XmlUtils.xPathNodeSearch(itemElement, "nc:ItemQuantity")); } } } for (int i=0; i < p.getPopulatedSuspectedDrugTypeCount(); i++) { String drugType = p.getSuspectedDrugType(i); Double drugQuantity = p.getEstimatedDrugQuantity(i); String measurement = p.getTypeDrugMeasurement(i); assertNotNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Substance[" + "j:DrugCategoryCode='" + drugType + "' and " + "nc:SubstanceQuantityMeasure/nc:MeasureDecimalValue='" + drugQuantity + "' and " + "nc:SubstanceQuantityMeasure/j:SubstanceUnitCode='" + measurement + "']")); } } for (Offender o : baseIncident.getOffenders()) { Integer offenderSequenceNumber = o.getOffenderSequenceNumber(); Element offenderPersonElement = (Element) XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Person[@s:id='Offender-" + offenderSequenceNumber + "']"); assertNotNull(offenderPersonElement); assertNotNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Subject[nc:RoleOfPerson/@s:ref='Offender-" + offenderSequenceNumber + "' and " + "j:OffenderSequenceNumberText/text()='" + offenderSequenceNumber + "']")); if (o.getReportedUnknown()) { assertEquals(0, offenderPersonElement.getChildNodes().getLength()); } else { assertDemographics(o, offenderPersonElement); } } for (Victim v : baseIncident.getVictims()) { Integer victimSequenceNumber = v.getVictimSequenceNumber(); assertEquals(XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Victim[nc:RoleOfPerson/@s:ref='Victim-" + victimSequenceNumber + "']/j:VictimCategoryCode"), v.getTypeOfVictim()); if (v.isPerson()) { Element victimPersonElement = (Element) XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Person[@s:id='Victim-" + victimSequenceNumber + "']"); assertNotNull(victimPersonElement); assertNotNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Victim[nc:RoleOfPerson/@s:ref='Victim-" + victimSequenceNumber + "' and " + "j:VictimSequenceNumberText/text()='" + victimSequenceNumber + "']")); assertDemographics(v, victimPersonElement); for (int i=0; i < v.getPopulatedAggravatedAssaultHomicideCircumstancesCount(); i++) { String circ = v.getAggravatedAssaultHomicideCircumstances(i); assertEquals(circ, XmlUtils.xPathStringSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:Victim[j:VictimSequenceNumberText='" + victimSequenceNumber + "']/j:VictimAggravatedAssaultHomicideFactorCode")); } for (int i=0; i < v.getPopulatedTypeOfInjuryCount(); i++) { String injury = v.getTypeOfInjury(i); assertEquals(injury, XmlUtils.xPathStringSearch(victimPersonElement, "nc:PersonInjury/j:InjuryCategoryCode")); } if (v.isLawEnforcementOfficer() && baseIncident.includesLeoka()) { Element enforcementOfficialElement = (Element) XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:EnforcementOfficial/nc:RoleOfPerson[@s:ref='Victim-" + victimSequenceNumber + "']"); assertNotNull(enforcementOfficialElement); assertEquals(v.getOfficerAssignmentType(), XmlUtils.xPathStringSearch(enforcementOfficialElement, "j:EnforcementOfficialAssignmentCategoryCode")); assertEquals(v.getTypeOfOfficerActivityCircumstance(), XmlUtils.xPathStringSearch(enforcementOfficialElement, "j:EnforcementOfficialActivityCategoryCode")); assertEquals(v.getOfficerOtherJurisdictionORI(), XmlUtils.xPathStringSearch(enforcementOfficialElement, "j:EnforcementOfficialUnit/j:OrganizationAugmentation/j:OrganizationORIIdentification/nc:IdentificationID")); } } else { assertNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/nc:Person[@s:id='Victim-" + victimSequenceNumber + "']")); } for (int i=0; i < v.getPopulatedUcrOffenseCodeConnectionCount(); i++) { String offenseCode = v.getUcrOffenseCodeConnection(i); assertNotNull(XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:OffenseVictimAssociation[j:Offense/@s:ref='Offense-" + offenseCode + "' and j:Victim/@s:ref='Victim-" + victimSequenceNumber + "']")); } for (int i=0; i < v.getPopulatedOffenderNumberRelatedCount(); i++) { Integer offender = v.getOffenderNumberRelated(i); Node assnNode = XmlUtils.xPathNodeSearch(d, "/nibrs:Submission/nibrs:Report[1]/j:SubjectVictimAssociation[j:Subject/@s:ref='Offender-" + offender + "' and j:Victim/@s:ref='Victim-" + victimSequenceNumber + "']"); assertNotNull(assnNode); assertEquals(XMLExporter.RELATIONSHIP_MAP.get(v.getVictimOffenderRelationship(i)), XmlUtils.xPathStringSearch(assnNode, "j:VictimToSubjectRelationshipCode")); } } assertArrestees(d, baseIncident, baseIncident.getArresteeCount()); } private void assertDemographics(Person person, Element personElement) throws Exception { String ethnicity = person.getEthnicity(); if (ethnicity == null) { assertNull(XmlUtils.xPathNodeSearch(personElement, "nc:PersonEthnicityCode")); } else { assertEquals(ethnicity, XmlUtils.xPathStringSearch(personElement, "nc:PersonEthnicityCode")); } assertEquals(person.getRace(), XmlUtils.xPathStringSearch(personElement, "j:PersonRaceNDExCode")); assertEquals(person.getSex(), XmlUtils.xPathStringSearch(personElement, "j:PersonSexCode")); assertPersonAge(person.getAge(), personElement); } private void assertPersonAge(NIBRSAge age, Node personElement) throws Exception { if (age.isAgeRange()) { assertEquals(age.getAgeMin(), new Integer(XmlUtils.xPathStringSearch(personElement, "nc:PersonAgeMeasure/nc:MeasureRangeValue/nc:RangeMinimumIntegerValue"))); assertEquals(age.getAgeMax(), new Integer(XmlUtils.xPathStringSearch(personElement, "nc:PersonAgeMeasure/nc:MeasureRangeValue/nc:RangeMaximumIntegerValue"))); } else if (age.isNonNumeric()) { assertEquals(age.getNonNumericAge(), XmlUtils.xPathStringSearch(personElement, "j:PersonAugmentation/nibrs:PersonAgeCode")); } else { assertEquals(age.getAgeMin(), new Integer(XmlUtils.xPathStringSearch(personElement, "nc:PersonAgeMeasure/nc:MeasureIntegerValue"))); } } private ZeroReport buildZeroReport() { ZeroReport incident = new ZeroReport(); incident.setYearOfTape(2016); incident.setMonthOfTape(5); incident.setOri("WA1234567"); incident.setReportActionType('I'); incident.setAdminSegmentLevel('0'); return incident; } private GroupBIncidentReport buildBaseGroupBIncident() throws ParseException { GroupBIncidentReport incident = new GroupBIncidentReport(); incident.setYearOfTape(2016); incident.setMonthOfTape(5); incident.setOri("WA123456789"); incident.setReportActionType('I'); incident.setAdminSegmentLevel('7'); Arrestee arrestee = new Arrestee(); incident.addArrestee(arrestee); arrestee.setArresteeSequenceNumber(1); arrestee.setAgeString("22"); arrestee.setRace("W"); arrestee.setSex("M"); arrestee.setArrestTransactionNumber("12345"); arrestee.setArrestDate(XMLExporter.DATE_FORMAT.parse("2016-05-16")); arrestee.setUcrArrestOffenseCode("90A"); arrestee.setTypeOfArrest("O"); return incident; } private GroupAIncidentReport buildBaseGroupAIncident() throws ParseException { GroupAIncidentReport incident = new GroupAIncidentReport(); incident.setYearOfTape(2016); incident.setMonthOfTape(5); incident.setOri("WA123456789"); incident.setIncidentNumber("54236732"); incident.setIncidentDate(XMLExporter.DATETIME_FORMAT.parse("2016-05-12T10:07:46.342-0500")); incident.setExceptionalClearanceCode("N"); incident.setReportActionType('I'); incident.setCargoTheftIndicator(false); Offense o = new Offense(); incident.addOffense(o); o.setUcrOffenseCode("64A"); o.setBiasMotivation(0, "88"); o.setOffendersSuspectedOfUsing(0, "N"); o.setTypeOfWeaponForceInvolved(0, "11A"); o.setOffenseAttemptedCompleted("C"); o.setLocationType("01"); o = new Offense(); incident.addOffense(o); o.setUcrOffenseCode("220"); o.setNumberOfPremisesEntered(1); o.setMethodOfEntry("F"); o.setBiasMotivation(0, "21"); o.setBiasMotivation(1, "22"); o.setOffendersSuspectedOfUsing(0, "N"); o.setOffenseAttemptedCompleted("A"); o.setLocationType("14"); o = new Offense(); incident.addOffense(o); o.setUcrOffenseCode("720"); o.setBiasMotivation(0, "88"); o.setOffendersSuspectedOfUsing(0, "N"); o.setOffenseAttemptedCompleted("C"); o.setTypeOfCriminalActivity(0, "A"); o.setLocationType("20"); o = new Offense(); incident.addOffense(o); o.setUcrOffenseCode("13A"); o.setOffenseAttemptedCompleted("C"); o.setLocationType("15"); Property p = new Property(); incident.addProperty(p); p.setTypeOfPropertyLoss("6"); // seized 24 oz of LSD p.setPropertyDescription(0, "10"); p.setEstimatedDrugQuantity(0, 24.0); p.setTypeDrugMeasurement(0, "OZ"); p.setSuspectedDrugType(0, "I"); p.setValueOfProperty(0, 500); // also seized some currency p.setPropertyDescription(1, "20"); p.setValueOfProperty(1, 2000); p = new Property(); incident.addProperty(p); // stole jewelry p.setTypeOfPropertyLoss("7"); p.setPropertyDescription(0, "17"); p.setValueOfProperty(0, 1000); p = new Property(); incident.addProperty(p); // recovered some jewelry p.setTypeOfPropertyLoss("5"); p.setPropertyDescription(0, "17"); p.setValueOfProperty(0, 200); p.setDateRecovered(0, XMLExporter.DATE_FORMAT.parse("2016-05-16")); p = new Property(); incident.addProperty(p); // stole car p.setTypeOfPropertyLoss("7"); p.setPropertyDescription(0, "03"); p.setValueOfProperty(0, 5000); p.setNumberOfStolenMotorVehicles(1); Victim v = new Victim(); incident.addVictim(v); v.setTypeOfVictim("I"); v.setTypeOfInjury(0, "N"); v.setVictimSequenceNumber(1); v.setAgeString("2022"); v.setEthnicity("N"); v.setResidentStatusOfVictim("R"); v.setSex("F"); v.setRace("B"); v.setUcrOffenseCodeConnection(0, "64A"); v.setUcrOffenseCodeConnection(1, "13A"); v.setOffenderNumberRelated(0, 1); v.setVictimOffenderRelationship(0, "ER"); v = new Victim(); incident.addVictim(v); v.setTypeOfVictim("I"); v.setTypeOfInjury(0, "N"); v.setVictimSequenceNumber(2); v.setAgeString("BB"); v.setEthnicity("N"); v.setResidentStatusOfVictim("R"); v.setSex("F"); v.setRace("B"); v.setUcrOffenseCodeConnection(0, "13A"); v.setOffenderNumberRelated(0, 1); v.setVictimOffenderRelationship(0, "FR"); v.setAggravatedAssaultHomicideCircumstances(0, "32"); v = new Victim(); incident.addVictim(v); v.setVictimSequenceNumber(3); v.setTypeOfVictim("B"); v.setUcrOffenseCodeConnection(0, "220"); v.setOffenderNumberRelated(0, 1); v.setVictimOffenderRelationship(0, "RU"); v = new Victim(); incident.addVictim(v); v.setVictimSequenceNumber(4); v.setTypeOfVictim("L"); v.setTypeOfInjury(0, "L"); v.setAgeString("30"); v.setEthnicity("N"); v.setResidentStatusOfVictim("R"); v.setSex("F"); v.setRace("B"); v.setOfficerAssignmentType("F"); v.setTypeOfOfficerActivityCircumstance("04"); v.setOfficerOtherJurisdictionORI("WA987654321"); v.setUcrOffenseCodeConnection(0, "13A"); v.setOffenderNumberRelated(0, 1); v.setVictimOffenderRelationship(0, "ST"); Offender offender = new Offender(); incident.addOffender(offender); offender.setOffenderSequenceNumber(1); offender.setAgeString("22"); offender.setRace("W"); offender.setSex("M"); Arrestee arrestee = new Arrestee(); incident.addArrestee(arrestee); arrestee.setArresteeSequenceNumber(1); arrestee.setAgeString("22"); arrestee.setRace("W"); arrestee.setSex("M"); arrestee.setArrestTransactionNumber("12345"); arrestee.setArrestDate(XMLExporter.DATE_FORMAT.parse("2016-05-16")); arrestee.setUcrArrestOffenseCode("64A"); arrestee.setTypeOfArrest("O"); arrestee.setMultipleArresteeSegmentsIndicator("N"); offender = new Offender(); incident.addOffender(offender); offender.setOffenderSequenceNumber(2); offender.setAgeString("32"); offender.setRace("B"); offender.setSex("F"); offender.setEthnicity("N"); offender = new Offender(); incident.addOffender(offender); offender.setOffenderSequenceNumber(0); return incident; } }
package org.truelicense.api; public interface LicenseApplicationContext { LicenseManagementContextBuilder context(); }
package MWC.Utilities.ReaderWriter.json; import java.io.IOException; import java.io.StringWriter; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Vector; import junit.framework.TestCase; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser.Feature; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import MWC.GenericData.HiResDate; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldLocation; import MWC.TacticalData.Fix; import MWC.TacticalData.Track; public class GNDDocHandler { private static JsonNode timeBoundsFor(Track track, ObjectMapper mapper) { Date first = track.getStartDTG().getDate(); Date last = track.getEndDTG().getDate(); ObjectNode times = mapper.createObjectNode(); times.put("start", timeFor(first)); times.put("end", timeFor(last)); return times; } private static WorldArea geoBoundsFor(Track track) { WorldArea bounds = null; Enumeration<Fix> fixes = track.getFixes(); while (fixes.hasMoreElements()) { Fix fix = fixes.nextElement(); if (bounds == null) bounds = new WorldArea(fix.getLocation(), fix.getLocation()); else bounds.extend(fix.getLocation()); } return bounds; } private static String timeFor(Date date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); String theTime = df.format(date); theTime = theTime.replace("+0000", "Z"); return theTime; } private static JsonNode locationFor(WorldLocation loc, ObjectMapper mapper) { ArrayNode locs = mapper.createArrayNode(); locs.add(loc.getLat()); locs.add(loc.getLong()); return locs; } public ObjectNode toJson(String name, Track track, String platform, String platformType, String sensor, String sensorType, String trial) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); ObjectNode root = mapper.createObjectNode(); ObjectNode metadata = mapper.createObjectNode(); metadata.put("name", name); metadata.put("platform", platform); metadata.put("platform_type", platformType); metadata.put("sensor", sensor); metadata.put("sensor_type", sensorType); metadata.put("trial", trial); metadata.put("type", "track"); ArrayNode types = mapper.createArrayNode(); types.add("lat"); types.add("lon"); types.add("time"); types.add("elevation"); types.add("course"); types.add("speed"); metadata.put("data_type", types); // now the location bounds WorldArea theArea = geoBoundsFor(track); ObjectNode gBounds = mapper.createObjectNode(); gBounds.put("tl", locationFor(theArea.getTopLeft(), mapper)); gBounds.put("br", locationFor(theArea.getBottomRight(), mapper)); metadata.put("geo_bounds", gBounds); // and the time bounds metadata.put("time_bounds", timeBoundsFor(track, mapper)); root.put("metadata", metadata); // now the data arrays ArrayNode latArr = mapper.createArrayNode(); ArrayNode longArr = mapper.createArrayNode(); ArrayNode timeArr = mapper.createArrayNode(); ArrayNode eleArr = mapper.createArrayNode(); ArrayNode crseArr = mapper.createArrayNode(); ArrayNode speedArr = mapper.createArrayNode(); Enumeration<Fix> fixes = track.getFixes(); while (fixes.hasMoreElements()) { Fix fix = fixes.nextElement(); latArr.add(fix.getLocation().getLat()); longArr.add(fix.getLocation().getLong()); timeArr.add(timeFor(fix.getTime().getDate())); eleArr.add(-fix.getLocation().getDepth()); crseArr.add(fix.getCourse()); // get m/s double yps = fix.getSpeed(); double kts = MWC.Algorithms.Conversions.Yps2Kts(yps); double m_sec = MWC.Algorithms.Conversions.Kts2Mps(kts); speedArr.add(m_sec); } root.put("lat", latArr); root.put("lon", longArr); root.put("time", timeArr); root.put("elevation", eleArr); root.put("course", crseArr); root.put("speed", speedArr); return root; } public static String asString(JsonNode root) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, root); return writer.toString(); } public final static class GNDDocument { private String _name; private Track _track; @SuppressWarnings("unused") private String _platform; @SuppressWarnings("unused") private String _platformType; @SuppressWarnings("unused") private String _sensor; @SuppressWarnings("unused") private String _sensorType; @SuppressWarnings("unused") private String _trial; public GNDDocument(String name, Track track, String platform, String platformType, String sensor, String sensorType, String trial) { _name = name; _track = track; _platform = platform; _platformType = platformType; _sensor = sensor; _sensorType = sensorType; _trial = trial; } /** * construct ourselves from the object * * @param content * @throws IOException * @throws JsonMappingException * @throws JsonParseException * @throws ParseException */ @SuppressWarnings("unchecked") public GNDDocument(String content) throws JsonParseException, JsonMappingException, IOException, ParseException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> root = mapper.readValue(content, Map.class); LinkedHashMap<String, Object> meta = (LinkedHashMap<String, Object>) root .get("metadata"); _name = (String) meta.get("name"); _platform = (String) meta.get("platform"); _platformType = (String) meta.get("platform_type"); _sensor = (String) meta.get("sensor"); _sensorType = (String) meta.get("sensor_type"); _trial = (String) meta.get("trial"); // ok, and populate the tracks ArrayList<String> dTypes = (ArrayList<String>) meta.get("data_type"); if (dTypes.contains("lat") && dTypes.contains("lon") && dTypes.contains("time")) { // ok, go for it. ArrayList<Double> latArr = (ArrayList<Double>) root.get("lat"); ArrayList<Double> lonArr = (ArrayList<Double>) root.get("lon"); ArrayList<String> timeArr = (ArrayList<String>) root.get("time"); ArrayList<Double> eleArr = null; ArrayList<Double> crseArr = null; ArrayList<Double> spdArr = null; if (dTypes.contains("elevation")) eleArr = (ArrayList<Double>) root.get("elevation"); if (dTypes.contains("course")) crseArr = (ArrayList<Double>) root.get("course"); if (dTypes.contains("speed")) spdArr = (ArrayList<Double>) root.get("speed"); _track = new Track(); _track.setName(_name); int ctr = 0; for (Iterator<String> iterator = timeArr.iterator(); iterator.hasNext();) { String string = iterator.next(); double lat = latArr.get(ctr); double lon = lonArr.get(ctr); double depth = 0, course = 0, speed = 0; if (eleArr != null) depth = -eleArr.get(ctr); if (crseArr != null) course = crseArr.get(ctr); if (spdArr != null) speed = spdArr.get(ctr); Date hd = timeFrom(string); HiResDate dt = new HiResDate(hd); WorldLocation theLoc = new WorldLocation(lat, lon, depth); Fix thisF = new Fix(dt, theLoc, course, speed); _track.addFix(thisF); ctr++; } } } public Track getTrack() { return _track; } private Date timeFrom(String str) throws ParseException { String format = "yyyy-MM-dd HH:mm:ss"; if (str.indexOf("T") != -1) { str = str.replace("T", " "); } if (str.indexOf("Z") != -1) { str = str.replace("Z", ""); } return new SimpleDateFormat(format).parse(str); } public String getName() { return _name; } } public static class TestJSON extends TestCase { public static Track getTestTrack(String theName) { double course = 135; double speed = 5; // put in some fixes Vector<Fix> fixes = new Vector<Fix>(); for (int i = 0; i < 3; i++) { @SuppressWarnings("deprecation") HiResDate time = new HiResDate(new Date(112, 6, 6, 12, 5, i * 25)); WorldLocation loc = new WorldLocation(4d + i / 100d, 5d + i / 100d, 0); course += (-3 + Math.random() * 5.5d); speed += (-1 + Math.random() * 2d); Fix newF = new Fix(time, loc, course, speed); fixes.add(newF); } Track track = new Track(fixes); track.setName(theName); return track; } public void testToGNDDoc() throws IOException { // ok, create a bit of a track Track track = getTestTrack("some-name"); assertNotNull("track not found", track); GNDDocument doc = new GNDDocument("NAME", track, "PLATFORM", "P_TYPE", "SENS", "S_TYPE", "TRIAL"); // and check the results assertNotNull("No output received", doc); // and check the contents ObjectNode root = new GNDDocHandler().toJson("NAME", track, "PLATFORM", "P_TYPE", "SENS", "S_TYPE", "TRIAL"); assertNotNull("found root", root); ObjectNode metadata = (ObjectNode) root.get("metadata"); assertNotNull("metadata not found", metadata); assertEquals("name wrong", "NAME", metadata.get("name").asText()); assertEquals("platform wrong", "PLATFORM", metadata.get("platform") .asText()); assertEquals("platform type wrong", "P_TYPE", metadata.get("platform_type").asText()); assertEquals("sensor wrong", "SENS", metadata.get("sensor").asText()); assertEquals("sensor type wrong", "S_TYPE", metadata.get("sensor_type") .asText()); assertEquals("trial wrong", "TRIAL", metadata.get("trial").asText()); // assertEquals("data types wrong", // "[\"lat\",\"long\",\"time\",\"elevation\"", metadata.get("data_type")); assertNotNull("geo bounds wrong", metadata.get("geo_bounds")); assertNotNull("time bounds wrong", metadata.get("time_bounds")); } } }
package net.jueb.util4j.net.nettyImpl.client; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.util.internal.logging.InternalLogger; import net.jueb.util4j.net.nettyImpl.NetLogFactory; import net.jueb.util4j.net.nettyImpl.OptionConfiger; import net.jueb.util4j.net.nettyImpl.config.BootstrapConfiger; import net.jueb.util4j.net.nettyImpl.handler.LoggerHandler; import net.jueb.util4j.thread.NamedThreadFactory; /** * * @author Administrator */ public class NettyClientConfig { protected final InternalLogger log = NetLogFactory.getLogger(getClass()); protected final Class<? extends SocketChannel> channelClass; protected final EventLoopGroup ioWorkers; protected LogLevel level; protected long connectTimeOutMills=TimeUnit.SECONDS.toMillis(3); public NettyClientConfig(Class<? extends SocketChannel> channelClass,EventLoopGroup ioWorkers) { this.channelClass = channelClass; this.ioWorkers = ioWorkers; } public NettyClientConfig() { this.channelClass = NioSocketChannel.class; this.ioWorkers = new NioEventLoopGroup(0,new NamedThreadFactory("ClientConfig-ioWorkers",true)); } public NettyClientConfig(int ioThreads) { if(ioThreads<0) { ioThreads=0; } this.channelClass = NioSocketChannel.class; this.ioWorkers = new NioEventLoopGroup(ioThreads,new NamedThreadFactory("ClientConfig-ioWorkers",true)); } public Class<? extends SocketChannel> getChannelClass() { return channelClass; } public EventLoopGroup getIoWorkers() { return ioWorkers; } public LogLevel getLevel() { return level; } public void setLevel(LogLevel level) { this.level = level; } public long getConnectTimeOutMills() { return connectTimeOutMills; } public void setConnectTimeOutMills(long connectTimeOutMills) { this.connectTimeOutMills = connectTimeOutMills; } public void destory() { if(ioWorkers!=null) { ioWorkers.shutdownGracefully(); } } protected final Bootstrap booter=new Bootstrap(); Bootstrap getBooter() { return booter; } protected void booterInit() { booter.group(ioWorkers); booter.channel(channelClass); initBooterOptions(new BootstrapConfiger(booter)); initBooterOptions(optionConfig()); } @Deprecated protected void initBooterOptions(BootstrapConfiger configer) { configer.option(ChannelOption.SO_KEEPALIVE, true); configer.option(ChannelOption.TCP_NODELAY, true); } protected void initBooterOptions(OptionConfiger configer) { configer.option(ChannelOption.SO_KEEPALIVE, true); configer.option(ChannelOption.TCP_NODELAY, true); } public OptionConfiger optionConfig() { return new OptionConfiger() { @Override public <T> OptionConfiger option(ChannelOption<T> option, T value) { booter.option(option, value); return this; } }; } /** * initremove,booterhandler * @param address * @param init * @return */ protected ChannelFuture doBooterConnect(InetSocketAddress address,final ChannelHandler init) { ChannelFuture cf; synchronized (booter) { if(booter.config().group()==null) { booterInit(); } final CountDownLatch latch=new CountDownLatch(1); ChannelHandler handler=new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { LogLevel level=getLevel(); if(level!=null) { ch.pipeline().addLast(new LoggerHandler(level)); } ch.pipeline().addLast(init); } }; /* * initChannelInitializer2channelRegistered * LoggerHandler2channelRegistered,initChannelInitializer ChannelInboundHandlerAdapter handler=new ChannelInboundHandlerAdapter(){ @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast(new LoggerHandler(getLevel())); ctx.pipeline().addLast(init); ctx.pipeline().remove(this); super.channelRegistered(ctx); } }; */ booter.handler(handler); cf=booter.connect(address); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.trace("connect operationComplete:isDone="+future.isDone()+",isSuccess="+future.isSuccess()); if(future.isDone() && future.isSuccess()) { latch.countDown(); } } }); try { latch.await(getConnectTimeOutMills(),TimeUnit.MILLISECONDS); } catch (Exception e) { log.error(e.getMessage(),e); } } return cf; } }
package org.project.openbaton.nfvo.vnfm_reg; import org.project.openbaton.catalogue.nfvo.*; import org.project.openbaton.clients.exceptions.VimDriverException; import org.project.openbaton.catalogue.mano.common.Event; import org.project.openbaton.catalogue.mano.common.LifecycleEvent; import org.project.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit; import org.project.openbaton.catalogue.mano.record.NetworkServiceRecord; import org.project.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord; import org.project.openbaton.nfvo.exceptions.NotFoundException; import org.project.openbaton.nfvo.exceptions.VimException; import org.project.openbaton.nfvo.core.interfaces.ResourceManagement; import org.project.openbaton.nfvo.core.interfaces.VNFLifecycleOperationGranting; import org.project.openbaton.nfvo.repositories_interfaces.GenericRepository; import org.project.openbaton.vnfm.interfaces.sender.VnfmSender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import javax.jms.JMSException; import javax.naming.NamingException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; @Service @Scope public class VnfmManager implements org.project.openbaton.vnfm.interfaces.manager.VnfmManager, ApplicationEventPublisherAware { protected Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private ConfigurableApplicationContext context; @Autowired @Qualifier("vnfmRegister") private VnfmRegister vnfmRegister; private ApplicationEventPublisher publisher; @Autowired private ResourceManagement resourceManagement; @Autowired private VNFLifecycleOperationGranting lifecycleOperationGranting; @Autowired @Qualifier("VNFRRepository") private GenericRepository<VirtualNetworkFunctionRecord> vnfrRepository; @Override @Async public Future<Void> deploy(NetworkServiceRecord networkServiceRecord) throws NotFoundException, NamingException, JMSException { for (VirtualNetworkFunctionRecord vnfr : networkServiceRecord.getVnfr()) { CoreMessage coreMessage = new CoreMessage(); coreMessage.setAction(Action.INSTANTIATE); coreMessage.setPayload(vnfr); VnfmManagerEndpoint endpoint = vnfmRegister.getVnfm(vnfr.getType()); if (endpoint == null) { throw new NotFoundException("VnfManager of type " + vnfr.getType() + " is not registered"); } /** * TODO Here use an abstraction to call the particular vnfm_reg */ VnfmSender vnfmSender; try { vnfmSender = this.getVnfmSender(endpoint.getEndpointType()); } catch (BeansException e) { throw new NotFoundException(e); } vnfmSender.sendCommand(coreMessage, endpoint); } return new AsyncResult<Void>(null); } // @Override // public abstract void actionFinished(@Payload CoreMessage coreMessage) throws NotFoundException, NamingException, JMSException; @Override public VnfmSender getVnfmSender(EndpointType endpointType) throws BeansException{ String senderName = endpointType.toString().toLowerCase() + "Sender"; return (VnfmSender) this.context.getBean(senderName); } @Override public void executeAction(CoreMessage message) throws JMSException, NamingException, NotFoundException, VimException { VirtualNetworkFunctionRecord virtualNetworkFunctionRecord; VnfmSender vnfmSender; try { vnfmSender = this.getVnfmSender(EndpointType.JMS);// we know it is jms, I'm in a jms receiver... } catch (BeansException e2) { throw new NotFoundException(e2); } switch (message.getAction()){ case GRANT_OPERATION: virtualNetworkFunctionRecord = message.getPayload(); virtualNetworkFunctionRecord = vnfrRepository.merge(virtualNetworkFunctionRecord); if (lifecycleOperationGranting.grantLifecycleOperation(virtualNetworkFunctionRecord)){ vnfmSender.sendCommand(message,vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); }else { message.setAction(Action.ERROR); vnfmSender.sendCommand(message, vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); } break; case INSTANTIATE_FINISH: log.debug("INSTANTIATE_FINISH"); virtualNetworkFunctionRecord = message.getPayload(); virtualNetworkFunctionRecord = vnfrRepository.merge(virtualNetworkFunctionRecord); log.info("Instantiation is finished for vnfr: " +virtualNetworkFunctionRecord.getName()); break; case RELEASE_RESOURCES: virtualNetworkFunctionRecord = (VirtualNetworkFunctionRecord) message.getPayload(); for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) try { resourceManagement.release(vdu); } catch (VimException e) { e.printStackTrace(); log.error(e.getMessage()); CoreMessage errorMessage = new CoreMessage(); errorMessage.setAction(Action.ERROR); LifecycleEvent lifecycleEvent = new LifecycleEvent(); lifecycleEvent.setEvent(Event.ERROR); virtualNetworkFunctionRecord.getLifecycle_event_history().add(lifecycleEvent); errorMessage.setPayload(virtualNetworkFunctionRecord); vnfmSender.sendCommand(errorMessage, vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); return; } break; case ALLOCATE_RESOURCES: log.debug("ALLOCATE_RESOURCES"); virtualNetworkFunctionRecord = (VirtualNetworkFunctionRecord) message.getPayload(); List<Future<String>> ids = new ArrayList<>(); for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) try { ids.add(resourceManagement.allocate(vdu, virtualNetworkFunctionRecord)); } catch (VimException e) { e.printStackTrace(); log.error(e.getMessage()); CoreMessage errorMessage = new CoreMessage(); errorMessage.setAction(Action.ERROR); LifecycleEvent lifecycleEvent = new LifecycleEvent(); lifecycleEvent.setEvent(Event.ERROR); virtualNetworkFunctionRecord.getLifecycle_event_history().add(lifecycleEvent); errorMessage.setPayload(virtualNetworkFunctionRecord); vnfmSender.sendCommand(errorMessage, vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); return; } catch (VimDriverException e) { e.printStackTrace(); log.error(e.getMessage()); CoreMessage errorMessage = new CoreMessage(); errorMessage.setAction(Action.ERROR); LifecycleEvent lifecycleEvent = new LifecycleEvent(); lifecycleEvent.setEvent(Event.ERROR); virtualNetworkFunctionRecord.getLifecycle_event_history().add(lifecycleEvent); errorMessage.setPayload(virtualNetworkFunctionRecord); vnfmSender.sendCommand(errorMessage, vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); return; } CoreMessage coreMessage = new CoreMessage(); coreMessage.setAction(Action.INSTANTIATE); coreMessage.setPayload(virtualNetworkFunctionRecord); vnfmSender.sendCommand(coreMessage, vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType())); break; case INSTANTIATE: break; } publishEvent(message); } private void publishEvent(CoreMessage message) { ApplicationEventNFVO event = new ApplicationEventNFVO(this, message.getAction(), message.getPayload()); log.debug("Publishing event: " + event); publisher.publishEvent(event); } @Override @Async public Future<Void> modify(VirtualNetworkFunctionRecord virtualNetworkFunctionRecordDest, CoreMessage coreMessage) throws NotFoundException, NamingException, JMSException { VnfmManagerEndpoint endpoint = vnfmRegister.getVnfm(virtualNetworkFunctionRecordDest.getType()); if (endpoint == null) { throw new NotFoundException("VnfManager of type " + virtualNetworkFunctionRecordDest.getType() + " is not registered"); } VnfmSender vnfmSender; try { vnfmSender = this.getVnfmSender(endpoint.getEndpointType()); } catch (BeansException e) { throw new NotFoundException(e); } log.debug("Sending message " + coreMessage.getAction() + " to endpoint " + endpoint); vnfmSender.sendCommand(coreMessage, endpoint); return new AsyncResult<Void>(null); } @Override @Async public Future<Void> release(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws NotFoundException, NamingException, JMSException { VnfmManagerEndpoint endpoint = vnfmRegister.getVnfm(virtualNetworkFunctionRecord.getType()); if (endpoint == null) { throw new NotFoundException("VnfManager of type " + virtualNetworkFunctionRecord.getType() + " is not registered"); } CoreMessage coreMessage = new CoreMessage(); coreMessage.setAction(Action.RELEASE_RESOURCES); coreMessage.setPayload(virtualNetworkFunctionRecord); VnfmSender vnfmSender; try { vnfmSender = this.getVnfmSender(endpoint.getEndpointType()); } catch (BeansException e) { throw new NotFoundException(e); } vnfmSender.sendCommand(coreMessage, endpoint); return new AsyncResult<Void>(null); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } }
import java.io.*; import java.util.*; /* Checks Resume content with job description content */ public class ResumeJDComparison { private String resumeFilename; private String descriptionFilename; private double percentMatch; public ResumeJDComparison(String resumeFilename, String descriptionFilename) { this.resumeFilename = resumeFilename; this.descriptionFilename = descriptionFilename; this.analyze(); } public double percentMatch() { return percentMatch; } private void analyze() { HashMap<String, Integer> jobDict = (new TextToHashMap(descriptionFilename)).getWordDict(); HashMap<String, Integer> resumeDict = (new TextToHashMap(resumeFilename)).getWordDict(); int numMatch = 0; //Number of resume phrases in job description. for (String phrase: resumeDict.keySet()) { String[] words = phrase.split("\\s+"); //Gets all the words in a single phrase boolean match = true; //Checks if all the words in a phrase are present in the job description for (int i = 0; i < words.length; i++) { if (!jobDict.containsKey(words[i])) { match = false; break; } } if (match) { numMatch += 1; } } if (jobDict.size() > 0) { this.percentMatch = ((double) numMatch) / jobDict.size(); //Number of resume matched words divided by number of words in JD } else { this.percentMatch = 0; } } }
package arez.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import javax.annotation.Nonnull; /** * Methods marked with this annotation are invoked in an Arez transaction. * * <p>The method that is annotated with @Action must comply with the additional constraints:</p> * <ul> * <li>Must not be annotated with any other arez annotation</li> * <li>Must not be private</li> * <li>Must not be static</li> * <li>Must not be final</li> * <li>Must not be abstract</li> * </ul> */ @Documented @Target( ElementType.METHOD ) public @interface Action { /** * Return the name of the Action relative to the component. * The value must conform to the requirements of a java identifier. * The name must also be unique across {@link Observable}s, * {@link Computed}s and {@link Action}s within the scope of the * {@link ArezComponent} annotated element. * * @return the name of the Action relative to the component. */ @Nonnull String name() default "<default>"; /** * Does the action mutate state or not. * * @return true if method should be wrapped in READ_WRITE transaction, false if it should it should be wrapped in READ_ONLY transaction. */ boolean mutation() default true; /** * Return true if the parameters should be reported to the Arez spy subsystem. * It is useful to disable reporting for large, circular or just uninteresting parameters to the spy infrastructure. * * @return true to report the parameters, false otherwise. */ boolean reportParameters() default true; /** * Return true if the return value of the action (if any) should be reported to the Arez spy subsystem. * It is useful to disable reporting for large, circular or just uninteresting parameters to the spy infrastructure. * * @return true to report the parameters, false otherwise. */ boolean reportResult() default true; /** * True if the action should always start a new transaction. A false value indicates that the action will * use the invoking transaction if present, otherwise will create a new transaction to invoke action. * * @return true if the action will create a new transaction, false if it will use the existing transaction if present. */ boolean requireNewTransaction() default false; /** * Flag indicating whether the code should verify that at least one read or write occurs within * the scope of the action. * * @return true to verify action reads or writes observable data. */ boolean verifyRequired() default true; /** * True if invocations of the action must be executed in an {@link arez.Environment}. * * @return true if invocations of the action must be executed in an {@link arez.Environment}, false otherwise. */ boolean requireEnvironment() default false; }
package hudson.maven; import hudson.FilePath; import hudson.Util; import hudson.maven.agent.Main; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.DependencyGraph; import hudson.model.Hudson; import hudson.model.Result; import hudson.model.Run; import hudson.model.Slave; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Launcher; import hudson.remoting.Which; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.tasks.Maven.MavenInstallation; import hudson.tasks.test.AbstractTestResultAction; import hudson.util.ArgumentListBuilder; import hudson.util.IOException2; import org.codehaus.classworlds.NoSuchRealmException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Set; /** * {@link Run} for {@link MavenModule}. * * @author Kohsuke Kawaguchi */ public class MavenBuild extends AbstractBuild<MavenModule,MavenBuild> { /** * {@link MavenReporter}s that will contribute project actions. * Can be null if there's none. */ /*package*/ List<MavenReporter> projectActionReporters; public MavenBuild(MavenModule job) throws IOException { super(job); } public MavenBuild(MavenModule job, Calendar timestamp) { super(job, timestamp); } public MavenBuild(MavenModule project, File buildDir) throws IOException { super(project, buildDir); } /** * Gets the {@link MavenModuleSetBuild} that has the same build number. * * @return * null if no such build exists, which happens when the module build * is manually triggered. */ public MavenModuleSetBuild getParentBuild() { return getParent().getParent().getBuildByNumber(getNumber()); } @Override public ChangeLogSet<? extends Entry> getChangeSet() { return new FilteredChangeLogSet(this); } /** * We always get the changeset from {@link MavenModuleSetBuild}. */ @Override public boolean hasChangeSetComputed() { return true; } @Override public AbstractTestResultAction getTestResultAction() { return getAction(AbstractTestResultAction.class); } public void registerAsProjectAction(MavenReporter reporter) { if(projectActionReporters==null) projectActionReporters = new ArrayList<MavenReporter>(); projectActionReporters.add(reporter); } @Override public void run() { run(new RunnerImpl()); getProject().updateTransientActions(); } /** * Runs Maven and builds the project. * * This code is executed on the remote machine. */ private static final class Builder implements Callable<Result,IOException> { private final BuildListener listener; private final MavenBuildProxy buildProxy; private final MavenReporter[] reporters; private final List<String> goals; public Builder(BuildListener listener,MavenBuildProxy buildProxy,MavenReporter[] reporters, List<String> goals) { this.listener = listener; this.buildProxy = buildProxy; this.reporters = reporters; this.goals = goals; } public Result call() throws IOException { try { int r = Main.launch(goals.toArray(new String[goals.size()])); return r==0 ? Result.SUCCESS : Result.FAILURE; } catch (NoSuchMethodException e) { throw new IOException2(e); } catch (IllegalAccessException e) { throw new IOException2(e); } catch (NoSuchRealmException e) { throw new IOException2(e); } catch (InvocationTargetException e) { throw new IOException2(e); } catch (ClassNotFoundException e) { throw new IOException2(e); } //MavenProject p=null; //try { // MavenEmbedder embedder = MavenUtil.createEmbedder(listener); // File pom = new File("pom.xml").getAbsoluteFile(); // MavenEmbedder only works if it's absolute // if(!pom.exists()) { // listener.error("No POM: "+pom); // return Result.FAILURE; // // event monitor is mostly useless. It only provides a few strings // EventMonitor eventMonitor = new DefaultEventMonitor( new PlexusLoggerAdapter( new EmbedderLoggerImpl(listener) ) ); // p = embedder.readProject(pom); // PluginManagerInterceptor interceptor; // try { // interceptor = (PluginManagerInterceptor)embedder.getContainer().lookup(PluginManager.class.getName()); // interceptor.setBuilder(buildProxy,reporters,listener); // } catch (ComponentLookupException e) { // throw new Error(e); // impossible // for (MavenReporter r : reporters) // r.preBuild(buildProxy,p,listener); // embedder.execute(p, goals, eventMonitor, // new TransferListenerImpl(listener), // null, // TODO: allow additional properties to be specified // pom.getParentFile()); // interceptor.fireLeaveModule(); // return null; //} catch (MavenEmbedderException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (ProjectBuildingException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (CycleDetectedException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (LifecycleExecutionException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (BuildFailureException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (DuplicateProjectException e) { // buildProxy.setResult(Result.FAILURE); // e.printStackTrace(listener.error(e.getMessage())); //} catch (AbortException e) { // listener.error("build aborted"); //} catch (InterruptedException e) { // listener.error("build aborted"); //} finally { // // this should happen after a build is marked as a failure // try { // if(p!=null) // for (MavenReporter r : reporters) // r.postBuild(buildProxy,p,listener); // } catch (InterruptedException e) { // buildProxy.setResult(Result.FAILURE); } } /** * {@link MavenBuildProxy} implementation. */ private class ProxyImpl implements MavenBuildProxy, Serializable { public <V, T extends Throwable> V execute(BuildCallable<V, T> program) throws T, IOException, InterruptedException { return program.call(MavenBuild.this); } public FilePath getRootDir() { return new FilePath(MavenBuild.this.getRootDir()); } public FilePath getProjectRootDir() { return new FilePath(MavenBuild.this.getParent().getRootDir()); } public FilePath getArtifactsDir() { return new FilePath(MavenBuild.this.getArtifactsDir()); } public void setResult(Result result) { MavenBuild.this.setResult(result); } public void registerAsProjectAction(MavenReporter reporter) { MavenBuild.this.registerAsProjectAction(reporter); } private Object writeReplace() { return Channel.current().export(MavenBuildProxy.class, new ProxyImpl()); } } private static final class getJavaExe implements Callable<String,IOException> { public String call() throws IOException { return new File(new File(System.getProperty("java.home")),"bin/java").getPath(); } } private class RunnerImpl extends AbstractRunner { protected Result doRun(BuildListener listener) throws Exception { // pick up a list of reporters to run List<MavenReporter> reporters = new ArrayList<MavenReporter>(); getProject().getReporters().addAllTo(reporters); for (MavenReporterDescriptor d : MavenReporters.LIST) { if(getProject().getReporters().contains(d)) continue; // already configured MavenReporter auto = d.newAutoInstance(getProject()); if(auto!=null) reporters.add(auto); } // start maven process ArgumentListBuilder args = buildMavenCmdLine(); Channel channel = launcher.launchChannel(args.toCommandArray(), new String[0], listener.getLogger(), getProject().getModuleRoot()); // Maven started. ArgumentListBuilder margs = new ArgumentListBuilder(); margs.add("-N"); margs.addTokenized(getProject().getGoals()); try { return channel.call(new Builder( listener,new ProxyImpl(), reporters.toArray(new MavenReporter[0]), margs.toList())); } finally { channel.close(); } } // UGLY.... private ArgumentListBuilder buildMavenCmdLine() throws IOException, InterruptedException { MavenInstallation mvn = getParent().getParent().getMaven(); // find classworlds.jar File bootDir = new File(mvn.getHomeDir(), "core/boot"); File[] classworlds = bootDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("classworlds") && name.endsWith(".jar"); } }); if(classworlds==null || classworlds.length==0) throw new IOException("No classworlds*.jar found in "+bootDir+" -- Is this a valid maven2 directory?"); boolean isMaster = getCurrentNode()==Hudson.getInstance(); FilePath slaveRoot=null; if(!isMaster) slaveRoot = ((Slave)getCurrentNode()).getFilePath(); ArgumentListBuilder args = new ArgumentListBuilder(); args.add(launcher.getChannel().call(new getJavaExe())); args.add("-cp"); args.add( (isMaster?Which.jarFile(Main.class).getAbsolutePath():slaveRoot.child("maven-agent.jar").getRemote())+ (launcher.isUnix()?":":";")+ classworlds[0].getAbsolutePath()); args.add(Main.class.getName()); // M2_HOME args.add(mvn.getMavenHome()); // remoting.jar args.add(Which.jarFile(Launcher.class).getPath()); // interceptor.jar args.add(isMaster? Which.jarFile(hudson.maven.agent.PluginManagerInterceptor.class).getAbsolutePath(): slaveRoot.child("maven-interceptor.jar").getRemote()); return args; } public void post(BuildListener listener) { if(!getResult().isWorseThan(Result.UNSTABLE)) { // trigger dependency builds DependencyGraph graph = Hudson.getInstance().getDependencyGraph(); for( AbstractProject<?,?> down : getParent().getDownstreamProjects()) { if(graph.hasIndirectDependencies(getParent(),down)) // if there's a longer dependency path to this project, // then scheduling the build now is going to be a waste, // so don't do that. // let the longer path eventually trigger this build continue; // if the downstream module depends on multiple modules, // only trigger them when all the upstream dependencies are updated. boolean trigger = true; AbstractBuild<?,?> dlb = down.getLastBuild(); // can be null. for (MavenModule up : Util.filter(down.getUpstreamProjects(),MavenModule.class)) { MavenBuild ulb; if(up==getProject()) { // the current build itself is not registered as lastSuccessfulBuild // at this point, so we have to take that into account. ugly. if(getResult()==null || !getResult().isWorseThan(Result.UNSTABLE)) ulb = MavenBuild.this; else ulb = up.getLastSuccessfulBuild(); } else ulb = up.getLastSuccessfulBuild(); if(ulb==null) { // if no usable build is available from the upstream, // then we have to wait at least until this build is ready trigger = false; break; } // if no record of the relationship in the last build // is available, we'll just have to assume that the condition // for the new build is met, or else no build will be fired forever. if(dlb==null) continue; int n = dlb.getUpstreamRelationship(up); if(n==-1) continue; assert ulb.getNumber()>=n; if(ulb.getNumber()==n) { // there's no new build of this upstream since the last build // of the downstream, and the upstream build is in progress. // The new downstream build should wait until this build is started if(isUpstreamBuilding(graph,up)) { trigger = false; break; } } } if(trigger) { listener.getLogger().println("Triggering a new build of "+down.getName()); down.scheduleBuild(); } } } } /** * Returns true if any of the upstream project (or itself) is either * building or is in the queue. * <p> * This means eventually there will be an automatic triggering of * the given project (provided that all builds went smoothly.) */ private boolean isUpstreamBuilding(DependencyGraph graph, AbstractProject project) { Set<AbstractProject> tups = graph.getTransitiveUpstream(project); tups.add(project); for (AbstractProject tup : tups) { if(tup.isBuilding() || tup.isInQueue()) return true; } return false; } } }
import java.util.*; public class RepairDroid { public static final String INITIAL_INPUT = Integer.toString(DroidMovement.NORTH); private static final int EXPLORE_UNTIL_OXYGEN = 1; private static final int EXPLORE_ENTIRE_MAZE = 2; public RepairDroid (Vector<String> instructions, boolean debug) { _debug = debug; _theComputer = new Intcode(instructions, INITIAL_INPUT, _debug); _currentLocation = new Coordinate(0, 0); // starting location _startingPoint = _currentLocation; _theMap = new Maze(); _trackTaken = new Stack<Integer>(); _foundOxygenStation = false; _exploreOption = EXPLORE_UNTIL_OXYGEN; _theMap.updateTile(_currentLocation, TileId.STARTING_POINT); } public final int moveToOxygenStation () { _exploreOption = EXPLORE_UNTIL_OXYGEN; explore(); return _trackTaken.size(); } public final boolean mapEntireMaze () { boolean mapped = false; _exploreOption = EXPLORE_ENTIRE_MAZE; explore(); return mapped; } public void printGrid () { System.out.println(_theMap); } /* * If we run into a wall then try a different direction. * If we can't move other than backwards then do that. * Don't move into areas we've already been. */ private int explore () { int response = DroidStatus.ERROR; while (!_theComputer.hasHalted() && !stopSearch()) { boolean needToBackup = false; //if (_debug) System.out.println("\n"+_theMap); /* * We search N, E, S and then W. */ response = tryToMove(String.valueOf(DroidMovement.NORTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.NORTH)); if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED)) { //if (_debug) System.out.println("\n"+_theMap); response = tryToMove(String.valueOf(DroidMovement.EAST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.EAST)); if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED)) { //if (_debug) System.out.println("\n"+_theMap); response = tryToMove(String.valueOf(DroidMovement.SOUTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.SOUTH)); if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED)) { //if (_debug) System.out.println("\n"+_theMap); response = tryToMove(String.valueOf(DroidMovement.WEST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.WEST)); if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED)) { //if (_debug) System.out.println("\n"+_theMap); /* * At this point we've exhausted all of the options for moving from * the current location. Therefore, we need to backtrack. */ needToBackup = true; } } } } if (needToBackup) return backtrack(); } return response; } private int tryToMove (String direction, Coordinate to) { if (_debug) System.out.println("Trying to move from: "+_currentLocation+" to "+to+" with direction "+DroidMovement.toString(direction)); // if we've already been there then don't move! if (_theMap.isExplored(to)) return DroidStatus.VISITED; _theComputer.setInput(direction); _theComputer.executeUntilInput(); if (_theComputer.hasOutput()) { int response = Integer.parseInt(_theComputer.getOutput()); if (_debug) System.out.println("Response is "+DroidStatus.toString(response)); switch (response) { case DroidStatus.ARRIVED: // arrived at the station!! { _theMap.updateTile(_currentLocation, TileId.TRAVERSE); _theMap.updateTile(to, TileId.OXYGEN_STATION); _currentLocation = to; recordJourney(Integer.parseInt(direction)); _foundOxygenStation = true; if (_debug) { System.out.println("FOUND OXYGEN!"); System.out.println("\n"+_theMap); } return response; } case DroidStatus.COLLISION: { _theMap.updateTile(to, TileId.WALL); // didn't move as we hit a wall return response; } case DroidStatus.MOVED: { /* * Droid moved so let's try to move again. */ if (!_currentLocation.equals(_startingPoint)) _theMap.updateTile(_currentLocation, TileId.TRAVERSE); _theMap.updateTile(to, TileId.DROID); _currentLocation = to; recordJourney(Integer.parseInt(direction)); return explore(); } default: System.out.println("Unknown response: "+response); } } else System.out.println("Error - no output after move instruction!"); return DroidStatus.ERROR; // error!! } private int backtrack () { int status = DroidStatus.ERROR; if (_trackTaken.size() > 0) { int backupDirection = DroidMovement.backupDirection(_trackTaken.pop()); if (_debug) System.out.println("Trying to backup from: "+_currentLocation+" with direction "+DroidMovement.toString(backupDirection)); _theComputer.setInput(String.valueOf(backupDirection)); _theComputer.executeUntilInput(); if (_theComputer.hasOutput()) { int response = Integer.parseInt(_theComputer.getOutput()); if (response == DroidStatus.MOVED) { _theMap.updateTile(_currentLocation, TileId.TRAVERSE); _currentLocation = DroidMovement.getNextPosition(_currentLocation, backupDirection); _theMap.updateTile(_currentLocation, TileId.DROID); status = DroidStatus.BACKTRACKED; // different from normal move response } else System.out.println("Unexpected backup response: "+response); } else System.out.println("Error - no output after move instruction!"); } else System.out.println("Cannot backtrack!"); return status; } private void recordJourney (int direction) { if (!stopSearch()) _trackTaken.push(direction); } private final void printTrack () { Enumeration<Integer> iter = _trackTaken.elements(); System.out.println("Path taken so far ..."); while (iter.hasMoreElements()) System.out.println("Moved "+DroidMovement.toString(iter.nextElement())); } private final boolean stopSearch () { if ((_exploreOption == EXPLORE_UNTIL_OXYGEN) && (_foundOxygenStation)) return true; else return false; } private boolean _debug; private Intcode _theComputer; private Coordinate _currentLocation; private Coordinate _startingPoint; private Maze _theMap; private Stack<Integer> _trackTaken; private boolean _foundOxygenStation; private int _exploreOption; }
package com.yahoo.vespa.hosted.controller.restapi.zone.v2; import com.yahoo.application.container.handler.Request.Method; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.zone.ZoneApi; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.vespa.hosted.controller.integration.ConfigServerProxyMock; import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock; import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest; import com.yahoo.vespa.hosted.controller.restapi.ContainerTester; import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author mpolden */ public class ZoneApiTest extends ControllerContainerTest { private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/responses/"; private static final List<ZoneApi> zones = List.of( ZoneApiMock.fromId("prod.us-north-1"), ZoneApiMock.fromId("dev.aws-us-north-2"), ZoneApiMock.fromId("test.us-north-3"), ZoneApiMock.fromId("staging.us-north-4")); private ContainerTester tester; private ConfigServerProxyMock proxy; @Before public void before() { tester = new ContainerTester(container, responseFiles); tester.serviceRegistry().zoneRegistry() .setDefaultRegionForEnvironment(Environment.dev, RegionName.from("us-north-2")) .setZones(zones); proxy = (ConfigServerProxyMock) container.components().getComponent(ConfigServerProxyMock.class.getName()); } @Test public void test_requests() { // GET /zone/v2 tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2"), new File("root.json")); // GET /zone/v2/prod/us-north-1 tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1"), "ok"); assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET"); // GET /zone/v2/nodes/v2/node/?recursive=true tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/?recursive=true"), "ok"); assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET"); // POST /zone/v2/dev/us-north-2/nodes/v2/command/restart?hostname=node1 tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/command/restart?hostname=node1", "", Method.POST), "ok"); // PUT /zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1 tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1", "", Method.PUT), "ok"); assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "PUT"); // DELETE /zone/v2/prod/us-north-1/nodes/v2/node/node1 tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/node1", "", Method.DELETE), "ok"); assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "DELETE"); // PATCH /zone/v2/prod/us-north-1/nodes/v2/node/node1 tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/node/node1", "{\"currentRestartGeneration\": 1}", Method.PATCH), "ok"); assertLastRequest(ZoneId.from("dev", "aws-us-north-2"), 1, "PATCH"); assertEquals("{\"currentRestartGeneration\": 1}", proxy.lastRequestBody().get()); assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty()); } @Test public void test_invalid_requests() { // POST /zone/v2/prod/us-north-34/nodes/v2 tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-42/nodes/v2", "", Method.POST), new File("unknown-zone.json"), 400); assertFalse(proxy.lastReceived().isPresent()); } private void assertLastRequest(ZoneId zoneId, int targets, String method) { ProxyRequest last = proxy.lastReceived().orElseThrow(); assertEquals(targets, last.getTargets().size()); assertTrue(last.getTargets().get(0).toString().contains(zoneId.value())); assertEquals(com.yahoo.jdisc.http.HttpRequest.Method.valueOf(method), last.getMethod()); } }
package org.cytoscape.task.internal.loadnetwork; import java.text.DecimalFormat; import java.text.NumberFormat; import org.cytoscape.io.read.CyNetworkReader; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.session.CyNetworkNaming; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.view.presentation.property.BasicVisualLexicon; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.work.AbstractTask; import org.cytoscape.work.TaskMonitor; class GenerateNetworkViewsTask extends AbstractTask { private final String name; private final CyNetworkReader viewReader; private final CyNetworkManager networkManager; private final CyNetworkViewManager networkViewManager; private final CyNetworkNaming namingUtil; private final int viewThreshold; private final VisualMappingManager vmm; public GenerateNetworkViewsTask(final String name, final CyNetworkReader viewReader, final CyNetworkManager networkManager, final CyNetworkViewManager networkViewManager, final CyNetworkNaming namingUtil, final int viewThreshold, final VisualMappingManager vmm) { this.name = name; this.viewReader = viewReader; this.networkManager = networkManager; this.networkViewManager = networkViewManager; this.namingUtil = namingUtil; this.viewThreshold = viewThreshold; this.vmm = vmm; } public void run(final TaskMonitor taskMonitor) throws Exception { taskMonitor.setProgress(0.0); final VisualStyle style = vmm.getCurrentVisualStyle(); // get the current style before registering the views! final CyNetwork[] networks = viewReader.getNetworks(); double numNets = (double)(networks.length); int i = 0; for (CyNetwork network : networks) { // Use original name if exists String networkName = network.getRow(network).get(CyNetwork.NAME, String.class); if (networkName == null || networkName.trim().length() == 0) { networkName = name; if (networkName == null) networkName = "? (Name is missing)"; network.getRow(network).set(CyNetwork.NAME, namingUtil.getSuggestedNetworkTitle(networkName)); } networkManager.addNetwork(network); final int numGraphObjects = network.getNodeCount() + network.getEdgeCount(); if (numGraphObjects < viewThreshold) { final CyNetworkView view = viewReader.buildCyNetworkView(network); networkViewManager.addNetworkView(view); vmm.setVisualStyle(style, view); style.apply(view); if (!view.isSet(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION) && !view.isSet(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION) && !view.isSet(BasicVisualLexicon.NETWORK_CENTER_Z_LOCATION)) view.fitContent(); } taskMonitor.setProgress((double)(++i)/numNets); informUserOfGraphStats(network, numGraphObjects, taskMonitor); } // If this is a subnetwork, and there is only one subnetwork in the root, check the name of the root network // If there is no name yet for the root network, set it the same as its base subnetwork if (networks.length == 1){ if (networks[0] instanceof CySubNetwork){ CySubNetwork subnet = (CySubNetwork) networks[0]; final CyRootNetwork rootNet = subnet.getRootNetwork(); String rootNetName = rootNet.getRow(rootNet).get(CyNetwork.NAME, String.class); if (rootNetName == null || rootNetName.trim().length() == 0){ // The root network does not have a name yet, set it the same as the base subnetwork rootNet.getRow(rootNet).set(CyNetwork.NAME, networks[0].getRow(networks[0]).get(CyNetwork.NAME, String.class)); } } } // Make sure rootNetwork has a name for (CyNetwork network : networks) { if (network instanceof CySubNetwork){ CySubNetwork subNet = (CySubNetwork) network; CyRootNetwork rootNet = subNet.getRootNetwork(); String networkName = rootNet.getRow(rootNet).get(CyNetwork.NAME, String.class); if(networkName == null || networkName.trim().length() == 0) { networkName = name; if(networkName == null) networkName = "? (Name is missing)"; rootNet.getRow(rootNet).set(CyNetwork.NAME, namingUtil.getSuggestedNetworkTitle(networkName)); } } } } /** * Inform User of Network Stats. */ private void informUserOfGraphStats(final CyNetwork newNetwork, final int objectCount, final TaskMonitor taskMonitor) { NumberFormat formatter = new DecimalFormat(" StringBuffer sb = new StringBuffer(); // Give the user some confirmation sb.append("Successfully loaded network from: "); sb.append(name); sb.append("\n\nNetwork contains " + formatter.format(newNetwork.getNodeCount())); sb.append(" nodes and " + formatter.format(newNetwork.getEdgeCount())); sb.append(" edges.\n\n"); if (objectCount < viewThreshold) { sb.append("Network is under " + viewThreshold + " graph objects. A view will be automatically created."); } else { sb.append("Network is over " + viewThreshold + " graph objects. A view has not been created." + " If you wish to view this network, use " + "\"Create View\" from the \"Edit\" menu."); } taskMonitor.setStatusMessage(sb.toString()); } }
package com.extrahardmode.task; import com.extrahardmode.ExtraHardMode; import com.extrahardmode.config.RootConfig; import com.extrahardmode.config.RootNode; import com.extrahardmode.features.Feature; import com.extrahardmode.module.DataStoreModule; import com.extrahardmode.module.EntityHelper; import com.extrahardmode.module.PlayerModule; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.AbstractMap.SimpleEntry; /** * Task to spawn more monsters. */ public class MoreMonstersTask implements Runnable { //TODO Return to this and make it actually spawn and not just take the old locations //TODO if block not valid check random block nearby /** * Plugin instance. */ private final ExtraHardMode plugin; /** * Config instanz */ private final RootConfig CFG; private final PlayerModule playerModule; /** * Constructor. * * @param plugin * - Plugin instance. */ public MoreMonstersTask(ExtraHardMode plugin) { this.plugin = plugin; CFG = plugin.getModuleForClass(RootConfig.class); playerModule = plugin.getModuleForClass(PlayerModule.class); } @Override public void run() { DataStoreModule dataStore = plugin.getModuleForClass(DataStoreModule.class); // spawn monsters from the last pass for (SimpleEntry<Player, Location> entry : dataStore.getPreviousLocations()) { Player player = entry.getKey(); Location location = entry.getValue(); Chunk chunk = location.getChunk(); World world = location.getWorld(); try { location = verifyLocation(location); if (location != null && location.getChunk().isLoaded()) {// spawn random monster(s) if (world.getEnvironment() == Environment.NORMAL) { Entity mob = EntityHelper.spawnRandomMob(location); //If there are Players nearby don't spawn //TODO find bug, maybe its the dev build?.... /*List<Entity> entities = mob.getNearbyEntities(32.0, 32.0, 32.0); for (Entity ent : entities) if (ent instanceof Player) { mob.remove(); break; }*/ for (Player p : plugin.getServer().getOnlinePlayers()) if (player.getLocation().distanceSquared(mob.getLocation()) < 600.0) { mob.remove(); break; } } } } catch (IllegalArgumentException ignored) { } // in case the player is in a different world from the saved location } // plan for the next pass dataStore.getPreviousLocations().clear(); for (Player player : plugin.getServer().getOnlinePlayers()) { Location verifiedLocation = null; //only if player hasn't got bypass and is in survival check location if (!playerModule.playerBypasses(player, Feature.MONSTERRULES)) verifiedLocation = verifyLocation(player.getLocation()); if (verifiedLocation != null) dataStore.getPreviousLocations().add(new SimpleEntry<Player, Location>(player, verifiedLocation)); } } //TODO move this into a utility class /** * Tests if a a given location is elligible to be spawned on * * @return a valid Location or null if the location is invalid */ private Location verifyLocation(Location location) { World world = location.getWorld(); Location verifiedLoc = null; final int maxY = CFG.getInt(RootNode.MONSTER_SPAWNS_IN_LIGHT_MAX_Y, world.getName()); // Only spawn monsters in normal world. End is crowded with endermen and nether is too extreme anyway, add config later int lightLvl = location.getBlock().getLightFromSky(); if (world.getEnvironment() == World.Environment.NORMAL && (location.getY() < maxY && lightLvl < 3)) verifiedLoc = EntityHelper.isLocSafeSpawn(location); return verifiedLoc; } }
package TobleMiner.MineFight.Configuration; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import TobleMiner.MineFight.ErrorHandling.Error; import TobleMiner.MineFight.ErrorHandling.ErrorReporter; import TobleMiner.MineFight.ErrorHandling.ErrorSeverity; import TobleMiner.MineFight.GameEngine.Match.Gamemode.Gamemode; import TobleMiner.MineFight.Protection.ProtectedArea; public class Config { public final HashMap<World,List<ProtectedArea>> protectionRegions = new HashMap<World,List<ProtectedArea>>(); public final FileConfiguration config; private final String flname = "plugins"+File.separator+"MineFight"+File.separator+"mineFight.conf"; public Config(FileConfiguration config) { this.config = config; } public void read() { this.load(); boolean makeConfig = config.getBoolean("config.reset",true); if(makeConfig) { List<World> worlds = Bukkit.getServer().getWorlds(); for(int i=0;i<worlds.size();i++) { World world = worlds.get(i); String name = world.getName(); Location spawn = world.getSpawnLocation(); String wpref = "Worlds."+name; config.set(wpref+".mpvp",false); config.set(wpref+".classSelection.X",spawn.getBlockX()); config.set(wpref+".classSelection.Y",spawn.getBlockY()); config.set(wpref+".classSelection.Z",spawn.getBlockZ()); config.set(wpref+".battleSpawn.X",spawn.getBlockX()); config.set(wpref+".battleSpawn.Y",spawn.getBlockY()); config.set(wpref+".battleSpawn.Z",spawn.getBlockZ()); ConfigurationSection cs = config.createSection("Worlds."+name+".protections"); String s = Integer.toString(spawn.getBlockX())+","+Integer.toString(spawn.getBlockY())+","+Integer.toString(spawn.getBlockZ()); cs.set(s+".pos1.X",spawn.getBlockX()); cs.set(s+".pos1.Y",spawn.getBlockY()); cs.set(s+".pos1.Z",spawn.getBlockZ()); cs.set(s+".pos2.X",spawn.getBlockX()); cs.set(s+".pos2.Y",spawn.getBlockY()); cs.set(s+".pos2.Z",spawn.getBlockZ()); cs.set(s+".enabled",true); for(Gamemode gmode : Gamemode.values()) { String wgmpref = wpref+".gamemodes."+gmode.toString().toLowerCase(); config.set(wgmpref+".points",500); config.set(wgmpref+".enabled",true); config.set(wgmpref+".autobalance",true); config.set(wgmpref+".player.preventItemDropOnDeath",true); config.set(wgmpref+".player.preventItemDrop",true); config.set(wgmpref+".player.enableFallDamage",true); config.set(wgmpref+".player.enableHunger",false); config.createSection(wgmpref+".infoSigns"); if(gmode.equals(Gamemode.Conquest)) { config.createSection(wgmpref+".flags"); config.set(wgmpref+".flagCaptureDistance",10); config.set(wgmpref+".flagCaptureSpeed",10); config.set(wgmpref+".flagCaptureAccelerationPerPerson",1.2d); config.set(wgmpref+".pointlossPerFlagPerSecond",1.0d); config.set(wgmpref+".losePointsWhenEnemyHasLessThanHalfFlags",false); } else if(gmode.equals(Gamemode.Rush)) { config.createSection(wgmpref+".radioStations"); config.set(wgmpref+".destructTime",10d); config.set(wgmpref+".defenderOuterSpawnRadius",20d); config.set(wgmpref+".defenderInnerSpawnRadius",5d); config.set(wgmpref+".attackerOuterSpawnRadius",70d); config.set(wgmpref+".attackerInnerSpawnRadius",30d); } config.set(wgmpref+".weapon.sniperDamage",10d); config.set(wgmpref+".weapon.generalDamage",5d); config.set(wgmpref+".weapon.headshotMultiplier",2d); config.set(wgmpref+".weapon.legshotMultiplier",0.5d); config.set(wgmpref+".weapon.critProbability",0.02d); config.set(wgmpref+".weapon.critMultiplier",2d); config.set(wgmpref+".environment.canBeDamaged",true); config.set(wgmpref+".environment.doExplosionsDamageEnvironment",true); } config.set(wpref+".environment.canBeDamaged",true); config.set(wpref+".environment.doExplosionsDamageEnvironment",true); config.set(wpref+".leaveWorld","world"); config.set(wpref+".minimapEnabled",true); } config.set("CombatClass.Sniper.Kit","261:0,1;262:0,64;337:0,4;268:0,1"); config.set("CombatClass.Sniper.Armor","298,299,300,301"); config.set("CombatClass.Heavy.Kit","267:0,1;264:0,1;351:4,5"); config.set("CombatClass.Heavy.Armor","310,311,312,313"); config.set("CombatClass.Engineer.Kit","267:0,1;268:0,1;23:0,1;262:0,64"); config.set("CombatClass.Engineer.Armor","306,307,308,309"); config.set("CombatClass.Medic.Kit","267:0,1;268:0,1;23:0,1;262:0,64"); config.set("CombatClass.Medic.Armor","306,307,308,309"); config.set("CombatClass.Pyro.Kit","267:0,1;268:0,1;23:0,1;262:0,64"); config.set("CombatClass.Pyro.Armor","306,307,308,309"); config.set("GameControl.Sign.joinCmd","Join game"); config.set("GameProps.C4.exploStr",4.0d); config.set("GameProps.C4.throwSpeed",0.5d); config.set("GameProps.C4.killRangeMod",0.5d); config.set("GameProps.C4.allowedInsideProtection",false); config.set("GameProps.M18.exploStr",4.0d); config.set("GameProps.M18.killRangeMod",0.5d); config.set("GameProps.M18.allowedInsideProtection",false); config.set("GameProps.sentry.projectileSpeed",4.5d); config.set("GameProps.sentry.missileSpeed",2.0d); config.set("GameProps.sentry.missileExploStr",3.0d); config.set("GameProps.sentry.missileKillRangeMod",0.5d); config.set("GameProps.sniperRifle.projectileSpeed",5.0d); config.set("GameProps.handGrenade.exploStr",4.0d); config.set("GameProps.handGrenade.fuse",3.0d); config.set("GameProps.handGrenade.throwSpeed",1.5d); config.set("GameProps.handGrenade.killRangeMod",0.5d); config.set("GameProps.handGrenade.allowedInsideProtection",true); config.set("GameProps.rpg.speed",1.5d); config.set("GameProps.rpg.accel",0.1d); config.set("GameProps.rpg.throtle",0.1d); config.set("GameProps.rpg.exploStr",3.0d); config.set("GameProps.rpg.lifeTime",10.0d); config.set("GameProps.rpg.killRangeMod",0.5d); config.set("GameProps.ims.triggerDist",12.0d); config.set("GameProps.ims.shots",6); config.set("GameProps.ims.allowedInsideProtection",false); config.set("GameProps.ims.grenade.speed",1.0d); config.set("GameProps.ims.grenade.height",20.0d); config.set("GameProps.ims.grenade.exploStr",4.0d); config.set("GameProps.ammoResupply.range", 4.0d); config.set("GameProps.ammoResupply.speed", 4.0d); config.set("GameProps.ammoResupply.amount", 20); config.set("GameProps.flamethrower.ignitionDist", 4.0d); config.set("GameProps.flamethrower.directDamage", 1); config.set("GameProps.medigun.healingDist", 4.0d); config.set("GameProps.medigun.healingRate", 1); config.set("GameProps.killassist.pointsPerPercent", 1d); config.set("GameProps.lang","EN_us.lang"); config.set("config.reset",false); config.set("debug",false); this.save(); } this.protectionRegions.clear(); List<World> worlds = Bukkit.getServer().getWorlds(); for(int i=0;i<worlds.size();i++) { World world = worlds.get(i); ConfigurationSection cs = config.getConfigurationSection("Worlds."+world.getName()+".protections"); List<ProtectedArea> lpa = new ArrayList<ProtectedArea>(); Set<String> keys = cs.getValues(false).keySet(); for(String key : keys) { double x1 = cs.getDouble(key+".pos1.X"); double y1 = cs.getDouble(key+".pos1.Y"); double z1 = cs.getDouble(key+".pos1.Z"); double x2 = cs.getDouble(key+".pos2.X"); double y2 = cs.getDouble(key+".pos2.Y"); double z2 = cs.getDouble(key+".pos2.Z"); if(this.isProtectionEnabled(cs,key)) { lpa.add(new ProtectedArea(new Location(world, x1, y1, z1), new Location(world, x2, y2, z2))); } } this.protectionRegions.put(world, lpa); } } public void load() { try { config.load(flname); } catch(Exception ex) { Error error = new Error("Failed loading configuration! This is normal if you start the plugin for the first time.","The pluginconfiguration could not be loaded: "+ex.getMessage(),"The plugin won't work until this error is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.SEVERE); ErrorReporter.reportError(error); } } public void save() { try { config.save(flname); } catch(Exception ex) { Error error = new Error("Failed saving configuration!","The pluginconfiguration could not be saved: "+ex.getMessage(),"The plugin won't work until this error is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.SEVERE); ErrorReporter.reportError(error); } } public Location getRoundEndSpawnForWorld(World w) { String worldStr = config.getString("Worlds."+w.getName()+".leaveWorld"); if(worldStr != null) { World world = Bukkit.getServer().getWorld(worldStr); if(world != null) { return world.getSpawnLocation(); } } return null; } public boolean isProtectionEnabled(ConfigurationSection cs,String key) { return cs.getBoolean(key+".enabled",true); } public Location getRespawnForWorld(World w) { Double x = config.getDouble("Worlds."+w.getName()+".classSelection.X"); Double y = config.getDouble("Worlds."+w.getName()+".classSelection.Y"); Double z = config.getDouble("Worlds."+w.getName()+".classSelection.Z"); return new Location(w, x, y, z); } public Location getSpawnForWorld(World w) { Double x = config.getDouble("Worlds."+w.getName()+".battleSpawn.X"); Double y = config.getDouble("Worlds."+w.getName()+".battleSpawn.Y"); Double z = config.getDouble("Worlds."+w.getName()+".battleSpawn.Z"); return new Location(w, x, y, z); } public float getC4ExploStr() { return (float)config.getDouble("GameProps.C4.exploStr"); } public float getC4KillRangeMod() { return (float)config.getDouble("GameProps.C4.killRangeMod"); } public float getM18ExploStr() { return (float)config.getDouble("GameProps.M18.exploStr"); } public float getM18KillRangeMod() { return (float)config.getDouble("GameProps.M18.killRangeMod"); } public float getSentryArrowSpeed() { return (float)config.getDouble("GameProps.sentry.projectileSpeed"); } public float getSniperMuzzleVelocity() { return (float)config.getDouble("GameProps.sniperRifle.projectileSpeed"); } public float getHandGrenadeExploStr() { return (float)config.getDouble("GameProps.handGrenade.exploStr"); } public float getHandGrenadeFuse() { return (float)config.getDouble("GameProps.handGrenade.fuse"); } public float getHandGrenadeThrowSpeed() { return (float)config.getDouble("GameProps.handGrenade.throwSpeed"); } public float getHandGrenadeKillRangeMod() { return (float)config.getDouble("GameProps.handGrenade.killRangeMod"); } public boolean isGamemodeEnabledInWorld(World w, Gamemode gmode) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gmode.toString().toLowerCase()+".enabled",false); } public int getPointsForGamemodeInWorld(World w, Gamemode gmode) { return config.getInt("Worlds."+w.getName()+".gamemodes."+gmode.toString().toLowerCase()+".points"); } public void addInfoSign(Sign sign,Gamemode gm) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+gm.toString().toLowerCase()+".infoSigns"); if(cs != null) { String signName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(signName+".X",sign.getLocation().getX()); cs.set(signName+".Y",sign.getLocation().getY()); cs.set(signName+".Z",sign.getLocation().getZ()); this.save(); } } public void removeInfoSign(Sign sign,Gamemode gm) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+gm.toString().toLowerCase()+".infoSigns"); if(cs != null) { String signName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(signName+".X",null); cs.set(signName+".Y",null); cs.set(signName+".Z",null); cs.set(signName,null); this.save(); } } public List<Sign> getInfoSigns(World world,Gamemode gm) { List<Sign> signs = new ArrayList<Sign>(); try { ConfigurationSection cs = config.getConfigurationSection("Worlds."+world.getName()+".gamemodes."+gm.toString().toLowerCase()+".infoSigns"); if(cs != null) { for(String s : cs.getValues(false).keySet()) { Location loc = new Location(world,cs.getDouble(s+".X"),cs.getDouble(s+".Y"),cs.getDouble(s+".Z")); Block b = world.getBlockAt(loc); if(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST)) { signs.add((Sign)b.getState()); } } } } catch(Exception ex) { } return signs; } public boolean getPreventItemDropOnDeath(World world,Gamemode gm) { return config.getBoolean("Worlds."+world.getName()+".gamemodes."+gm.toString().toLowerCase()+".player.preventItemDropOnDeath",true); } public boolean getPreventItemDrop(World world,Gamemode gm) { return config.getBoolean("Worlds."+world.getName()+".gamemodes."+gm.toString().toLowerCase()+".player.preventItemDrop",true); } public void addFlag(Sign sign) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flags"); if(cs != null) { String flagName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(flagName+".X",sign.getLocation().getX()); cs.set(flagName+".Y",sign.getLocation().getY()); cs.set(flagName+".Z",sign.getLocation().getZ()); this.save(); } } public void removeFlag(Sign sign) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flags"); if(cs != null) { String flagName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(flagName+".X",null); cs.set(flagName+".Y",null); cs.set(flagName+".Z",null); cs.set(flagName,null); this.save(); } } public List<Sign> getFlags(World world) { List<Sign> signs = new ArrayList<Sign>(); try { ConfigurationSection cs = config.getConfigurationSection("Worlds."+world.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flags"); if(cs != null) { for(String s : cs.getValues(false).keySet()) { Location loc = new Location(world,cs.getDouble(s+".X"),cs.getDouble(s+".Y"),cs.getDouble(s+".Z")); Block b = world.getBlockAt(loc); if(b.getType().equals(Material.WALL_SIGN)) { signs.add((Sign)b.getState()); } } } } catch(Exception ex) { } return signs; } public double getFlagCaptureDistance(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flagCaptureDistance",10d); } public double getFlagCaptureSpeed(World w) //% per second { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flagCaptureSpeed",10d); } public double getFlagCaptureAcceleration(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".flagCaptureAccelerationPerPerson",1.2d); } public double getPointlossPerFlagPerSecond(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".pointlossPerFlagPerSecond",1.0d); } public boolean getLosePointsWhenEnemyHasLessThanHalfFlags(World w) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+Gamemode.Conquest.toString().toLowerCase()+".losePointsWhenEnemyHasLessThanHalfFlags",false); } public boolean getAutobalance(World w,Gamemode gm) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gm.toString().toLowerCase()+".autobalance",true); } public double getRPGMaxSpeed() { return config.getDouble("GameProps.rpg.speed",1.5d); } public double getRPGAcceleration() { return config.getDouble("GameProps.rpg.accel",0.1d); } public double getRPGThrotle() { return config.getDouble("GameProps.rpg.throtle",0.1d); } public float getRPGExploStr() { return (float)config.getDouble("GameProps.rpg.exploStr",3.0d); } public double getRPGLifeTime() { return config.getDouble("GameProps.rpg.lifeTime",10.0d); } public float getRPGKillRangeMod() { return (float)config.getDouble("GameProps.rpg.killRangeMod",0.5d); } public double getIMSTriggerDist() { return config.getDouble("GameProps.ims.triggerDist",12.0d); } public int getIMSShots() { return config.getInt("GameProps.ims.shots",6); } public double getIMSGrenadeSpeed() { return config.getDouble("GameProps.ims.grenade.speed",1.0d); } public double getIMSGrenadePeekHeight() { return config.getDouble("GameProps.ims.grenade.height",20.0d); } public float getIMSGrenadeExploStr() { return (float)config.getDouble("GameProps.ims.grenade.exploStr",4.0d); } public List<Sign> getRadioStations(World world) { List<Sign> signs = new ArrayList<Sign>(); try { ConfigurationSection cs = config.getConfigurationSection("Worlds."+world.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".radioStations"); if(cs != null) { for(String s : cs.getValues(false).keySet()) { Location loc = new Location(world,cs.getDouble(s+".X"),cs.getDouble(s+".Y"),cs.getDouble(s+".Z")); Block b = world.getBlockAt(loc); if(b.getType().equals(Material.WALL_SIGN)) { signs.add((Sign)b.getState()); } } } } catch(Exception ex) { } return signs; } public void addRadioStation(Sign sign) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".radioStations"); if(cs != null) { String rsName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(rsName+".X",sign.getLocation().getX()); cs.set(rsName+".Y",sign.getLocation().getY()); cs.set(rsName+".Z",sign.getLocation().getZ()); this.save(); } } public void removeRadioStation(Sign sign) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+sign.getWorld().getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".radioStations"); if(cs != null) { String rsName = Integer.toString(sign.getLocation().getBlockX())+","+Integer.toString(sign.getLocation().getBlockY())+","+Integer.toString(sign.getLocation().getBlockZ()); cs.set(rsName+".X",null); cs.set(rsName+".Y",null); cs.set(rsName+".Z",null); cs.set(rsName,null); this.save(); } } public double getRadioStationDestructTime(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".destructTime",10d); } public double getDefenderInnerSpawnRadius(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".defenderInnerSpawnRadius",5d); } public double getDefenderOuterSpawnRadius(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".defenderOuterSpawnRadius",10d); } public double getAttackerInnerSpawnRadius(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".attackerInnerSpawnRadius",30d); } public double getAttackerOuterSpawnRadius(World w) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+Gamemode.Rush.toString().toLowerCase()+".attackerOuterSpawnRadius",70d); } public double getSentryMissileSpeed() { return config.getDouble("GameProps.sentry.missileSpeed",2D); } public float getSentryMissileExploStr() { return (float)config.getDouble("GameProps.sentry.missileExploStr",3.0d); } public float getSentryMissileKillRangeMod() { return (float)config.getDouble("GameProps.sentry.missileKillRangeMod",0.5d); } public double getC4ThrowSpeed() { return config.getDouble("GameProps.C4.throwSpeed",0.5d); } public void addNewProtectedRegion(Location pos1, Location pos2) { ConfigurationSection cs = config.getConfigurationSection("Worlds."+pos1.getWorld().getName()+".protections"); String prefix = Integer.toString(pos1.getBlockX())+","+Integer.toString(pos1.getBlockY())+","+Integer.toString(pos1.getBlockZ()); cs.set(prefix+".pos1.X", pos1.getX()); cs.set(prefix+".pos1.Y", pos1.getY()); cs.set(prefix+".pos1.Z", pos1.getZ()); cs.set(prefix+".pos2.X", pos2.getX()); cs.set(prefix+".pos2.Y", pos2.getY()); cs.set(prefix+".pos2.Z", pos2.getZ()); cs.set(prefix+".enabled",true); this.save(); List<ProtectedArea> lpa = new ArrayList<ProtectedArea>(); Set<String> keys = cs.getValues(false).keySet(); for(String key : keys) { double x1 = cs.getDouble(key+".pos1.X"); double y1 = cs.getDouble(key+".pos1.Y"); double z1 = cs.getDouble(key+".pos1.Z"); double x2 = cs.getDouble(key+".pos2.X"); double y2 = cs.getDouble(key+".pos2.Y"); double z2 = cs.getDouble(key+".pos2.Z"); if(this.isProtectionEnabled(cs,key)) { lpa.add(new ProtectedArea(new Location(pos1.getWorld(), x1, y1, z1), new Location(pos1.getWorld(), x2, y2, z2))); } } this.protectionRegions.put(pos1.getWorld(), lpa); } public boolean getC4allowedInsideProtection() { return config.getBoolean("GameProps.C4.allowedInsideProtection",false); } public boolean getM18allowedInsideProtection() { return config.getBoolean("GameProps.M18.allowedInsideProtection",false); } public boolean getHandGrenadeAllowedInsideProtection() { return config.getBoolean("GameProps.handGrenade.allowedInsideProtection",true); } public boolean getIMSAllowedInsideProtection() { return config.getBoolean("GameProps.ims.allowedInsideProtection",false); } public boolean isFalldamageActive(World w, Gamemode gm) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gm.toString().toLowerCase()+".player.enableFallDamage",true); } public boolean isHungerActive(World w, Gamemode gm) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gm.toString().toLowerCase()+".player.enableHunger",false); } public double getAmmoResupplyRange() { return config.getDouble("GameProps.ammoResupply.range", 4.0d); } public double getAmmoResupplySpeed() { return config.getDouble("GameProps.ammoResupply.speed", 4.0d); } public int getAmmoResupplyAmount() { return config.getInt("GameProps.ammoResupply.amount", 20); } public double getFlamethrowerIgnitionDist() { return config.getDouble("GameProps.flamethrower.ignitionDist", 4.0d); } public int getFlamethrowerDirectDamage() { return config.getInt("GameProps.flamethrower.directDamage",3); } public double getMedigunHealingDist() { return config.getDouble("GameProps.medigun.healingDist", 12.0d); } public double getMedigunHealingRate() { return config.getDouble("GameProps.medigun.healingRate",1.0d); } public boolean isMpvpEnabled(World w) { return config.getBoolean("Worlds."+w.getName()+".mpvp",false); } public String getLangFile() { return config.getString("GameProps.lang","EN_us.lang"); } public boolean isDebuging() { return config.getBoolean("debug",true); } public double getKillassistPointModifier() { return config.getDouble("GameProps.killassist.pointsPerPercent",1d); } public boolean isMinimapEnabled(World w) { return config.getBoolean("Worlds."+w.getName()+".minimapEnabled",true); } public double getSniperDamage(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.sniperDamage",10d); } public double getGeneralDamage(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.generalDamage",5d); } public double getHeadshotDamageMultiplier(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.headshotMultiplier",2d); } public double getLegshotDamageMultiplier(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.legshotMultiplier",0.5d); } public double getCritProbability(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.critProbability",0.02d); } public double getCritMultiplier(World w, Gamemode g) { return config.getDouble("Worlds."+w.getName()+".gamemodes."+g.toString().toLowerCase()+".weapon.critMultiplier",2.0d); } public boolean canEvironmentBeDamaged(Gamemode gmode, World w) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gmode.toString().toLowerCase()+".environment.canBeDamaged",true) && config.getBoolean("Worlds."+w.getName()+".environment.canBeDamaged",true); } public boolean canExlosionsDamageEnvironment(Gamemode gmode, World w) { return config.getBoolean("Worlds."+w.getName()+".gamemodes."+gmode.toString().toLowerCase()+".environment.doExplosionsDamageEnvironment",true) && config.getBoolean("Worlds."+w.getName()+".environment.doExplosionsDamageEnvironment",true); } public boolean canEvironmentBeDamaged(World w) { return config.getBoolean("Worlds."+w.getName()+".environment.canBeDamaged",true); } }
package DataAccess.Implementations; import DataAccess.ConnectionFactory; import DataAccess.Interfaces.ZoneDaoInterface; import Elements.Seating; import Elements.Zone; import java.sql.*; public class ZoneDao extends BaseDao<Zone> implements ZoneDaoInterface { @Override public Zone extractFromResultSet(ResultSet rs) throws SQLException{ Zone zone = new Zone(); zone.setId(rs.getInt("id")); zone.setDiscountPercent(rs.getInt("discount_percent")); zone.setName(rs.getString("name")); return zone; } public int insertZone(Zone zone) throws SQLException{ Connection connection = ConnectionFactory.getConnection(); PreparedStatement statement = null; String query = "INSERT INTO zone (name, discount_percent) VALUES (?, ?)"; statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); statement.setString(1, zone.getName()); statement.setInt(2, zone.getDiscountPercent()); int rowsAffected = statement.executeUpdate(); if(rowsAffected == 0){ throw new SQLException("No rows affected"); } try(ResultSet generatedKeys = statement.getGeneratedKeys()){ if (generatedKeys.next()){ return generatedKeys.getInt("id"); } else { throw new SQLException("No id obtained"); } } } @Override public Zone findById(int id) { Connection connection = ConnectionFactory.getConnection(); Statement statement = null; try { statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM zone WHERE id=" + id); connection.close(); if (resultSet.next()) return extractFromResultSet(resultSet); } catch (SQLException e) { e.printStackTrace(); } return null; } }
package org.eclipse.birt.data.engine.impl.group; import java.math.BigDecimal; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; public class DecimalGroupCalculator extends GroupCalculator { BigDecimal doubleStartValue; /** * * @param intervalStart * @param intervalRange * @throws BirtException */ public DecimalGroupCalculator( Object intervalStart, double intervalRange ) throws BirtException { super( intervalStart, intervalRange ); intervalRange = (intervalRange == 0 ? 1 : intervalRange); this.intervalRange = intervalRange; // If the value '-1',grouping interval doesn't work for negative categories .So I change the value to '-Double.MAX_VALUE'. if ( intervalStart == null ) doubleStartValue = new BigDecimal(-Double.MAX_VALUE ); else doubleStartValue = DataTypeUtil.toBigDecimal( intervalStart ); } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.impl.group.GroupCalculator#calculate(java.lang.Object) */ public Object calculate( Object value ) throws BirtException { if ( value == null ) { // If the value '-1',grouping interval doesn't work for negative categories .So I change the value to '-Double.MAX_VALUE'. return new BigDecimal( -Double.MAX_VALUE); } BigDecimal dValue = DataTypeUtil.toBigDecimal( value ); if ( dValue.compareTo( doubleStartValue ) < 0 ) { return new Double( -1 ); } else { dValue = dValue.subtract( doubleStartValue ); dValue = dValue.divide(new BigDecimal(intervalRange), 0, BigDecimal.ROUND_FLOOR ); return dValue; } } }
package acmi.l2.clientmod.io; import java.io.*; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.nio.charset.Charset; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; import static acmi.l2.clientmod.io.ByteUtil.*; @SuppressWarnings("unused") public class UnrealPackage implements Closeable { private static Charset defaultCharset = Charset.forName("EUC-KR"); public static Charset getDefaultCharset() { return defaultCharset; } public static void setDefaultCharset(Charset defaultCharset) { UnrealPackage.defaultCharset = defaultCharset; } public static final int UNREAL_PACKAGE_MAGIC = 0x9E2A83C1; public static final int VERSION_OFFSET = 4; public static final int LICENSEE_OFFSET = 6; public static final int PACKAGE_FLAGS_OFFSET = 8; public static final int NAME_COUNT_OFFSET = 12; public static final int NAME_OFFSET_OFFSET = 16; public static final int EXPORT_COUNT_OFFSET = 20; public static final int EXPORT_OFFSET_OFFSET = 24; public static final int IMPORT_COUNT_OFFSET = 28; public static final int IMPORT_OFFSET_OFFSET = 32; public static final int GUID_OFFSET = 36; public static final int GENERATIONS_OFFSET = 52; private RandomAccess file; private int version; private int licensee; private int flags; private List<NameEntry> names; private List<ExportEntry> exports; private List<ImportEntry> imports; private UUID uuid; private List<Generation> generations; public <T extends Context> UnrealPackage(String path, boolean readOnly, IOFactory<T> ioFactory, T context) throws IOException { this(new RandomAccessFile(path, readOnly, defaultCharset, ioFactory, context)); } public <T extends Context> UnrealPackage(File file, boolean readOnly, IOFactory<T> ioFactory, T context) throws IOException { this(new RandomAccessFile(file, readOnly, defaultCharset, ioFactory, context)); } public <T extends Context> UnrealPackage(String name, byte[] data, IOFactory<T> ioFactory, T context) throws IOException { this(new RandomAccessMemory(name, data, defaultCharset, ioFactory, context)); } public UnrealPackage(RandomAccess file) throws IOException { this.file = Objects.requireNonNull(file); file.setPosition(0); if (file.readInt() != UNREAL_PACKAGE_MAGIC) throw new IOException("Not a L2 package file."); version = file.readUnsignedShort(); licensee = file.readUnsignedShort(); flags = file.readInt(); readNameTable(); readImportTable(); readExportTable(); file.setPosition(GUID_OFFSET); byte[] uuidBytes = new byte[16]; file.readFully(uuidBytes); uuid = uuidFromBytes(uuidBytes); file.setPosition(GENERATIONS_OFFSET); int count = file.readInt(); List<Generation> tmp = new ArrayList<>(count); for (int i = 0; i < count; i++) tmp.add(new Generation(this, i, file.readInt(), file.readInt())); generations = Collections.unmodifiableList(tmp); } public RandomAccess getFile() { return file; } public String getPackageName() { return getFile().getName(); } public int getVersion() { return version; } public void setVersion(int version) throws IOException { file.setPosition(VERSION_OFFSET); file.writeShort(version); this.version = version; } public int getLicensee() { return licensee; } public void setLicensee(int licensee) throws IOException { file.setPosition(LICENSEE_OFFSET); file.writeShort(licensee); this.licensee = licensee; } public int getFlags() { return flags; } public void setFlags(int flags) throws IOException { file.setPosition(PACKAGE_FLAGS_OFFSET); file.writeInt(flags); this.flags = flags; } public UUID getGUID() { return uuid; } public void setGUID(UUID guid) throws IOException { file.setPosition(GUID_OFFSET); file.write(uuidToBytes(uuid)); this.uuid = guid; } public List<NameEntry> getNameTable() { return names; } private void readNameTable() throws IOException { file.setPosition(NAME_COUNT_OFFSET); int count = file.readInt(); file.setPosition(getNameTableOffset()); List<NameEntry> tmp = new ArrayList<>(count); for (int i = 0; i < count; i++) tmp.add(new NameEntry(this, i, file.readLine(), file.readInt())); names = Collections.unmodifiableList(tmp); } public List<ExportEntry> getExportTable() { return exports; } private void readExportTable() throws IOException { file.setPosition(EXPORT_COUNT_OFFSET); int count = file.readInt(); file.setPosition(getExportTableOffset()); List<ExportEntry> tmp = new ArrayList<>(count); for (int i = 0; i < count; i++) tmp.add(new ExportEntry(this, i, file.readCompactInt(), file.readCompactInt(), file.readInt(), file.readCompactInt(), file.readInt(), file.readCompactInt(), file.readCompactInt())); exports = Collections.unmodifiableList(tmp); } public List<ImportEntry> getImportTable() { return imports; } private void readImportTable() throws IOException { file.setPosition(IMPORT_COUNT_OFFSET); int count = file.readInt(); file.setPosition(getImportTableOffset()); List<ImportEntry> tmp = new ArrayList<>(count); for (int i = 0; i < count; i++) tmp.add(new ImportEntry(this, i, file.readCompactInt(), file.readCompactInt(), file.readInt(), file.readCompactInt())); imports = Collections.unmodifiableList(tmp); } public UUID getUUID() { return uuid; } public void setUUID(UUID uuid) throws IOException { file.setPosition(GUID_OFFSET); file.write(uuidToBytes(uuid)); this.uuid = uuid; } public List<Generation> getGenerations() { return generations; } public String toString() { return getPackageName(); } public String nameReference(int index) { return getNameTable().get(index).getName(); } public int nameReference(String name) { Optional<NameEntry> entry = getNameTable().stream() .filter(e -> e.getName().equalsIgnoreCase(name)) .findAny(); return entry.isPresent() ? entry.get().getIndex() : -1; } public Entry objectReference(int ref) { if (ref > 0) return getExportTable().get(ref - 1); else if (ref < 0) return getImportTable().get(-ref - 1); else return null; } public Entry getAt(int index) { return objectReference(index); } public int objectReference(String name, String clazz) { int ref; if ((ref = importReference(name, clazz)) != 0) return ref; if ((ref = exportReference(name, clazz)) != 0) return ref; return 0; } public int importReference(String name, String clazz) { try { return getImportTable().stream() .filter(entry -> entry.getObjectFullName().equalsIgnoreCase(name)) .findAny() .get() .getObjectReference(); } catch (NoSuchElementException ignore) { return 0; } } public int exportReference(String name, String clazz) { try { return getExportTable().stream() .filter(entry -> entry.getObjectInnerFullName().equalsIgnoreCase(name)) .findAny() .get() .getObjectReference(); } catch (NoSuchElementException ignore) { return 0; } } public void updateNameTable(Consumer<List<NameEntry>> transformation) throws IOException { List<NameEntry> nameTable = new ArrayList<>(getNameTable()); transformation.accept(nameTable); int newNameTablePos = getDataEndOffset(); file.setPosition(newNameTablePos); writeNameTable(nameTable); int newImportTablePos = file.getPosition(); writeImportTable(getImportTable()); int newExportTablePos = file.getPosition(); writeExportTable(getExportTable()); file.trimToPosition(); file.setPosition(NAME_COUNT_OFFSET); file.writeInt(nameTable.size()); file.setPosition(NAME_OFFSET_OFFSET); file.writeInt(newNameTablePos); file.setPosition(EXPORT_OFFSET_OFFSET); file.writeInt(newExportTablePos); file.setPosition(IMPORT_OFFSET_OFFSET); file.writeInt(newImportTablePos); readNameTable(); } public void updateImportTable(Consumer<List<ImportEntry>> transformation) throws IOException { List<ImportEntry> importTable = new ArrayList<>(getImportTable()); transformation.accept(importTable); file.setPosition(getImportTableOffset()); writeImportTable(importTable); int newExportTablePos = file.getPosition(); writeExportTable(getExportTable()); file.trimToPosition(); file.setPosition(EXPORT_OFFSET_OFFSET); file.writeInt(newExportTablePos); file.setPosition(IMPORT_COUNT_OFFSET); file.writeInt(importTable.size()); readImportTable(); } public void addNameEntries(Map<String, Integer> names) throws IOException { updateNameTable(nameTable -> names.forEach((k, v) -> { NameEntry entry = new NameEntry(null, 0, k, v); if (!nameTable.contains(entry)) nameTable.add(entry); })); } public void updateNameEntry(int index, String newName, int newFlags) throws IOException { updateNameTable(nameTable -> { nameTable.remove(index); nameTable.add(index, new NameEntry(this, index, newName, newFlags)); }); } public void addImportEntries(Map<String, String> imports, boolean force) throws IOException { Map<String, Integer> namesToAdd = new HashMap<>(); imports.forEach((k, v) -> { String[] namePath = k.split("\\."); String[] classPath = v.split("\\."); Arrays.stream(namePath) .filter(s -> nameReference(s) == -1) .forEach(s -> namesToAdd.put(s, PACKAGE_FLAGS)); Arrays.stream(classPath) .filter(s -> nameReference(s) == -1) .forEach(s -> namesToAdd.put(s, PACKAGE_FLAGS)); }); addNameEntries(namesToAdd); updateImportTable(importTable -> { for (Map.Entry<String, String> entry : imports.entrySet()) { String[] namePath = entry.getKey().split("\\."); String[] classPath = entry.getValue().split("\\."); int pckg = 0; ImportEntry importEntry; for (int i = 0; i < namePath.length - 1; i++) { importEntry = new ImportEntry(this, 0, nameReference("Core"), nameReference("Package"), pckg, nameReference(namePath[i])); if ((pckg = importTable.indexOf(importEntry)) == -1) { importTable.add(importEntry); pckg = importTable.size() - 1; } pckg = -(pckg + 1); } importEntry = new ImportEntry(this, 0, nameReference(classPath[0]), nameReference(classPath[1]), pckg, nameReference(namePath[namePath.length - 1])); if (force || importTable.indexOf(importEntry) == -1) importTable.add(importEntry); } }); } public void addExportEntry(String objectName, String objectClass, String objectSuperClass, byte[] data, int flags) throws IOException { Map<String, String> classes = new HashMap<>(); if (objectClass != null && objectReference(objectClass, "Core.Class") == 0) classes.put(objectClass, "Core.Class"); if (objectSuperClass != null && objectReference(objectSuperClass, "Core.Class") == 0) classes.put(objectClass, "Core.Class"); if (!classes.isEmpty()) addImportEntries(classes, false); Map<String, Integer> namesToAdd = new HashMap<>(); String[] namePath = objectName.split("\\."); Arrays.stream(namePath) .filter(s -> nameReference(s) == -1) .forEach(s -> namesToAdd.put(s, PACKAGE_FLAGS)); addNameEntries(namesToAdd); file.setPosition(getDataEndOffset()); List<ExportEntry> exportTable = new ArrayList<>(getExportTable()); int pckgInd = importReference("Core.Package", "Core.Class"); byte[] pckgData = compactIntToByteArray(nameReference("None")); int pckg = 0; ExportEntry exportEntry; for (int i = 0; i < namePath.length - 1; i++) { exportEntry = new ExportEntry(this, 0, pckgInd, 0, pckg, nameReference(namePath[i]), PACKAGE_FLAGS, pckgData.length, file.getPosition()); if ((pckg = exportTable.indexOf(exportEntry)) == -1) { exportTable.add(exportEntry); pckg = exportTable.size() - 1; file.write(pckgData); } pckg++; } exportEntry = new ExportEntry(this, 0, objectReference(objectClass, "Core.Class"), objectReference(objectSuperClass, "Core.Class"), pckg, nameReference(namePath[namePath.length - 1]), flags, data.length, file.getPosition()); if (exportTable.indexOf(exportEntry) == -1) { exportTable.add(exportEntry); file.write(data); } int nameTablePosition = file.getPosition(); writeNameTable(getNameTable()); int importTablePosition = file.getPosition(); writeImportTable(getImportTable()); int exportTablePosition = file.getPosition(); writeExportTable(exportTable); file.setPosition(NAME_OFFSET_OFFSET); file.writeInt(nameTablePosition); file.setPosition(EXPORT_COUNT_OFFSET); file.writeInt(exportTable.size()); file.setPosition(EXPORT_OFFSET_OFFSET); file.writeInt(exportTablePosition); file.setPosition(IMPORT_OFFSET_OFFSET); file.writeInt(importTablePosition); readNameTable(); readImportTable(); readExportTable(); } // public void renameExport(String nameSrc, String nameDst) throws IOException { // if (objectReference(nameSrc) <= 0){ // log.log(Level.WARNING, "ExportEntry not found: "+nameSrc); // return; // if (objectReference(nameDst) != 0){ // log.log(Level.WARNING, "Entry already exist: "+nameDst); // return; // List<String> namesToAdd = new ArrayList<>(); // String[] namePath = nameDst.split("\\."); // if (namePath.length > 1 && objectReference("Core.Package") == 0) // addImportEntries(Collections.singletonMap("Core.Package", "Core.Class")); // for (String s : namePath) // if (nameReference(s) == -1) // namesToAdd.add(s); // String[] newNames = namesToAdd.toArray(new String[namesToAdd.size()]); // addNameEntries(newNames); // List<NameEntry> nameTable = getNameTable(); // List<ImportEntry> importTable = getImportTable(); // file.setPosition(getDataEndOffset()); // List<ExportEntry> exportTable = new ArrayList<>(getExportTable()); // int pckgInd = objectReference("Core.Package"); // byte[] pckgData = L2RandomAccessFile.compactIntToByteArray(getNameTable().indexOf(new NameEntry("None"))); // int pckg = 0; // ExportEntry exportEntry; // for (int i = 0; i < namePath.length - 1; i++) { // exportEntry = new ExportEntry( // pckgInd, // pckg, // nameReference(namePath[i]), // RF_Public | RF_LoadForServer | RF_LoadForEdit, // pckgData.length, file.getPosition()); // if ((pckg = exportTable.indexOf(exportEntry)) == -1) { // exportTable.add(exportEntry); // pckg = exportTable.size() - 1; // file.write(pckgData); // log.log(Level.INFO, "ExportEntry added: "+exportEntry); // pckg++; // for (ExportEntry entry : exportTable) { // if (entry.getAbsoluteName().equalsIgnoreCase(nameSrc)) { // log.log(Level.INFO, "ExportEntry renamed: "+entry); // entry.objectPackage = pckg; // entry.objectName = nameReference(namePath[namePath.length - 1]); // //log.log(Level.INFO, "New ExportEntry name: "+entry); // break; // int nameTablePosition = file.getPosition(); // writeNameTable(nameTable); // int importTablePosition = file.getPosition(); // writeImportTable(importTable); // int exportTablePosition = file.getPosition(); // writeExportTable(exportTable); // setNameTableOffset(nameTablePosition); // setExportTableOffset(exportTablePosition); // setExportTableCount(exportTable.size()); // setImportTableOffset(importTablePosition); // names = null; // imports = null; // exports = null; // public void removeExport(String className) throws IOException{ // if (objectReference("Core.Package") == 0) // addImportEntries(Collections.singletonMap("Core.Package", "Core.Class"), false); // int pckgInd = objectReference("Core.Package"); // byte[] pckgData = compactIntToByteArray(nameReference("None")); // List<ExportEntry> exportTable = getExportTable(); // for (ExportEntry entry : exportTable){ // if (entry.getObjectClass().getObjectFullName().equalsIgnoreCase(className)){ // entry.objectClass = pckgInd; // entry.objectSuperClass = 0; // entry.objectFlags = ObjectFlag.getFlags(ObjectFlag.Public, ObjectFlag.LoadForServer, ObjectFlag.LoadForEdit); // entry.setObjectRawData(pckgData, false); // file.setPosition(getExportTableOffset()); // writeExportTable(exportTable); // exports = null; public void renameImport(int index, String importDst) throws IOException { addImportEntries( Collections.singletonMap(importDst, getImportTable().get(index).getFullClassName()), true ); updateImportTable(importTable -> importTable.set(index, importTable.remove(importTable.size() - 1))); } public void changeImportClass(int index, String importDst) throws IOException { String[] clazz = importDst.split("\\."); if (clazz.length != 2) throw new IllegalArgumentException("Format: Package.Class"); addNameEntries(Arrays.stream(clazz) .filter(s -> nameReference(s) == -1) .collect(Collectors.toMap(v -> v, v -> PACKAGE_FLAGS))); updateImportTable(importTable -> { ImportEntry entry = importTable.get(index); entry.classPackage = nameReference(clazz[0]); entry.className = nameReference(clazz[1]); }); } private OutputStream fileOutputStream = new OutputStream() { @Override public void write(int b) throws IOException { file.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { file.write(b, off, len); } }; private void writeNameTable(List<NameEntry> nameTable) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutput buffer = new DataOutputStream(baos, file.getCharset()); for (NameEntry entry : nameTable) { buffer.writeLine(entry.getName()); buffer.writeInt(entry.getFlags()); } baos.writeTo(fileOutputStream); } private void writeImportTable(List<ImportEntry> importTable) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutput buffer = new DataOutputStream(baos, file.getCharset()); for (ImportEntry entry : importTable) { buffer.writeCompactInt(entry.classPackage); buffer.writeCompactInt(entry.className); buffer.writeInt(entry.objectPackage); buffer.writeCompactInt(entry.objectName); } baos.writeTo(fileOutputStream); } private void writeExportTable(List<ExportEntry> exportTable) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutput buffer = new DataOutputStream(baos, file.getCharset()); for (ExportEntry entry : exportTable) { buffer.writeCompactInt(entry.objectClass); buffer.writeCompactInt(entry.objectSuperClass); buffer.writeInt(entry.objectPackage); buffer.writeCompactInt(entry.objectName); buffer.writeInt(entry.objectFlags); buffer.writeCompactInt(entry.size); buffer.writeCompactInt(entry.offset); } baos.writeTo(fileOutputStream); } public int getNameTableOffset() throws IOException { file.setPosition(NAME_OFFSET_OFFSET); return file.readInt(); } public int getExportTableOffset() throws IOException { file.setPosition(EXPORT_OFFSET_OFFSET); return file.readInt(); } public int getImportTableOffset() throws IOException { file.setPosition(IMPORT_OFFSET_OFFSET); return file.readInt(); } public int getDataStartOffset() { return getExportTable().stream() .filter(entry -> entry.getSize() > 0) .mapToInt(ExportEntry::getOffset) .min() .orElseThrow(() -> new IllegalStateException("Data block is empty")); } public int getDataEndOffset() { return getExportTable().stream() .filter(entry -> entry.getSize() > 0) .mapToInt(entry -> entry.getOffset() + entry.getSize()) .max() .orElseThrow(() -> new IllegalStateException("Data block is empty")); } @Override public void close() throws IOException { file.close(); } private static abstract class PackageEntry { private final UnrealPackage unrealPackage; private final int index; protected PackageEntry(UnrealPackage unrealPackage, int index) { this.unrealPackage = unrealPackage; this.index = index; } public UnrealPackage getUnrealPackage() { return unrealPackage; } public int getIndex() { return index; } } public static final class Generation extends PackageEntry { private final int exportCount; private final int importCount; public Generation(UnrealPackage unrealPackage, int index, int exportCount, int importCount) { super(unrealPackage, index); this.exportCount = exportCount; this.importCount = importCount; } public int getExportCount() { return exportCount; } public int getNameCount() { return importCount; } @Override public String toString() { return "Generation[" + "exportCount=" + exportCount + ", importCount=" + importCount + ']'; } } public static final class NameEntry extends PackageEntry { private final String name; private int flags; private NameEntry(UnrealPackage unrealPackage, int index, String name, int flags) { super(unrealPackage, index); this.name = Objects.requireNonNull(name); this.flags = flags; } public String getName() { return name; } public int getFlags() { return flags; } public String toString() { return name; } public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } NameEntry nameEntry = (NameEntry) o; return name.equalsIgnoreCase(nameEntry.name); } public int hashCode() { return name.hashCode(); } public NameEntry previous() { return getUnrealPackage().getNameTable().get(getIndex() - 1); } public NameEntry next() { return getUnrealPackage().getNameTable().get(getIndex() + 1); } } public static abstract class Entry extends PackageEntry { protected final int objectPackage; protected final int objectName; private Reference<String> innerName = new SoftReference<>(null); protected Entry(UnrealPackage unrealPackage, int index, int objectPackage, int objectName) { super(unrealPackage, index); this.objectPackage = objectPackage; this.objectName = objectName; } public Entry getObjectPackage() { return getUnrealPackage().objectReference(objectPackage); } public NameEntry getObjectName() { return getUnrealPackage().getNameTable().get(objectName); } public String getObjectInnerFullName() { String str = innerName.get(); if (str == null) { Entry pckg = getObjectPackage(); str = pckg == null ? getObjectName().getName() : pckg.getObjectInnerFullName() + '.' + getObjectName().getName(); innerName = new SoftReference<>(str); } return str; } public String getObjectFullName() { return getObjectInnerFullName(); } public abstract String getFullClassName(); @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Entry)) return false; Entry entry = (Entry) o; return getObjectFullName().equalsIgnoreCase(entry.getObjectFullName()) && getFullClassName().equalsIgnoreCase(entry.getFullClassName()); } @Override public int hashCode() { return Objects.hash(getObjectFullName(), getFullClassName()); } public String toString() { return getObjectFullName(); } } public static final class ExportEntry extends Entry { private int objectClass; private int objectSuperClass; private int objectFlags; private int size; private int offset; private Reference<String> fullName = new SoftReference<>(null); private ExportEntry(UnrealPackage unrealPackage, int index, int objectClass, int objectSuperClass, int objectPackage, int objectName, int objectFlags, int size, int offset) { super(unrealPackage, index, objectPackage, objectName); this.objectClass = objectClass; this.objectSuperClass = objectSuperClass; this.objectFlags = objectFlags; this.size = size; this.offset = offset; } public int getObjectReference() { return getIndex() + 1; } public Entry getObjectClass() { return getUnrealPackage().objectReference(objectClass); } public Entry getObjectSuperClass() { return getUnrealPackage().objectReference(objectSuperClass); } @Override public String getFullClassName() { return getObjectClass() != null ? getObjectClass().getObjectFullName() : "Core.Class"; } public int getObjectFlags() { return objectFlags; } public int getSize() { return size; } public int getOffset() { return offset; } public byte[] getObjectRawData() throws IOException { if (getSize() == 0) return new byte[0]; byte[] raw = new byte[size]; getUnrealPackage().file.setPosition(offset); getUnrealPackage().file.readFully(raw); return raw; } public byte[] getObjectRawDataExternally() throws IOException { if (getSize() == 0) return new byte[0]; try (RandomAccess ra = getUnrealPackage().getFile().openNewSession(true)) { byte[] data = new byte[getSize()]; ra.setPosition(getOffset()); ra.readFully(data); return data; } } public void setObjectRawData(byte[] data) throws IOException { setObjectRawData(data, true); } public void setObjectRawData(byte[] data, boolean writeExportTable) throws IOException { if (data.length <= getSize()) { getUnrealPackage().file.setPosition(getOffset()); getUnrealPackage().file.write(data); if (data.length != getSize()) { size = data.length; if (writeExportTable) { getUnrealPackage().file.setPosition(getUnrealPackage().getExportTableOffset()); getUnrealPackage().writeExportTable(getUnrealPackage().getExportTable()); } } } else { // //clear // getUnrealPackage().file.setPosition(getOffset()); // getUnrealPackage().file.write(new byte[getSize()]); getUnrealPackage().file.setPosition(getUnrealPackage().getDataEndOffset()); offset = getUnrealPackage().file.getPosition(); size = data.length; getUnrealPackage().file.write(data); int nameTablePosition = getUnrealPackage().file.getPosition(); getUnrealPackage().writeNameTable(getUnrealPackage().getNameTable()); int importTablePosition = getUnrealPackage().file.getPosition(); getUnrealPackage().writeImportTable(getUnrealPackage().getImportTable()); int exportTablePosition = getUnrealPackage().file.getPosition(); getUnrealPackage().writeExportTable(getUnrealPackage().getExportTable()); getUnrealPackage().file.setPosition(NAME_OFFSET_OFFSET); getUnrealPackage().file.writeInt(nameTablePosition); getUnrealPackage().file.setPosition(EXPORT_OFFSET_OFFSET); getUnrealPackage().file.writeInt(exportTablePosition); getUnrealPackage().file.setPosition(IMPORT_OFFSET_OFFSET); getUnrealPackage().file.writeInt(importTablePosition); } } @Override public String getObjectFullName() { String str = fullName.get(); if (str == null) { str = getUnrealPackage().getPackageName() + "." + getObjectInnerFullName(); fullName = new SoftReference<>(str); } return str; } @Override public String toString() { return getObjectInnerFullName(); } public ExportEntry previous() { return getUnrealPackage().getExportTable().get(getIndex() - 1); } public ExportEntry next() { return getUnrealPackage().getExportTable().get(getIndex() + 1); } } public static final class ImportEntry extends Entry { private int classPackage; private int className; private Reference<String> fullClassName = new SoftReference<>(null); private ImportEntry(UnrealPackage unrealPackage, int index, int classPackage, int className, int objectPackage, int objectName) { super(unrealPackage, index, objectPackage, objectName); this.classPackage = classPackage; this.className = className; } public int getObjectReference() { return -(getIndex() + 1); } public NameEntry getClassPackage() { return getUnrealPackage().getNameTable().get(classPackage); } public NameEntry getClassName() { return getUnrealPackage().getNameTable().get(className); } public String getFullClassName() { String str = fullClassName.get(); if (str == null) { NameEntry pckg = getClassPackage(); str = pckg == null ? getClassName().getName() : pckg.getName() + '.' + getClassName().getName(); fullClassName = new SoftReference<>(str); } return str; } public ImportEntry previous() { return getUnrealPackage().getImportTable().get(getIndex() - 1); } public ImportEntry next() { return getUnrealPackage().getImportTable().get(getIndex() + 1); } } public enum ObjectFlag { /** * Object is transactional. */ Transactional, /** * Object is not reachable on the object graph. */ Unreachable, /** * Object is visible outside its package. */ Public, /** * Temporary import tag in load/save. */ TagImp, /** * Temporary export tag in load/save. */ TagExp, /** * Modified relative to source files. */ SourceModified, /** * Check during garbage collection. */ TagGarbage, Private, Flag8, /** * During load, indicates object needs loading. */ NeedLoad, /** * A hardcoded name which should be syntaxhighlighted. */ HighlightedName, /** * In a singular function. */ InSingularFunc, /** * Suppressed log name. */ Suppress, /** * Within an EndState call. */ InEndState, /** * Don't save object. */ Transient, /** * Data is being preloaded from file. */ PreLoading, /** * In-file load for client. */ LoadForClient, /** * In-file load for client. */ LoadForServer, /** * In-file load for client. */ LoadForEdit, /** * Keep object around for editing even if unreferenced. */ Standalone, /** * Don't load this object for the game client. */ NotForClient, /** * Don't load this object for the game server. */ NotForServer, /** * Don't load this object for the editor. */ NotForEdit, /** * Object Destroy has already been called. */ Destroyed, /** * Object needs to be postloaded. */ NeedPostLoad, /** * Has execution stack. */ HasStack, /** * Native (UClass only). */ Native, /** * Marked (for debugging). */ Marked, /** * ShutdownAfterError called. */ ErrorShutdown, /** * For debugging Serialize calls. */ DebugPostLoad, /** * For debugging Serialize calls. */ DebugSerialize, /** * For debugging Destroy calls. */ DebugDestroy; private int mask; ObjectFlag() { this.mask = 1 << ordinal(); } public int getMask() { return mask; } @Override public String toString() { return "RF_" + name(); } public static Collection<ObjectFlag> getFlags(int flags) { return Arrays.stream(values()) .filter(e -> (e.getMask() & flags) != 0) .collect(Collectors.toList()); } public static int getFlags(ObjectFlag... flags) { int v = 0; for (ObjectFlag flag : flags) v |= flag.getMask(); return v; } } private static final int PACKAGE_FLAGS = ObjectFlag.getFlags( ObjectFlag.Public, ObjectFlag.LoadForClient, ObjectFlag.LoadForServer, ObjectFlag.LoadForEdit); public enum PackageFlag { /** * Allow downloading package */ AllowDownload(0), /** * Purely optional for clients */ ClientOptional(1), /** * Only needed on the server side */ ServerSideOnly(2), /** * Loaded from linker with broken import links */ BrokenLinks(3), /** * Not trusted */ Unsecure(4), /** * Client needs to download this package */ Need(15); private int mask; PackageFlag(int bit) { this.mask = 1 << bit; } public int getMask() { return mask; } @Override public String toString() { return "PKG_" + name(); } public static Collection<PackageFlag> getFlags(int flags) { return Arrays.stream(values()) .filter(e -> (e.getMask() & flags) != 0) .collect(Collectors.toList()); } public static int getFlags(PackageFlag... flags) { int v = 0; for (PackageFlag flag : flags) v |= flag.getMask(); return v; } } }
package VASL.build.module.map; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import VASL.build.module.map.boardPicker.ASLBoard; import VASL.build.module.map.boardPicker.Overlay; import VASSAL.build.AbstractBuildable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.ServerConnection; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.command.Command; import VASSAL.configure.StringConfigurer; import VASSAL.tools.PropertiesEncoder; public class BoardVersionChecker extends AbstractBuildable implements GameComponent, PropertyChangeListener { private String boardVersionURL; private String overlayVersionURL; private String boardPageURL; private Map map; private Properties boardVersions; private Properties overlayVersions; private static final String BOARD_VERSION_URL = "boardVersionURL"; private static final String OVERLAY_VERSION_URL = "overlayVersionURL"; private static final String BOARD_PAGE_URL = "boardPageURL"; private static final String BOARD_VERSIONS = "boardVersions"; private static final String OVERLAY_VERSIONS = "overlayVersions"; public String[] getAttributeNames() { return new String[]{BOARD_VERSION_URL, OVERLAY_VERSION_URL, BOARD_PAGE_URL}; } public String getAttributeValueString(String key) { if (BOARD_VERSION_URL.equals(key)) { return boardVersionURL; } else if (OVERLAY_VERSION_URL.equals(key)) { return overlayVersionURL; } else if (BOARD_PAGE_URL.equals(key)) { return boardPageURL; } return null; } public void setAttribute(String key, Object value) { if (BOARD_VERSION_URL.equals(key)) { boardVersionURL = (String) value; } else if (OVERLAY_VERSION_URL.equals(key)) { overlayVersionURL = (String) value; } else if (BOARD_PAGE_URL.equals(key)) { boardPageURL = (String) value; } } public void addTo(Buildable parent) { map = (Map) parent; GameModule.getGameModule().getGameState().addGameComponent(this); GameModule.getGameModule().getServer().addPropertyChangeListener(ServerConnection.CONNECTED, this); GameModule.getGameModule().getPrefs().addOption(null, new StringConfigurer(BOARD_VERSIONS, null)); Properties p = readVersionList((String) GameModule.getGameModule().getPrefs().getValue(BOARD_VERSIONS)); if (p != null) { boardVersions = p; } GameModule.getGameModule().getPrefs().addOption(null, new StringConfigurer(OVERLAY_VERSIONS, null)); p = readVersionList((String) GameModule.getGameModule().getPrefs().getValue(OVERLAY_VERSIONS)); if (p != null) { overlayVersions = p; } } public Command getRestoreCommand() { return null; } public void setup(boolean gameStarting) { if (gameStarting) { if (boardVersions != null) { String info = "Using board(s): "; for (Board board : map.getBoards()) { ASLBoard b = (ASLBoard) board; info += b.getName() + "(v" + b.getVersion() + ") "; } GameModule.getGameModule().warn(info); } if (boardVersions != null) { Vector obsolete = new Vector(); for (Board board : map.getBoards()) { ASLBoard b = (ASLBoard) board; String availableVersion = boardVersions.getProperty(b.getName(), b.getVersion()); if (!availableVersion.equals(b.getVersion())) { obsolete.addElement(b.getName()); } } String msg = null; if (obsolete.size() == 1) { String name = (String) obsolete.firstElement(); msg = "Version " + boardVersions.getProperty(name) + " of board " + name + " is now available.\n"+boardPageURL; } else if (obsolete.size() > 1) { StringBuffer buff = new StringBuffer(); for (int i = 0,j = obsolete.size(); i < j; ++i) { buff.append((String) obsolete.elementAt(i)); if (i < j - 2) { buff.append(", "); } else if (i < j - 1) { buff.append(" and "); } } msg = "New versions of boards " + buff + " are available.\n"+boardPageURL; } if (msg != null) { final String message = msg; Runnable runnable = new Runnable() { public void run() { JOptionPane.showMessageDialog(map.getView().getTopLevelAncestor(), message); } }; SwingUtilities.invokeLater(runnable); } } if (overlayVersions != null) { Vector obsolete = new Vector(); for (Board board : map.getBoards()) { ASLBoard b = (ASLBoard) board; for (Enumeration e2 = b.getOverlays(); e2.hasMoreElements();) { Overlay o = (Overlay) e2.nextElement(); if (o.getClass().equals(Overlay.class)) { // Don't check for SSROverlays String name = o.getFile().getName(); String availableVersion = overlayVersions.getProperty(name, o.getVersion()); if (!availableVersion.equals(o.getVersion())) { obsolete.addElement(name); } } } } String msg = null; if (obsolete.size() == 1) { String name = (String) obsolete.firstElement(); msg = "Version " + overlayVersions.getProperty(name) + " of overlay " + name + " is now available.\n"+boardPageURL; } else if (obsolete.size() > 1) { StringBuffer buff = new StringBuffer(); for (int i = 0,j = obsolete.size(); i < j; ++i) { buff.append((String) obsolete.elementAt(i)); if (i < j - 2) { buff.append(", "); } else if (i < j - 1) { buff.append(" and "); } } msg = "New versions of overlays " + buff + " are available.\n"+boardPageURL; } if (msg != null) { final String message = msg; Runnable runnable = new Runnable() { public void run() { JOptionPane.showMessageDialog(map.getView().getTopLevelAncestor(), message); } }; SwingUtilities.invokeLater(runnable); } } } } private Properties readVersionList(String s) { Properties p = null; if (s != null && s.length() > 0) { try { p = new PropertiesEncoder(s).getProperties(); } catch (IOException e) { // Fail silently if we can't contact the server } } return p; } public void propertyChange(PropertyChangeEvent evt) { if (Boolean.TRUE.equals(evt.getNewValue())) { try { URL base = new URL(boardVersionURL); URLConnection conn = base.openConnection(); conn.setUseCaches(false); InputStream input = conn.getInputStream(); Properties p = new Properties(); p.load(input); boardVersions = p; GameModule.getGameModule().getPrefs().getOption(BOARD_VERSIONS).setValue(new PropertiesEncoder(p).getStringValue()); input.close(); } catch (IOException e) { // Fail silently if we can't contact the server } try { URL base = new URL(overlayVersionURL); URLConnection conn = base.openConnection(); conn.setUseCaches(false); InputStream input = conn.getInputStream(); Properties p = new Properties(); p.load(input); overlayVersions = p; GameModule.getGameModule().getPrefs().getOption(OVERLAY_VERSIONS).setValue(new PropertiesEncoder(p).getStringValue()); input.close(); } catch (IOException e) { // Fail silently if we can't contact the server } } } }
import java.io.File; import java.io.IOException; import org.apache.log4j.Logger; import edu.ucdenver.ccp.common.download.DownloadUtil; import edu.ucdenver.ccp.common.file.CharacterEncoding; import edu.ucdenver.ccp.common.file.FileUtil; import edu.ucdenver.ccp.common.file.reader.Line; import edu.ucdenver.ccp.common.file.reader.StreamLineReader; /** * Abstract class for reading data records from a file. * * @author Bill Baumgartner * */ public abstract class FileRecordReader<T extends FileRecord> extends RecordReader<T> { private static Logger logger = Logger.getLogger(FileRecordReader.class); private final StreamLineReader reader; /** * This constructor takes as input a reference to the file to parse including its character * encoding and line prefix that indicates a line to ignore. * * @param dataFile * @param encoding * @param skipLinePrefix * @throws IOException */ public FileRecordReader(File dataFile, CharacterEncoding encoding, String skipLinePrefix) throws IOException { FileUtil.validateFile(dataFile); logger.info(String.format("Reading records from file: %s", dataFile.getAbsolutePath())); reader = new StreamLineReader(dataFile, encoding, skipLinePrefix); initialize(); } /** * This constructor is designed to be used in conjunction with the FTPDownload annotation. It * allows the user to specify a working directory where file(s) will be downloaded. If this * constructor is implemented by a subclass of FileRecordReader, then the * initializeFileLineReaderFromDownload() method MUST be overriden, else an * UnsupportedOperationException will be thrown. * * @param workDirectory * @param encoding * @param skipLinePrefix * @param ftpUsername * @param ftpPassword * @param clean * @throws IOException */ public FileRecordReader(File workDirectory, CharacterEncoding encoding, String skipLinePrefix, String ftpUsername, String ftpPassword, boolean clean) throws IOException { FileUtil.validateDirectory(workDirectory); try { DownloadUtil.download(this, workDirectory, ftpUsername, ftpPassword, clean); } catch (IllegalArgumentException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } reader = initializeLineReaderFromDownload(encoding, skipLinePrefix); initialize(); } /** * This method is to be overriden by any subclass implementations of FileRecordReader that use * the FileRecordReader(File workDirectory, CharacterEncoding encoding, String skipLinePrefix, * String ftpUsername, String ftpPassword, boolean clean) constructor. In fact, it MUST be * overriden by any of such subclasses. * * @param encoding * @param skipLinePrefix * @return * @throws IOException */ protected StreamLineReader initializeLineReaderFromDownload(@SuppressWarnings("unused") CharacterEncoding encoding, @SuppressWarnings("unused") String skipLinePrefix) throws IOException { throw new UnsupportedOperationException(String.format( "The initializeFileLineReaderFromDownload( method must be overriden by the %s subclass " + "of FileRecordReader in order to use the constructor which automatically downloads " + "the data file.", getClass().getName())); } /** * Read next line * * @return the next line of text from this file, or null if end of file is encountered before * even one byte is read. */ protected Line readLine() throws IOException { return reader.readLine(); } protected void initialize() throws IOException { String fileHeader = getFileHeader(); validateFileHeader(fileHeader); // optionally override to provide functionality, such as skipping lines at the beginning of // the file being parsed. } /** * @return the file header for the file being read. Returns null by default. This method should * be overriden for files that contain headers. * @throws IOException */ protected String getFileHeader() throws IOException { // optionally override to retrieve the header for a data source file return null; } protected void validateFileHeader(String fileHeader) throws IOException { if (fileHeader == null && getExpectedFileHeader() == null) { return; } if (fileHeader == null && getExpectedFileHeader() != null) { throw new IllegalStateException( "File header inconsistency! Code changes likely required. The file header is null but the expected file header is not."); } if (fileHeader != null && getExpectedFileHeader() == null) { throw new IllegalStateException( "File header inconsistency! Code changes likely required. The expected file header is null, but the file being read has a header: " + fileHeader); } if (!fileHeader.equals(getExpectedFileHeader())) { String msg = ""; if (fileHeader.length() > getExpectedFileHeader().length()) { msg = "File header is longer than expected. (" + fileHeader.length() + ">" + getExpectedFileHeader().length() + ")"; } else if (fileHeader.length() < getExpectedFileHeader().toCharArray().length) { msg = "File header is shorter than expected. (" + fileHeader.length() + "<" + getExpectedFileHeader().length() + ")"; } else { int cIndex = 0; for (; cIndex < fileHeader.toCharArray().length; cIndex++) { if (fileHeader.toCharArray()[cIndex] != getExpectedFileHeader().toCharArray()[cIndex]) { break; } } int windowStart = (cIndex > 10) ? (cIndex - 10) : 0; int windowEnd = (cIndex < (fileHeader.length() - 10)) ? (cIndex + 10) : fileHeader.length(); msg = "File header is the expected length (" + fileHeader.length() + "), however there is a difference at character: " + cIndex + ". Expected: ..." + getExpectedFileHeader().substring(windowStart, windowEnd) + "... but was, ..." + fileHeader.subSequence(windowStart, windowEnd) + "..."; } // int windowEndIndex = (cIndex+10 < fileHeader.length()) ? cIndex+10 : // fileHeader.length(); throw new IllegalStateException("File header inconsistency! Code changes likely required. " + msg + " \nFILE_HEADER: " + fileHeader.replaceAll(" ", "[S]").replaceAll("\\t", "[T]").replaceAll("\\n", "[N]") + "\nEXPECTED : " + getExpectedFileHeader().replaceAll(" ", "[S]").replaceAll("\\t", "[T]").replaceAll("\\n", "[N]")); // + "\nLook for mismatch around character index " // + cIndex // + "; header: " // + fileHeader.substring(cIndex, windowEndIndex) // + " expected: " // + getExpectedFileHeader().substring(cIndex, windowEndIndex)); } } protected String getExpectedFileHeader() throws IOException { // optionally override if this file has a header that can be validated return null; } @Override public void close() throws IOException { if (reader != null) { reader.close(); } } }
package com.bitlimit.Tweaks; import org.bukkit.block.Chest; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import java.util.*; import org.bukkit.event.*; import org.bukkit.*; import org.bukkit.entity.*; import org.bukkit.event.entity.CreatureSpawnEvent.*; import org.bukkit.event.entity.*; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.metadata.*; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; import org.bukkit.event.block.*; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.meta.SkullMeta; import com.sk89q.worldedit.Vector; import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.ApplicableRegionSet; import static com.sk89q.worldguard.bukkit.BukkitUtil.*; public class TweaksListener implements Listener { private final Tweaks plugin; // Reference main plugin public TweaksListener(Tweaks plugin) { // Notify plugin manager that this plugin handles implemented events (block place, etc.) plugin.getServer().getPluginManager().registerEvents(this, plugin); this.plugin = plugin; } @EventHandler public void onCreatureSpawnEvent(CreatureSpawnEvent event) { // CreatureSpawnEvent (Entity spawnee, CreatureType type, Location loc, SpawnReason reason FileConfiguration config = this.plugin.getConfig(); if (!config.getConfigurationSection("preferences").getBoolean("slimes")) return; // Gather information to determine if these are the slimes we are looking for. EntityType entityType = event.getEntityType(); SpawnReason reason = event.getSpawnReason(); if (entityType == EntityType.SLIME && (reason == SpawnReason.NATURAL || reason == SpawnReason.SLIME_SPLIT)) { // Pseudo-randomly cancel slime spawns to reduce their numbers. boolean shouldCancel = getRandomBoolean(0.75F); event.setCancelled(shouldCancel); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onBlockPlaceEvent(BlockPlaceEvent event) { // Event reference // BlockPlaceEvent(Block placedBlock, BlockState replacedBlockState, Block placedAgainst, ItemStack itemInHand, Player thePlayer, boolean canBuild) boolean confinementEnabled = this.plugin.getConfig().getConfigurationSection("preferences").getBoolean("tnt"); if (event.getItemInHand().getType() == Material.TNT && confinementEnabled) { WorldGuardPlugin worldGuard = getWorldGuard(); Block block = event.getBlockPlaced(); Vector pt = toVector(block.getLocation()); LocalPlayer localPlayer = worldGuard.wrapPlayer(event.getPlayer()); RegionManager regionManager = worldGuard.getRegionManager(event.getPlayer().getWorld()); ApplicableRegionSet set = regionManager.getApplicableRegions(pt); if (set.size() == 0) event.setCancelled(true); else event.setCancelled(!set.isOwnerOfAll(localPlayer)); if (event.isCancelled()) { displaySmokeInWorldAtLocation(block.getWorld(), block.getLocation()); event.getPlayer().sendMessage(ChatColor.RED + "You are not authorized to place TNT in this location."); } } if (event.getItemInHand().getType() == Material.SKULL_ITEM || event.getItemInHand().getType() == Material.SKULL) { if (event.getItemInHand().getItemMeta().getLore() == null) return; if (event.getItemInHand().getItemMeta().getLore().size() == 0) return; SkullMeta skullMeta = (SkullMeta)event.getItemInHand().getItemMeta(); List<String> meta = event.getItemInHand().getItemMeta().getLore(); StringBuilder builder = new StringBuilder(); for (String value : meta) { builder.append(value); } String builtString = builder.toString(); String strippedString = ChatColor.stripColor(builtString); builtString = builtString.replaceFirst(strippedString.substring(0, 1), strippedString.substring(0, 1).toLowerCase()); event.getBlockPlaced().setMetadata("com.bitlimit.Tweaks.display", new FixedMetadataValue(this.plugin, ChatColor.YELLOW + skullMeta.getOwner() + ChatColor.AQUA + " was " + builtString)); event.getBlockPlaced().setMetadata("com.bitlimit.Tweaks.lore", new FixedMetadataValue(this.plugin, skullMeta.getLore())); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerInteractEvent(PlayerInteractEvent event) { Block block = event.getClickedBlock(); if (block == null) return; Player player = event.getPlayer(); if (block.hasMetadata("com.bitlimit.Tweaks.display")) { List<MetadataValue> metadataValueList = event.getClickedBlock().getMetadata("com.bitlimit.Tweaks.display"); if (metadataValueList.size() > 0) { for (MetadataValue metadataValue : metadataValueList) { String metaString = metadataValue.asString(); player.sendMessage(metaString); } } } if (block.getType() == Material.CAKE_BLOCK && player.getFoodLevel() < 20) { this.onBlockBreakEvent(new BlockBreakEvent(block, player)); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onBlockBreakEvent(BlockBreakEvent event) { Block block = event.getBlock(); if (block.hasMetadata("com.bitlimit.Tweaks.display")) block.removeMetadata("com.bitlimit.Tweaks.display", this.plugin); if (block.hasMetadata("com.bitlimit.Tweaks.lore")) { List<MetadataValue> metadataValueList = block.getMetadata("com.bitlimit.Tweaks.lore"); ItemStack itemStack = (ItemStack)block.getDrops().iterator().next(); if (event.getPlayer().getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH) || event.getPlayer().getGameMode() == GameMode.CREATIVE) { ArrayList<String> lore = new ArrayList<String>(); for (MetadataValue metadataValue : metadataValueList) { lore.add(metadataValue.asString().substring(1, metadataValue.asString().length() - 1)); } ItemMeta newMeta = itemStack.getItemMeta(); newMeta.setLore(lore); itemStack.setItemMeta(newMeta); } block.getLocation().getWorld().dropItemNaturally(block.getLocation(), itemStack); event.setCancelled(true); block.setType(Material.AIR); block.removeMetadata("com.bitlimit.Tweaks.lore", this.plugin); } if (MHFBlocks().containsKey(block.getType())) { float probability = 0.01F; if (block.getType() == Material.CAKE_BLOCK) { probability = 0.07F; Bukkit.broadcastMessage("chance"); } else if (block.getType() == Material.MELON_BLOCK || block.getType() == Material.PUMPKIN) { probability = 0.005F; } boolean shouldDrop = getRandomBoolean(probability); if (!shouldDrop) { return; } ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(getMHFNameForBlock(block)); meta.setDisplayName(humanize2(block.getType().toString().toLowerCase()).replace("Tnt", "TNT")); head.setItemMeta(meta); Location location = block.getLocation(); location.getWorld().dropItemNaturally(location, head); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void PistonExtendEvent(BlockPistonExtendEvent event) { Block movedBlock = event.getBlock(); Block pistonRelative = movedBlock.getRelative(event.getDirection()); if (MHFFarmableBlock().contains(pistonRelative.getType())) { this.onBlockBreakEvent(new BlockBreakEvent(pistonRelative, null)); return; } for (Block block : event.getBlocks()) { Block relative = block.getRelative(event.getDirection()); if (MHFFarmableBlock().contains(relative.getType())) { this.onBlockBreakEvent(new BlockBreakEvent(relative, null)); return; } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { if (event.getEntity().getKiller() == null) return; if (event.getEntity().getKiller() instanceof Player) { ItemStack skullStack = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)skullStack.getItemMeta(); meta.setOwner(event.getEntity().getDisplayName()); Player killer = event.getEntity().getKiller(); if (killer.getItemInHand().containsEnchantment(Enchantment.DAMAGE_ARTHROPODS)) { ArrayList lore = new ArrayList(); lore.add(ChatColor.AQUA + "Slain by " + ChatColor.GOLD + event.getEntity().getKiller().getDisplayName() + ChatColor.AQUA + " on " + getFriendlyDate(Calendar.getInstance())); meta.setLore(lore); } skullStack.setItemMeta(meta); event.getDrops().add(skullStack); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onEntityDeathEvent(EntityDeathEvent event) { Entity entity = event.getEntity(); if (entity instanceof Skeleton) { Skeleton skeleton = (Skeleton)entity; if (skeleton.getSkeletonType() == Skeleton.SkeletonType.WITHER) { return; } } float probability = 0.99F; if (entity.getType() == EntityType.GHAST) { probability = 0.6F; } else if (entity.getType() == EntityType.CREEPER) { probability = 0.85F; } if (!MHFNames().containsKey(entity.getType()) || getRandomBoolean(probability)) { return; } String MHFName = getMHFNameForEntity(entity); ItemStack head = null; if (MHFName.equals("special")) { int type = 0; if (entity.getType() == EntityType.ZOMBIE || entity.getType() == EntityType.GIANT) { type = 2; } else if (entity.getType() == EntityType.CREEPER) { type = 4; } head = new ItemStack(Material.SKULL_ITEM, 1, (byte)type); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setDisplayName(humanize2(entity.getType().toString().toLowerCase() + " Head")); head.setItemMeta(meta); } else { head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(MHFName); meta.setDisplayName(humanize2(entity.getType().toString().toLowerCase() + " Head")); head.setItemMeta(meta); } event.getDrops().add(head); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onLightningStrike(LightningStrikeEvent event) { Location location = event.getLightning().getLocation(); ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(getMHFNameForEntity(event.getLightning())); meta.setDisplayName("Herobrine Head"); head.setItemMeta(meta); Random random = new Random(); location.getWorld().dropItemNaturally(location.add(random.nextInt(10) - 7, 50, 0), head); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onChatEvent(AsyncPlayerChatEvent event) { boolean shouldNotDropItem = getRandomBoolean(0.97F); if (shouldNotDropItem) { return; } class ChatHandlerTask implements Runnable { private final AsyncPlayerChatEvent event; ChatHandlerTask(AsyncPlayerChatEvent event) { this.event = event; } public void run() { Player player = this.event.getPlayer(); if (player == null) { return; } Location location = player.getLocation(); if (location == null) { return; } ArrayList<String> bonuses = MHFBonuses(); String bonus = bonuses.get(new Random().nextInt(bonuses.size())); ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(bonus); meta.setDisplayName(humanize2(bonus.replace("MHF_", "").replace("Arrow", "Arrow ") + " Head")); head.setItemMeta(meta); location.getWorld().dropItemNaturally(location.add(0, 2, 0), head); } } Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, new ChatHandlerTask(event)); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerJoinEvent(PlayerJoinEvent event) { if (!event.getPlayer().hasPlayedBefore()) { if (!this.plugin.getConfig().getConfigurationSection("preferences").getBoolean("spawnItems")) return; Location location = this.parseLocation(this.plugin.getConfig().getConfigurationSection("meta").getConfigurationSection("spawnItems").getConfigurationSection("location")); Block block = location.getWorld().getBlockAt(location); if (block.getType() == Material.CHEST) { Chest chestBlock = (Chest)block.getState(); int index = 0; for (ItemStack itemStack : chestBlock.getInventory().getContents()) { event.getPlayer().getInventory().setItem(index, itemStack); if (index < 27) index++; } } } } private WorldGuardPlugin getWorldGuard() { Plugin plugin = this.plugin.getServer().getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { return null; // Maybe you want throw an exception instead } return (WorldGuardPlugin) plugin; } public Location parseLocation(ConfigurationSection locationSection) { Location location = new Location(Bukkit.getWorld(locationSection.getString("world")), locationSection.getDouble("x"), locationSection.getDouble("y"), locationSection.getDouble("z"), Float.parseFloat(locationSection.getString("yaw")), Float.parseFloat(locationSection.getString("pitch"))); return location; } public boolean getRandomBoolean(float probability) { Random random = new Random(); return (random.nextInt(100) < (probability * 100)); } private void displaySmokeInWorldAtLocation(World world, Location location) { world.playEffect(location, Effect.MOBSPAWNER_FLAMES, 0); } // Overloaded function to cut down on calling arguments, no default parameters in Java =/ private static String getFriendlyDate(Calendar theDate) { return getFriendlyDate(theDate, false); } // Function to get a human readable version of a Calendar object // If verbose is true we slightly expand the date wording private static String getFriendlyDate(Calendar theDate, boolean verbose) { int year = theDate.get(Calendar.YEAR); int month = theDate.get(Calendar.MONTH); int dayOfMonth = theDate.get(Calendar.DAY_OF_MONTH); int dayOfWeek = theDate.get(Calendar.DAY_OF_WEEK); // Get the day of the week as a String. // Note: The Calendar DAY_OF_WEEK property is NOT zero-based, and Sunday is the first day of week. String friendly = ""; switch (dayOfWeek) { case 1: friendly = "Sunday"; break; case 2: friendly = "Monday"; break; case 3: friendly = "Tuesday"; break; case 4: friendly = "Wednesday"; break; case 5: friendly = "Thursday"; break; case 6: friendly = "Friday"; break; case 7: friendly = "Saturday"; break; default: friendly = "BadDayValue"; break; } // Add padding and the prefix to the day of month if (verbose == true) { friendly += " the " + dayOfMonth; } else { friendly += ", " + dayOfMonth; } String dayString = String.valueOf(dayOfMonth); // Convert dayOfMonth to String using valueOf // Suffix is "th" for day of day of month values ending in 0, 4, 5, 6, 7, 8, and 9 if (dayString.endsWith("0") || dayString.endsWith("4") || dayString.endsWith("5") || dayString.endsWith("6") || dayString.endsWith("7") || dayString.endsWith("8") || dayString.endsWith("9") || dayString.equals("13")) { friendly += "th "; } else if (dayString.endsWith("1")) { friendly += "st "; } else if (dayString.endsWith("2")) { friendly += "nd "; } else if (dayString.endsWith("3")) { friendly += "rd "; } // Add more padding if we've been asked to be verbose if (verbose == true) { friendly += "of "; } // Get a friendly version of the month. // Note: The Calendar MONTH property is zero-based to increase the chance of developers making mistakes. switch (month) { case 0: friendly += "January"; break; case 1: friendly += "February"; break; case 2: friendly += "March"; break; case 3: friendly += "April"; break; case 4: friendly += "May"; break; case 5: friendly += "June"; break; case 6: friendly += "July"; break; case 7: friendly += "August"; break; case 8: friendly += "September"; break; case 9: friendly += "October"; break; case 10: friendly += "November"; break; case 11: friendly += "December"; break; default: friendly += "BadMonthValue"; break; } // Tack on the year and we're done. Phew! friendly += " " + year; return friendly; } // End of getFriendlyDate function /** * Returns the given underscored_word_group as a Human Readable Word Group. * (Underscores are replaced by spaces and capitalized following words.) * * @param pWord * String to be made more readable * @return Human-readable string */ public static String humanize2(String pWord) { StringBuilder sb = new StringBuilder(); String[] words = pWord.replaceAll("_", " ").split("\\s"); for (int i = 0; i < words.length; i++) { if (i > 0) sb.append(" "); if (words[i].length() > 0) { sb.append(Character.toUpperCase(words[i].charAt(0))); if (words[i].length() > 1) { sb.append(words[i].substring(1)); } } } return sb.toString(); } private static String getMHFNameForEntity(Entity entity) { return MHFNames().get(entity.getType()); } private static HashMap <EntityType, String> MHFNames() { HashMap <EntityType, String> entityNames = new HashMap<EntityType, String>(); entityNames.put(EntityType.CREEPER, "special"); entityNames.put(EntityType.GIANT, "special"); entityNames.put(EntityType.ZOMBIE, "special"); entityNames.put(EntityType.SKELETON, "special"); entityNames.put(EntityType.LIGHTNING, "MHF_Herobrine"); entityNames.put(EntityType.BLAZE, "MHF_Blaze"); entityNames.put(EntityType.CAVE_SPIDER, "MHF_CaveSpider"); entityNames.put(EntityType.CHICKEN, "MHF_Chicken"); entityNames.put(EntityType.COW, "MHF_Cow"); entityNames.put(EntityType.ENDERMAN, "MHF_Enderman"); entityNames.put(EntityType.GHAST, "MHF_Ghast"); entityNames.put(EntityType.IRON_GOLEM, "MHF_Golem"); entityNames.put(EntityType.MAGMA_CUBE, "MHF_LavaSlime"); entityNames.put(EntityType.MUSHROOM_COW, "MHF_MushroomCow"); entityNames.put(EntityType.OCELOT, "MHF_Ocelot"); entityNames.put(EntityType.PIG, "MHF_Pig"); entityNames.put(EntityType.PIG_ZOMBIE, "MHF_PigZombie"); entityNames.put(EntityType.SHEEP, "MHF_Sheep"); entityNames.put(EntityType.SLIME, "MHF_Slime"); entityNames.put(EntityType.SPIDER, "MHF_Spider"); entityNames.put(EntityType.SQUID, "MHF_Squid"); entityNames.put(EntityType.VILLAGER, "MHF_Villager"); entityNames.put(EntityType.WITHER, "MHF_Wither"); return entityNames; } private static ArrayList<String> MHFBonuses() { ArrayList bonuses = new ArrayList<String>(); bonuses.add("MHF_ArrowUp"); bonuses.add("MHF_ArrowDown"); bonuses.add("MHF_ArrowLeft"); bonuses.add("MHF_ArrowRight"); bonuses.add("MHF_Exclamation"); bonuses.add("MHF_Question"); return bonuses; } private static String getMHFNameForBlock(Block block) { Object unknown = MHFBlocks().get(block.getType()); if (unknown instanceof String) { return (String)unknown; } else { String[] names = (String[])unknown; return names[new Random().nextInt(names.length)]; } } private static HashMap <Material, Object> MHFBlocks() { HashMap <Material, Object> blockNames = new HashMap<Material, Object>(); blockNames.put(Material.CACTUS, "MHF_Cactus"); blockNames.put(Material.CAKE_BLOCK, "MHF_Cake"); blockNames.put(Material.CHEST, "MHF_Chest"); blockNames.put(Material.MELON_BLOCK, "MHF_Melon"); blockNames.put(Material.LOG, "MHF_OakLog"); blockNames.put(Material.PUMPKIN, "MHF_Pumpkin"); String[] TNTNames = {"MHF_TNT", "MHF_TNT2"}; blockNames.put(Material.TNT, TNTNames); return blockNames; } private static ArrayList<Material> MHFFarmableBlock() { ArrayList farmables = new ArrayList<Material>(); farmables.add(Material.PUMPKIN); farmables.add(Material.MELON_BLOCK); return farmables; } }
package com.bitlimit.Tweaks; import org.bukkit.block.Chest; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import java.util.*; import org.bukkit.event.*; import org.bukkit.*; import org.bukkit.entity.*; import org.bukkit.event.entity.CreatureSpawnEvent.*; import org.bukkit.event.entity.*; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.metadata.*; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; import org.bukkit.event.block.*; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.meta.SkullMeta; import com.sk89q.worldedit.Vector; import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.ApplicableRegionSet; import static com.sk89q.worldguard.bukkit.BukkitUtil.*; public class TweaksListener implements Listener { private final Tweaks plugin; // Reference main plugin public TweaksListener(Tweaks plugin) { // Notify plugin manager that this plugin handles implemented events (block place, etc.) plugin.getServer().getPluginManager().registerEvents(this, plugin); this.plugin = plugin; } @EventHandler public void onCreatureSpawnEvent(CreatureSpawnEvent event) { // CreatureSpawnEvent (Entity spawnee, CreatureType type, Location loc, SpawnReason reason FileConfiguration config = this.plugin.getConfig(); if (!config.getConfigurationSection("preferences").getBoolean("slimes")) return; // Gather information to determine if these are the slimes we are looking for. EntityType entityType = event.getEntityType(); SpawnReason reason = event.getSpawnReason(); if (entityType == EntityType.SLIME && (reason == SpawnReason.NATURAL || reason == SpawnReason.SLIME_SPLIT)) { // Pseudo-randomly cancel slime spawns to reduce their numbers. boolean shouldCancel = getRandomBoolean(0.75F); event.setCancelled(shouldCancel); } } @EventHandler public void onBlockPlaceEvent(BlockPlaceEvent event) { // Event reference // BlockPlaceEvent(Block placedBlock, BlockState replacedBlockState, Block placedAgainst, ItemStack itemInHand, Player thePlayer, boolean canBuild) boolean confinementEnabled = this.plugin.getConfig().getConfigurationSection("preferences").getBoolean("tnt"); if (event.getItemInHand().getType() == Material.TNT && confinementEnabled) { WorldGuardPlugin worldGuard = getWorldGuard(); Block block = event.getBlockPlaced(); Vector pt = toVector(block.getLocation()); LocalPlayer localPlayer = worldGuard.wrapPlayer(event.getPlayer()); RegionManager regionManager = worldGuard.getRegionManager(event.getPlayer().getWorld()); ApplicableRegionSet set = regionManager.getApplicableRegions(pt); if (set.size() == 0) event.setCancelled(true); else event.setCancelled(!set.isOwnerOfAll(localPlayer)); if (event.isCancelled()) { displaySmokeInWorldAtLocation(block.getWorld(), block.getLocation()); event.getPlayer().sendMessage(ChatColor.RED + "You are not authorized to place TNT in this location."); } } if (event.getItemInHand().getType() == Material.SKULL_ITEM || event.getItemInHand().getType() == Material.SKULL) { if (event.getItemInHand().getItemMeta().getLore() == null) return; if (event.getItemInHand().getItemMeta().getLore().size() == 0) return; SkullMeta skullMeta = (SkullMeta)event.getItemInHand().getItemMeta(); List<String> meta = event.getItemInHand().getItemMeta().getLore(); StringBuilder builder = new StringBuilder(); for (String value : meta) { builder.append(value); } String builtString = builder.toString(); String strippedString = ChatColor.stripColor(builtString); builtString = builtString.replaceFirst(strippedString.substring(0, 1), strippedString.substring(0, 1).toLowerCase()); event.getBlockPlaced().setMetadata("com.bitlimit.Tweaks.display", new FixedMetadataValue(this.plugin, ChatColor.YELLOW + skullMeta.getOwner() + ChatColor.AQUA + " was " + builtString)); event.getBlockPlaced().setMetadata("com.bitlimit.Tweaks.lore", new FixedMetadataValue(this.plugin, skullMeta.getLore())); } } @EventHandler public void onPlayerInteractEvent(PlayerInteractEvent event) { Block block = event.getClickedBlock(); if (block == null) return; if (!block.hasMetadata("com.bitlimit.Tweaks.display")) return; List<MetadataValue> metadataValueList = event.getClickedBlock().getMetadata("com.bitlimit.Tweaks.display"); if (metadataValueList.size() > 0) { Player player = event.getPlayer(); for (MetadataValue metadataValue : metadataValueList) { String metaString = metadataValue.asString(); player.sendMessage(metaString); } } } @EventHandler public void onBlockBreakEvent(BlockBreakEvent event) { Block block = event.getBlock(); if (block.hasMetadata("com.bitlimit.Tweaks.display")) block.removeMetadata("com.bitlimit.Tweaks.display", this.plugin); if (block.hasMetadata("com.bitlimit.Tweaks.lore")) { List<MetadataValue> metadataValueList = block.getMetadata("com.bitlimit.Tweaks.lore"); ItemStack itemStack = (ItemStack)block.getDrops().iterator().next(); if (event.getPlayer().getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH) || event.getPlayer().getGameMode() == GameMode.CREATIVE) { ArrayList<String> lore = new ArrayList<String>(); for (MetadataValue metadataValue : metadataValueList) { lore.add(metadataValue.asString().substring(1, metadataValue.asString().length() - 1)); } ItemMeta newMeta = itemStack.getItemMeta(); newMeta.setLore(lore); itemStack.setItemMeta(newMeta); } block.getLocation().getWorld().dropItemNaturally(block.getLocation(), itemStack); event.setCancelled(true); block.setType(Material.AIR); block.removeMetadata("com.bitlimit.Tweaks.lore", this.plugin); } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { if (event.getEntity().getKiller() == null) return; if (event.getEntity().getKiller() instanceof Player) { ItemStack skullStack = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)skullStack.getItemMeta(); meta.setOwner(event.getEntity().getDisplayName()); Player killer = event.getEntity().getKiller(); if (killer.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH)) { ArrayList lore = new ArrayList(); lore.add(ChatColor.AQUA + "Slain by " + ChatColor.GOLD + event.getEntity().getKiller().getDisplayName() + ChatColor.AQUA + " on " + getFriendlyDate(Calendar.getInstance())); meta.setLore(lore); } skullStack.setItemMeta(meta); event.getDrops().add(skullStack); } } @EventHandler public void onEntityDeathEvent(EntityDeathEvent event) { Entity entity = event.getEntity(); if (entity instanceof Skeleton) { Skeleton skeleton = (Skeleton)entity; if (skeleton.getSkeletonType() == Skeleton.SkeletonType.WITHER) { return; } } if (!MHFNames().containsKey(entity.getType()) || getRandomBoolean(0.99F)) { return; } String MHFName = getMHFNameForEntity(entity); ItemStack head = null; if (MHFName.equals("special")) { int type = 0; if (entity.getType() == EntityType.ZOMBIE || entity.getType() == EntityType.GIANT) { type = 2; } else if (entity.getType() == EntityType.CREEPER) { type = 4; } head = new ItemStack(Material.SKULL_ITEM, 1, (byte)type); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setDisplayName(humanize2(entity.getType().toString().toLowerCase() + " Head")); head.setItemMeta(meta); } else { head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(MHFName); meta.setDisplayName(humanize2(entity.getType().toString().toLowerCase() + " Head")); head.setItemMeta(meta); } event.getDrops().add(head); } @EventHandler public void onLightningStrike(LightningStrikeEvent event) { Location location = event.getLightning().getLocation(); ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (byte)3); SkullMeta meta = (SkullMeta)head.getItemMeta(); meta.setOwner(getMHFNameForEntity(event.getLightning())); meta.setDisplayName("Herobrine Head"); head.setItemMeta(meta); Random random = new Random(); location.getWorld().dropItemNaturally(location.add(random.nextInt(10) - 7, 50, 0), head); } @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent event) { if (!event.getPlayer().hasPlayedBefore()) { if (!this.plugin.getConfig().getConfigurationSection("preferences").getBoolean("spawnItems")) return; Location location = this.parseLocation(this.plugin.getConfig().getConfigurationSection("meta").getConfigurationSection("spawnItems").getConfigurationSection("location")); Block block = location.getWorld().getBlockAt(location); if (block.getType() == Material.CHEST) { Chest chestBlock = (Chest)block.getState(); int index = 0; for (ItemStack itemStack : chestBlock.getInventory().getContents()) { event.getPlayer().getInventory().setItem(index, itemStack); if (index < 27) index++; } } } } private WorldGuardPlugin getWorldGuard() { Plugin plugin = this.plugin.getServer().getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { return null; // Maybe you want throw an exception instead } return (WorldGuardPlugin) plugin; } public Location parseLocation(ConfigurationSection locationSection) { Location location = new Location(Bukkit.getWorld(locationSection.getString("world")), locationSection.getDouble("x"), locationSection.getDouble("y"), locationSection.getDouble("z"), Float.parseFloat(locationSection.getString("yaw")), Float.parseFloat(locationSection.getString("pitch"))); return location; } public boolean getRandomBoolean(float probability) { Random random = new Random(); return random.nextInt(100) < (probability * 100); } private void displaySmokeInWorldAtLocation(World world, Location location) { world.playEffect(location, Effect.MOBSPAWNER_FLAMES, 0); } // Overloaded function to cut down on calling arguments, no default parameters in Java =/ private static String getFriendlyDate(Calendar theDate) { return getFriendlyDate(theDate, false); } // Function to get a human readable version of a Calendar object // If verbose is true we slightly expand the date wording private static String getFriendlyDate(Calendar theDate, boolean verbose) { int year = theDate.get(Calendar.YEAR); int month = theDate.get(Calendar.MONTH); int dayOfMonth = theDate.get(Calendar.DAY_OF_MONTH); int dayOfWeek = theDate.get(Calendar.DAY_OF_WEEK); // Get the day of the week as a String. // Note: The Calendar DAY_OF_WEEK property is NOT zero-based, and Sunday is the first day of week. String friendly = ""; switch (dayOfWeek) { case 1: friendly = "Sunday"; break; case 2: friendly = "Monday"; break; case 3: friendly = "Tuesday"; break; case 4: friendly = "Wednesday"; break; case 5: friendly = "Thursday"; break; case 6: friendly = "Friday"; break; case 7: friendly = "Saturday"; break; default: friendly = "BadDayValue"; break; } // Add padding and the prefix to the day of month if (verbose == true) { friendly += " the " + dayOfMonth; } else { friendly += ", " + dayOfMonth; } String dayString = String.valueOf(dayOfMonth); // Convert dayOfMonth to String using valueOf // Suffix is "th" for day of day of month values ending in 0, 4, 5, 6, 7, 8, and 9 if (dayString.endsWith("0") || dayString.endsWith("4") || dayString.endsWith("5") || dayString.endsWith("6") || dayString.endsWith("7") || dayString.endsWith("8") || dayString.endsWith("9") || dayString.equals("13")) { friendly += "th "; } else if (dayString.endsWith("1")) { friendly += "st "; } else if (dayString.endsWith("2")) { friendly += "nd "; } else if (dayString.endsWith("3")) { friendly += "rd "; } // Add more padding if we've been asked to be verbose if (verbose == true) { friendly += "of "; } // Get a friendly version of the month. // Note: The Calendar MONTH property is zero-based to increase the chance of developers making mistakes. switch (month) { case 0: friendly += "January"; break; case 1: friendly += "February"; break; case 2: friendly += "March"; break; case 3: friendly += "April"; break; case 4: friendly += "May"; break; case 5: friendly += "June"; break; case 6: friendly += "July"; break; case 7: friendly += "August"; break; case 8: friendly += "September"; break; case 9: friendly += "October"; break; case 10: friendly += "November"; break; case 11: friendly += "December"; break; default: friendly += "BadMonthValue"; break; } // Tack on the year and we're done. Phew! friendly += " " + year; return friendly; } // End of getFriendlyDate function /** * Returns the given underscored_word_group as a Human Readable Word Group. * (Underscores are replaced by spaces and capitalized following words.) * * @param pWord * String to be made more readable * @return Human-readable string */ public static String humanize2(String pWord) { StringBuilder sb = new StringBuilder(); String[] words = pWord.replaceAll("_", " ").split("\\s"); for (int i = 0; i < words.length; i++) { if (i > 0) sb.append(" "); if (words[i].length() > 0) { sb.append(Character.toUpperCase(words[i].charAt(0))); if (words[i].length() > 1) { sb.append(words[i].substring(1)); } } } return sb.toString(); } private static String getMHFNameForEntity(Entity entity) { /* Mobs: MHF_Blaze MHF_CaveSpider MHF_Chicken MHF_Cow MHF_Enderman MHF_Ghast MHF_Golem MHF_Herobrine MHF_LavaSlime MHF_MushroomCow MHF_Ocelot MHF_Pig MHF_PigZombie MHF_Sheep MHF_Slime MHF_Spider MHF_Squid MHF_Villager MHF_Wither Blocks: MHF_Cactus MHF_Cake MHF_Chest MHF_Melon MHF_OakLog MHF_Pumpkin MHF_TNT MHF_TNT2 Bonus: MHF_ArrowUp MHF_ArrowDown MHF_ArrowLeft MHF_ArrowRight MHF_Exclamation MHF_Question */ return MHFNames().get(entity.getType()); } private static HashMap <EntityType, String> MHFNames() { HashMap <EntityType, String> entityNames = new HashMap<EntityType, String>(); entityNames.put(EntityType.CREEPER, "special"); entityNames.put(EntityType.GIANT, "special"); entityNames.put(EntityType.ZOMBIE, "special"); entityNames.put(EntityType.SKELETON, "special"); entityNames.put(EntityType.LIGHTNING, "MHF_Herobrine"); entityNames.put(EntityType.BLAZE, "MHF_Blaze"); entityNames.put(EntityType.CAVE_SPIDER, "MHF_CaveSpider"); entityNames.put(EntityType.CHICKEN, "MHF_Chicken"); entityNames.put(EntityType.COW, "MHF_Cow"); entityNames.put(EntityType.ENDERMAN, "MHF_Enderman"); entityNames.put(EntityType.GHAST, "MHF_Ghast"); entityNames.put(EntityType.IRON_GOLEM, "MHF_Golem"); entityNames.put(EntityType.MAGMA_CUBE, "MHF_LavaSlime"); entityNames.put(EntityType.MUSHROOM_COW, "MHF_MushroomCow"); entityNames.put(EntityType.OCELOT, "MHF_Ocelot"); entityNames.put(EntityType.PIG, "MHF_Pig"); entityNames.put(EntityType.PIG_ZOMBIE, "MHF_PigZombie"); entityNames.put(EntityType.SHEEP, "MHF_Sheep"); entityNames.put(EntityType.SLIME, "MHF_Slime"); entityNames.put(EntityType.SPIDER, "MHF_Spider"); entityNames.put(EntityType.SQUID, "MHF_Squid"); entityNames.put(EntityType.VILLAGER, "MHF_Villager"); entityNames.put(EntityType.WITHER, "MHF_Wither"); return entityNames; } }
package com.dailystudio.app.prefs; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import com.dailystudio.development.Logger; public abstract class AbsPrefs { public static final String ACTION_PREFS_CHANGED = "devbricks.intent.ACTION_PREFS_CHANGED"; public static final String EXTRA_PREF_KEY = "devbricks.intent.EXTRA_PREF_KEY"; private SharedPreferences getSharedPreferences(Context context) { if (context == null) { return null; } return context.getSharedPreferences( getPrefName(), Context.MODE_PRIVATE); } private Editor getEditor(Context context) { if (context == null) { return null; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return null; } return sharedPref.edit(); } public void setStringPrefValue(Context context, String pref, String sValue) { if (context == null || pref == null || sValue == null) { return; } Editor editor = getEditor(context); editor.putString(pref, sValue); editor.commit(); notifyPrefChanged(context, pref); } public void setBooleanPrefValue(Context context, String pref, boolean bValue) { if (context == null || pref == null) { return; } Editor editor = getEditor(context); editor.putBoolean(pref, bValue); editor.commit(); notifyPrefChanged(context, pref); } public void setLongPrefValue(Context context, String pref, long lValue) { if (context == null || pref == null) { return; } Editor editor = getEditor(context); editor.putLong(pref, lValue); editor.commit(); notifyPrefChanged(context, pref); } public void setIntegerPrefValue(Context context, String pref, int iValue) { if (context == null || pref == null) { return; } Editor editor = getEditor(context); editor.putInt(pref, iValue); editor.commit(); notifyPrefChanged(context, pref); } public void setFloatPrefValue(Context context, String pref, float fValue) { if (context == null || pref == null) { return; } Editor editor = getEditor(context); editor.putFloat(pref, fValue); editor.commit(); notifyPrefChanged(context, pref); } public String getStringPrefValue(Context context, String pref) { if (context == null || pref == null) { return null; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return null; } return sharedPref.getString(pref, null); } public boolean getBooleanPrefValue(Context context, String pref) { return getBooleanPrefValue(context, pref, false); } public boolean getBooleanPrefValue(Context context, String pref, boolean defVal) { if (context == null || pref == null) { return defVal; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return defVal; } return sharedPref.getBoolean(pref, defVal); } public long getLongPrefValue(Context context, String pref) { return getLongPrefValue(context, pref, 0l); } public long getLongPrefValue(Context context, String pref, long defVal) { if (context == null || pref == null) { return defVal; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return defVal; } return sharedPref.getLong(pref, defVal); } public int getIntegerPreValue(Context context, String pref) { return getIntegerPreValue(context, pref, 0); } public int getIntegerPreValue(Context context, String pref, int defVal) { if (context == null || pref == null) { return defVal; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return defVal; } return sharedPref.getInt(pref, defVal); } public float getFloatPreValue(Context context, String pref) { return getFloatPreValue(context, pref, 0.0f); } public float getFloatPreValue(Context context, String pref, float defVal) { if (context == null || pref == null) { return defVal; } SharedPreferences sharedPref = getSharedPreferences(context); if (sharedPref == null) { return defVal; } return sharedPref.getFloat(pref, defVal); } protected void notifyPrefChanged(Context context, String key) { if (context == null || TextUtils.isEmpty(key)) { return; } Intent i = new Intent(ACTION_PREFS_CHANGED); i.putExtra(EXTRA_PREF_KEY, key); LocalBroadcastManager.getInstance(context).sendBroadcast(i); } public void registerPrefChangesReceiver(Context context, BroadcastReceiver receiver) { if (context == null || receiver == null) { return; } IntentFilter filter = new IntentFilter(ACTION_PREFS_CHANGED); try { LocalBroadcastManager.getInstance(context) .registerReceiver(receiver, filter); } catch (Exception e) { Logger.warn("could not register receiver [%s] on %s: %s", receiver, ACTION_PREFS_CHANGED, e.toString()); } } public void unregisterPrefChangesReceiver(Context context, BroadcastReceiver receiver) { if (context == null || receiver == null) { return; } try { LocalBroadcastManager.getInstance(context) .unregisterReceiver(receiver); } catch (Exception e) { Logger.warn("could not unregister receiver [%s] from %s: %s", receiver, ACTION_PREFS_CHANGED, e.toString()); } } abstract protected String getPrefName(); }
package ro.isdc.wro.maven.plugin; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.classworlds.ClassRealm; import org.sonatype.plexus.build.incremental.BuildContext; import ro.isdc.wro.WroRuntimeException; import ro.isdc.wro.config.Context; import ro.isdc.wro.extensions.manager.standalone.ExtensionsStandaloneManagerFactory; import ro.isdc.wro.manager.WroManager; import ro.isdc.wro.manager.factory.WroManagerFactory; import ro.isdc.wro.manager.factory.standalone.StandaloneContext; import ro.isdc.wro.manager.factory.standalone.StandaloneContextAware; import ro.isdc.wro.maven.plugin.support.ExtraConfigFileAware; import ro.isdc.wro.model.WroModel; import ro.isdc.wro.model.WroModelInspector; import ro.isdc.wro.model.group.Group; import ro.isdc.wro.model.group.processor.InjectorBuilder; import ro.isdc.wro.model.resource.Resource; import ro.isdc.wro.model.resource.ResourceType; import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; import ro.isdc.wro.model.resource.processor.decorator.ExceptionHandlingProcessorDecorator; import ro.isdc.wro.model.resource.processor.impl.css.AbstractCssImportPreProcessor; import ro.isdc.wro.model.resource.processor.impl.css.CssImportPreProcessor; import ro.isdc.wro.model.resource.support.hash.HashStrategy; import ro.isdc.wro.util.Function; /** * Defines most common properties used by wro4j build-time solution infrastructure. * * @author Alex Objelean */ public abstract class AbstractWro4jMojo extends AbstractMojo { /** * File containing the groups definitions. * * @parameter default-value="${basedir}/src/main/webapp/WEB-INF/wro.xml" expression="${wroFile}" * @optional */ private File wroFile; /** * The folder where web application context resides useful for locating resources relative to servletContext . * * @parameter default-value="${basedir}/src/main/webapp/" expression="${contextFolder}" */ private File contextFolder; /** * @parameter default-value="true" expression="${minimize}" * @optional */ private boolean minimize; /** * @parameter default-value="true" expression="${ignoreMissingResources}" * @optional */ private boolean ignoreMissingResources; /** * Comma separated group names. This field is optional. If no value is provided, a file for each group will be * created. * * @parameter expression="${targetGroups}" * @optional */ private String targetGroups; /** * @parameter default-value="${project}" */ private MavenProject mavenProject; /** * @parameter expression="${wroManagerFactory}" * @optional */ private String wroManagerFactory; /** * An instance of {@link StandaloneContextAware}. */ private WroManagerFactory managerFactory; /** * The path to configuration file. * * @parameter default-value="${basedir}/src/main/webapp/WEB-INF/wro.properties" expression="${extraConfigFile}" * @optional */ private File extraConfigFile; private BuildContext buildContext; /** * {@inheritDoc} */ public final void execute() throws MojoExecutionException { validate(); getLog().info("Executing the mojo: "); getLog().info("Wro4j Model path: " + wroFile.getPath()); getLog().info("targetGroups: " + getTargetGroups()); getLog().info("minimize: " + isMinimize()); getLog().info("ignoreMissingResources: " + isIgnoreMissingResources()); getLog().debug("wroManagerFactory: " + this.wroManagerFactory); getLog().debug("extraConfig: " + extraConfigFile); extendPluginClasspath(); Context.set(Context.standaloneContext()); try { onBeforeExecute(); doExecute(); } catch (final Exception e) { throw new MojoExecutionException("Exception occured while processing: " + e.getMessage(), e); } finally { onAfterExecute(); } } /** * Invoked before execution is performed. */ protected void onBeforeExecute() { } /** * Invoked right after execution completion. This method is invoked also if the execution failed with an exception. */ protected void onAfterExecute() { } /** * Creates a {@link StandaloneContext} by setting properties passed after mojo is initialized. */ private StandaloneContext createStandaloneContext() { final StandaloneContext runContext = new StandaloneContext(); runContext.setContextFolder(getContextFolder()); runContext.setMinimize(isMinimize()); runContext.setWroFile(getWroFile()); runContext.setIgnoreMissingResources(isIgnoreMissingResources()); return runContext; } /** * Perform actual plugin processing. */ protected abstract void doExecute() throws Exception; /** * This method will ensure that you have a right and initialized instance of {@link StandaloneContextAware}. When * overriding this method, ensure that creating managerFactory performs injection during manager creation, otherwise * the manager won't be initialized porperly. * * @return {@link WroManagerFactory} implementation. */ protected WroManagerFactory getManagerFactory() { if (managerFactory == null) { try { managerFactory = newWroManagerFactory(); } catch (final MojoExecutionException e) { throw WroRuntimeException.wrap(e); } // initialize before process. if (managerFactory instanceof StandaloneContextAware) { ((StandaloneContextAware) managerFactory).initialize(createStandaloneContext()); } } return managerFactory; } /** * {@inheritDoc} */ protected WroManagerFactory newWroManagerFactory() throws MojoExecutionException { WroManagerFactory factory = null; if (wroManagerFactory != null) { factory = createCustomManagerFactory(); } else { factory = new ExtensionsStandaloneManagerFactory(); } getLog().info("wroManagerFactory class: " + factory.getClass().getName()); if (factory instanceof ExtraConfigFileAware) { if (extraConfigFile == null) { throw new MojoExecutionException("The " + factory.getClass() + " requires a valid extraConfigFile!"); } getLog().debug("Using extraConfigFile: " + extraConfigFile.getAbsolutePath()); ((ExtraConfigFileAware) factory).setExtraConfigFile(extraConfigFile); } return factory; } /** * Creates an instance of Manager factory based on the value of the wroManagerFactory plugin parameter value. */ private WroManagerFactory createCustomManagerFactory() throws MojoExecutionException { WroManagerFactory managerFactory; try { final Class<?> wroManagerFactoryClass = Thread.currentThread().getContextClassLoader().loadClass( wroManagerFactory.trim()); managerFactory = (WroManagerFactory) wroManagerFactoryClass.newInstance(); } catch (final Exception e) { getLog().error("Cannot instantiate wroManagerFactoryClass", e); throw new MojoExecutionException("Invalid wroManagerFactoryClass, called: " + wroManagerFactory, e); } return managerFactory; } /** * @return a list of groups which will be processed. */ protected final List<String> getTargetGroupsAsList() throws Exception { List<String> result = null; if (isIncrementalBuild()) { result = getIncrementalGroupNames(); } else if (getTargetGroups() == null) { result = getAllModelGroupNames(); } else { result = Arrays.asList(getTargetGroups().split(",")); } persistResourceFingerprints(result); getLog().info("The following groups will be processed: " + result); return result; } /** * Store digest for all resources contained inside the list of provided groups. */ private void persistResourceFingerprints(final List<String> groupNames) { if (buildContext != null) { final WroModelInspector modelInspector = new WroModelInspector(getModel()); for (final String groupName : groupNames) { final Group group = modelInspector.getGroupByName(groupName); if (group != null) { for (final Resource resource : group.getResources()) { persistResourceFingerprints(resource); } } } } } private void persistResourceFingerprints(final Resource resource) { final WroManager manager = getWroManager(); final HashStrategy hashStrategy = manager.getHashStrategy(); final UriLocatorFactory locatorFactory = manager.getUriLocatorFactory(); try { final String fingerprint = hashStrategy.getHash(locatorFactory.locate(resource.getUri())); buildContext.setValue(resource.getUri(), fingerprint); getLog().debug("Persist fingerprint for resource '" + resource.getUri() + "' : " + fingerprint); if (resource.getType() == ResourceType.CSS) { final Reader reader = new InputStreamReader(locatorFactory.locate(resource.getUri())); getLog().debug("Check @import directive from " + resource); // persist fingerprints in imported resources. persistFingerprintsForCssImports(resource, reader); } } catch (final IOException e) { getLog().debug("could not check fingerprint of resource: " + resource); } } /** * Invokes the provided function for each detected css import. * * @param func * a function (closure) invoked for each found import. It will be provided as argument the uri of imported * css. */ private void forEachCssImportApply(final Function<String, Void> func, final Resource resource, final Reader reader) throws IOException { final ResourcePreProcessor cssImportProcessor = new AbstractCssImportPreProcessor() { @Override protected void onImportDetected(final String importedUri) { getLog().debug("Found @import " + importedUri); try { func.apply(importedUri); } catch (final Exception e) { getLog().error("Cannot apply a function on @import resource: " + importedUri + ". Ignoring it.", e); } persistResourceFingerprints(Resource.create(importedUri, ResourceType.CSS)); } @Override protected String doTransform(final String cssContent, final List<Resource> foundImports) throws IOException { // no need to build the content, since we are interested in finding imported resources only return ""; } @Override public String toString() { return CssImportPreProcessor.class.getSimpleName(); } }; final ResourcePreProcessor processor = new ExceptionHandlingProcessorDecorator(cssImportProcessor) { @Override protected boolean isIgnoreFailingProcessor() { return true; } }; InjectorBuilder.create(getManagerFactory()).build().inject(processor); processor.process(resource, reader, new StringWriter()); } private void persistFingerprintsForCssImports(final Resource resource, final Reader reader) throws IOException { forEachCssImportApply(new Function<String, Void>() { public Void apply(final String importedUri) throws Exception { persistResourceFingerprints(Resource.create(importedUri, ResourceType.CSS)); return null; } }, resource, reader); } private void detectChangeForCssImports(final Resource resource, final Reader reader, final AtomicBoolean changeDetected) throws IOException { forEachCssImportApply(new Function<String, Void>() { public Void apply(final String importedUri) throws Exception { final boolean isImportChanged = isResourceChanged(Resource.create(importedUri, ResourceType.CSS)); getLog().debug("\tisImportChanged: " + isImportChanged); if (isImportChanged) { changeDetected.set(true); // no need to continue throw new WroRuntimeException("Change detected. No need to continue processing"); } return null; } }, resource, reader); } /** * @return a list of groups changed by incremental builds. */ private List<String> getIncrementalGroupNames() throws Exception { final List<String> changedGroupNames = new ArrayList<String>(); final String targetGroups = getTargetGroups(); for (final Group group : getModel().getGroups()) { if (!targetGroups.isEmpty() && !targetGroups.contains(group.getName())) { //skip this group processing continue; } for (final Resource resource : group.getResources()) { getLog().debug("checking delta for resource: " + resource); if (isResourceChanged(resource)) { getLog().debug("detected change for resource: " + resource + " and group: " + group.getName()); changedGroupNames.add(group.getName()); // no need to check rest of resources from this group break; } } } return changedGroupNames; } private boolean isResourceChanged(final Resource resource) { final WroManager manager = getWroManager(); final HashStrategy hashStrategy = manager.getHashStrategy(); final UriLocatorFactory locatorFactory = manager.getUriLocatorFactory(); // using AtomicBoolean because we need to mutate this variable inside an anonymous class. final AtomicBoolean changeDetected = new AtomicBoolean(false); try { final String fingerprint = hashStrategy.getHash(locatorFactory.locate(resource.getUri())); final String previousFingerprint = buildContext != null ? String .valueOf(buildContext.getValue(resource.getUri())) : null; getLog().debug("fingerprint <current, prev>: <" + fingerprint + ", " + previousFingerprint + ">"); changeDetected.set(fingerprint != null && !fingerprint.equals(previousFingerprint)); if (!changeDetected.get() && resource.getType() == ResourceType.CSS) { final Reader reader = new InputStreamReader(locatorFactory.locate(resource.getUri())); getLog().debug("Check @import directive from " + resource); // detect changes in imported resources. detectChangeForCssImports(resource, reader, changeDetected); } return changeDetected.get(); } catch (final IOException e) { getLog().debug("failed to check for delta resource: " + resource); } return false; } /** * @return true if the build was triggered by an incremental change. */ protected final boolean isIncrementalBuild() { return buildContext != null && buildContext.isIncremental(); } private List<String> getAllModelGroupNames() { return new WroModelInspector(getModel()).getGroupNames(); } private WroModel getModel() { return getWroManager().getModelFactory().create(); } private WroManager getWroManager() { try { return getManagerFactory().create(); } catch (final Exception e) { throw WroRuntimeException.wrap(e); } } /** * Checks if all required fields are configured. */ protected void validate() throws MojoExecutionException { if (wroFile == null) { throw new MojoExecutionException("contextFolder was not set!"); } if (contextFolder == null) { throw new MojoExecutionException("contextFolder was not set!"); } } /** * Update the classpath. */ protected final void extendPluginClasspath() throws MojoExecutionException { final List<String> classpathElements = new ArrayList<String>(); try { classpathElements.addAll(mavenProject.getRuntimeClasspathElements()); } catch (final DependencyResolutionRequiredException e) { throw new MojoExecutionException("Could not get compile classpath elements", e); } final ClassLoader classLoader = createClassLoader(classpathElements); Thread.currentThread().setContextClassLoader(classLoader); } /** * @return {@link ClassRealm} based on project dependencies. */ private ClassLoader createClassLoader(final List<String> classpathElements) { getLog().debug("Classpath elements:"); final List<URL> urls = new ArrayList<URL>(); try { for (final String element : classpathElements) { final File elementFile = new File(element); getLog().debug("Adding element to plugin classpath: " + elementFile.getPath()); urls.add(elementFile.toURI().toURL()); } } catch (final Exception e) { getLog().error("Error retreiving URL for artifact", e); throw new RuntimeException(e); } return new URLClassLoader(urls.toArray(new URL[] {}), Thread.currentThread().getContextClassLoader()); } /** * @param contextFolder * the servletContextFolder to set * @VisibleForTesting */ void setContextFolder(final File contextFolder) { this.contextFolder = contextFolder; } /** * @param wroFile * the wroFile to set * @VisibleForTesting */ void setWroFile(final File wroFile) { this.wroFile = wroFile; } /** * @return the wroFile * @VisibleForTesting */ File getWroFile() { return this.wroFile; } /** * @return the contextFolder * @VisibleForTesting */ File getContextFolder() { return this.contextFolder; } /** * @param minimize * flag for minimization. * @VisibleForTesting */ void setMinimize(final boolean minimize) { this.minimize = minimize; } /** * @param ignoreMissingResources * the ignoreMissingResources to set * @VisibleForTesting */ void setIgnoreMissingResources(final boolean ignoreMissingResources) { this.ignoreMissingResources = ignoreMissingResources; } /** * @return the minimize * @VisibleForTesting */ boolean isMinimize() { return this.minimize; } /** * @return the ignoreMissingResources * @VisibleForTesting */ boolean isIgnoreMissingResources() { return this.ignoreMissingResources; } /** * Used for testing. * * @param mavenProject * the mavenProject to set */ void setMavenProject(final MavenProject mavenProject) { this.mavenProject = mavenProject; } /** * @return the targetGroups * @VisibleForTesting */ String getTargetGroups() { return this.targetGroups; } /** * @param versionEncoder * (targetGroups) comma separated group names. * @VisibleForTesting */ void setTargetGroups(final String targetGroups) { this.targetGroups = targetGroups; } /** * @param wroManagerFactory * fully qualified name of the {@link WroManagerFactory} class. * @VisibleForTesting */ void setWroManagerFactory(final String wroManagerFactory) { this.wroManagerFactory = wroManagerFactory; } /** * @param extraConfigFile * the extraConfigFile to set * @VisibleForTesting */ void setExtraConfigFile(final File extraConfigFile) { this.extraConfigFile = extraConfigFile; } /** * @VisibleForTesting */ void setBuildContext(final BuildContext buildContext) { this.buildContext = buildContext; } }
package org.elasticsearch.xpack.ccr; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterStateListener; import org.elasticsearch.cluster.RestoreInProgress; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.repositories.Repository; import org.elasticsearch.repositories.RepositoryMissingException; import org.elasticsearch.snapshots.RestoreInfo; import org.elasticsearch.snapshots.RestoreService; import org.elasticsearch.snapshots.Snapshot; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.CcrIntegTestCase; import org.elasticsearch.xpack.ccr.action.repositories.GetCcrRestoreFileChunkAction; import org.elasticsearch.xpack.ccr.repository.CcrRepository; import org.elasticsearch.xpack.ccr.repository.CcrRestoreSourceService; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Collections.singletonMap; import static org.elasticsearch.snapshots.RestoreService.restoreInProgress; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.lessThan; // TODO: Fold this integration test into a more expansive integration test as more bootstrap from remote work // TODO: is completed. public class CcrRepositoryIT extends CcrIntegTestCase { private final IndicesOptions indicesOptions = IndicesOptions.strictSingleIndexNoExpandForbidClosed(); public void testThatRepositoryIsPutAndRemovedWhenRemoteClusterIsUpdated() throws Exception { String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; final RepositoriesService repositoriesService = getFollowerCluster().getDataOrMasterNodeInstances(RepositoriesService.class).iterator().next(); try { Repository repository = repositoriesService.repository(leaderClusterRepoName); assertEquals(CcrRepository.TYPE, repository.getMetadata().type()); assertEquals(leaderClusterRepoName, repository.getMetadata().name()); } catch (RepositoryMissingException e) { fail("need repository"); } ClusterUpdateSettingsRequest putSecondCluster = new ClusterUpdateSettingsRequest(); String address = getFollowerCluster().getDataNodeInstance(TransportService.class).boundAddress().publishAddress().toString(); putSecondCluster.persistentSettings(Settings.builder().put("cluster.remote.follower_cluster_copy.seeds", address)); assertAcked(followerClient().admin().cluster().updateSettings(putSecondCluster).actionGet()); String followerCopyRepoName = CcrRepository.NAME_PREFIX + "follower_cluster_copy"; try { Repository repository = repositoriesService.repository(followerCopyRepoName); assertEquals(CcrRepository.TYPE, repository.getMetadata().type()); assertEquals(followerCopyRepoName, repository.getMetadata().name()); } catch (RepositoryMissingException e) { fail("need repository"); } ClusterUpdateSettingsRequest deleteLeaderCluster = new ClusterUpdateSettingsRequest(); deleteLeaderCluster.persistentSettings(Settings.builder().put("cluster.remote.leader_cluster.seeds", "")); assertAcked(followerClient().admin().cluster().updateSettings(deleteLeaderCluster).actionGet()); expectThrows(RepositoryMissingException.class, () -> repositoriesService.repository(leaderClusterRepoName)); ClusterUpdateSettingsRequest deleteSecondCluster = new ClusterUpdateSettingsRequest(); deleteSecondCluster.persistentSettings(Settings.builder().put("cluster.remote.follower_cluster_copy.seeds", "")); assertAcked(followerClient().admin().cluster().updateSettings(deleteSecondCluster).actionGet()); expectThrows(RepositoryMissingException.class, () -> repositoriesService.repository(followerCopyRepoName)); ClusterUpdateSettingsRequest putLeaderRequest = new ClusterUpdateSettingsRequest(); address = getLeaderCluster().getDataNodeInstance(TransportService.class).boundAddress().publishAddress().toString(); putLeaderRequest.persistentSettings(Settings.builder().put("cluster.remote.leader_cluster.seeds", address)); assertAcked(followerClient().admin().cluster().updateSettings(putLeaderRequest).actionGet()); } public void testThatRepositoryRecoversEmptyIndexBasedOnLeaderSettings() throws IOException { String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; String leaderIndex = "index1"; String followerIndex = "index2"; final int numberOfPrimaryShards = randomIntBetween(1, 3); final String leaderIndexSettings = getIndexSettings(numberOfPrimaryShards, between(0, 1), singletonMap(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), "true")); assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON)); ensureLeaderGreen(leaderIndex); final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class); final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class); Settings.Builder settingsBuilder = Settings.builder() .put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, followerIndex) .put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true); RestoreSnapshotRequest restoreRequest = new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST) .indices(leaderIndex).indicesOptions(indicesOptions).renamePattern("^(.*)$") .renameReplacement(followerIndex).masterNodeTimeout(new TimeValue(1L, TimeUnit.HOURS)) .indexSettings(settingsBuilder); PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture(); restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future)); RestoreInfo restoreInfo = future.actionGet(); assertEquals(restoreInfo.totalShards(), restoreInfo.successfulShards()); assertEquals(0, restoreInfo.failedShards()); ClusterStateResponse leaderState = leaderClient() .admin() .cluster() .prepareState() .clear() .setMetaData(true) .setIndices(leaderIndex) .get(); ClusterStateResponse followerState = followerClient() .admin() .cluster() .prepareState() .clear() .setMetaData(true) .setIndices(followerIndex) .get(); IndexMetaData leaderMetadata = leaderState.getState().metaData().index(leaderIndex); IndexMetaData followerMetadata = followerState.getState().metaData().index(followerIndex); assertEquals(leaderMetadata.getNumberOfShards(), followerMetadata.getNumberOfShards()); Map<String, String> ccrMetadata = followerMetadata.getCustomData(Ccr.CCR_CUSTOM_METADATA_KEY); assertEquals(leaderIndex, ccrMetadata.get(Ccr.CCR_CUSTOM_METADATA_LEADER_INDEX_NAME_KEY)); assertEquals(leaderMetadata.getIndexUUID(), ccrMetadata.get(Ccr.CCR_CUSTOM_METADATA_LEADER_INDEX_UUID_KEY)); assertEquals("leader_cluster", ccrMetadata.get(Ccr.CCR_CUSTOM_METADATA_REMOTE_CLUSTER_NAME_KEY)); assertEquals(followerIndex, followerMetadata.getSettings().get(IndexMetaData.SETTING_INDEX_PROVIDED_NAME)); assertEquals(true, IndexSettings.INDEX_SOFT_DELETES_SETTING.get(followerMetadata.getSettings())); // UUID is changed so that we can follow indexes on same cluster assertNotEquals(leaderMetadata.getIndexUUID(), followerMetadata.getIndexUUID()); } public void testDocsAreRecovered() throws Exception { String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; String leaderIndex = "index1"; String followerIndex = "index2"; final int numberOfPrimaryShards = randomIntBetween(1, 3); final String leaderIndexSettings = getIndexSettings(numberOfPrimaryShards, between(0, 1), singletonMap(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), "true")); assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON)); ensureLeaderGreen(leaderIndex); final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class); final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class); final int firstBatchNumDocs = randomIntBetween(1, 64); logger.info("Indexing [{}] docs as first batch", firstBatchNumDocs); for (int i = 0; i < firstBatchNumDocs; i++) { final String source = String.format(Locale.ROOT, "{\"f\":%d}", i); leaderClient().prepareIndex("index1", "doc", Integer.toString(i)).setSource(source, XContentType.JSON).get(); } leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get(); AtomicBoolean isRunning = new AtomicBoolean(true); // Concurrently index new docs with mapping changes Thread thread = new Thread(() -> { char[] chars = "abcdeghijklmnopqrstuvwxyz".toCharArray(); for (char c : chars) { if (isRunning.get() == false) { break; } final String source; long l = randomLongBetween(0, 50000); if (randomBoolean()) { source = String.format(Locale.ROOT, "{\"%c\":%d}", c, l); } else { source = String.format(Locale.ROOT, "{\"%c\":\"%d\"}", c, l); } for (int i = 64; i < 150; i++) { if (isRunning.get() == false) { break; } leaderClient().prepareIndex("index1", "doc", Long.toString(i)).setSource(source, XContentType.JSON).get(); if (rarely()) { leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).get(); } } leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get(); } }); thread.start(); Settings.Builder settingsBuilder = Settings.builder() .put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, followerIndex) .put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true); RestoreSnapshotRequest restoreRequest = new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST) .indices(leaderIndex).indicesOptions(indicesOptions).renamePattern("^(.*)$") .renameReplacement(followerIndex).masterNodeTimeout(new TimeValue(1L, TimeUnit.HOURS)) .indexSettings(settingsBuilder); PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture(); restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future)); RestoreInfo restoreInfo = future.actionGet(); assertEquals(restoreInfo.totalShards(), restoreInfo.successfulShards()); assertEquals(0, restoreInfo.failedShards()); for (int i = 0; i < firstBatchNumDocs; ++i) { assertExpectedDocument(followerIndex, i); } isRunning.set(false); thread.join(); } public void testRateLimitingIsEmployed() throws Exception { boolean followerRateLimiting = randomBoolean(); ClusterUpdateSettingsRequest settingsRequest = new ClusterUpdateSettingsRequest(); settingsRequest.persistentSettings(Settings.builder().put(CcrSettings.RECOVERY_MAX_BYTES_PER_SECOND.getKey(), "10K")); if (followerRateLimiting) { assertAcked(followerClient().admin().cluster().updateSettings(settingsRequest).actionGet()); } else { assertAcked(leaderClient().admin().cluster().updateSettings(settingsRequest).actionGet()); } String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; String leaderIndex = "index1"; String followerIndex = "index2"; final int numberOfPrimaryShards = randomIntBetween(1, 3); final String leaderIndexSettings = getIndexSettings(numberOfPrimaryShards, between(0, 1), singletonMap(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), "true")); assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON)); ensureLeaderGreen(leaderIndex); final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class); final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class); List<CcrRepository> repositories = new ArrayList<>(); List<CcrRestoreSourceService> restoreSources = new ArrayList<>(); for (RepositoriesService repositoriesService : getFollowerCluster().getDataOrMasterNodeInstances(RepositoriesService.class)) { Repository repository = repositoriesService.repository(leaderClusterRepoName); repositories.add((CcrRepository) repository); } for (CcrRestoreSourceService restoreSource : getLeaderCluster().getDataOrMasterNodeInstances(CcrRestoreSourceService.class)) { restoreSources.add(restoreSource); } logger.info("--> indexing some data"); for (int i = 0; i < 100; i++) { final String source = String.format(Locale.ROOT, "{\"f\":%d}", i); leaderClient().prepareIndex("index1", "doc", Integer.toString(i)).setSource(source, XContentType.JSON).get(); } leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get(); Settings.Builder settingsBuilder = Settings.builder() .put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, followerIndex) .put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true); RestoreSnapshotRequest restoreRequest = new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST) .indices(leaderIndex).indicesOptions(indicesOptions).renamePattern("^(.*)$") .renameReplacement(followerIndex).masterNodeTimeout(new TimeValue(1L, TimeUnit.HOURS)) .indexSettings(settingsBuilder); PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture(); restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future)); future.actionGet(); if (followerRateLimiting) { assertTrue(repositories.stream().anyMatch(cr -> cr.getRestoreThrottleTimeInNanos() > 0)); } else { assertTrue(restoreSources.stream().anyMatch(cr -> cr.getThrottleTime() > 0)); } settingsRequest = new ClusterUpdateSettingsRequest(); ByteSizeValue defaultValue = CcrSettings.RECOVERY_MAX_BYTES_PER_SECOND.getDefault(Settings.EMPTY); settingsRequest.persistentSettings(Settings.builder().put(CcrSettings.RECOVERY_MAX_BYTES_PER_SECOND.getKey(), defaultValue)); if (followerRateLimiting) { assertAcked(followerClient().admin().cluster().updateSettings(settingsRequest).actionGet()); } else { assertAcked(leaderClient().admin().cluster().updateSettings(settingsRequest).actionGet()); } } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/38027") public void testIndividualActionsTimeout() throws Exception { ClusterUpdateSettingsRequest settingsRequest = new ClusterUpdateSettingsRequest(); TimeValue timeValue = TimeValue.timeValueMillis(100); settingsRequest.persistentSettings(Settings.builder().put(CcrSettings.INDICES_RECOVERY_ACTION_TIMEOUT_SETTING.getKey(), timeValue)); assertAcked(followerClient().admin().cluster().updateSettings(settingsRequest).actionGet()); String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; String leaderIndex = "index1"; String followerIndex = "index2"; final int numberOfPrimaryShards = randomIntBetween(1, 3); final String leaderIndexSettings = getIndexSettings(numberOfPrimaryShards, between(0, 1), singletonMap(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), "true")); assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON)); ensureLeaderGreen(leaderIndex); List<MockTransportService> transportServices = new ArrayList<>(); for (TransportService transportService : getFollowerCluster().getDataOrMasterNodeInstances(TransportService.class)) { MockTransportService mockTransportService = (MockTransportService) transportService; transportServices.add(mockTransportService); mockTransportService.addSendBehavior((connection, requestId, action, request, options) -> { if (action.equals(GetCcrRestoreFileChunkAction.NAME) == false) { connection.sendRequest(requestId, action, request, options); } }); } logger.info("--> indexing some data"); for (int i = 0; i < 100; i++) { final String source = String.format(Locale.ROOT, "{\"f\":%d}", i); leaderClient().prepareIndex("index1", "doc", Integer.toString(i)).setSource(source, XContentType.JSON).get(); } leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get(); Settings.Builder settingsBuilder = Settings.builder() .put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, followerIndex) .put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true); RestoreSnapshotRequest restoreRequest = new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST) .indices(leaderIndex).indicesOptions(indicesOptions).renamePattern("^(.*)$") .renameReplacement(followerIndex).masterNodeTimeout(new TimeValue(1L, TimeUnit.HOURS)) .indexSettings(settingsBuilder); final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class); final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class); PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture(); restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future)); // Depending on when the timeout occurs this can fail in two ways. If it times-out when fetching // metadata this will throw an exception. If it times-out when restoring a shard, the shard will // be marked as failed. Either one is a success for the purpose of this test. try { RestoreInfo restoreInfo = future.actionGet(); assertThat(restoreInfo.failedShards(), greaterThan(0)); assertThat(restoreInfo.successfulShards(), lessThan(restoreInfo.totalShards())); assertEquals(numberOfPrimaryShards, restoreInfo.totalShards()); } catch (Exception e) { assertThat(ExceptionsHelper.unwrapCause(e), instanceOf(ElasticsearchTimeoutException.class)); } for (MockTransportService transportService : transportServices) { transportService.clearAllRules(); } settingsRequest = new ClusterUpdateSettingsRequest(); TimeValue defaultValue = CcrSettings.INDICES_RECOVERY_ACTION_TIMEOUT_SETTING.getDefault(Settings.EMPTY); settingsRequest.persistentSettings(Settings.builder().put(CcrSettings.INDICES_RECOVERY_ACTION_TIMEOUT_SETTING.getKey(), defaultValue)); assertAcked(followerClient().admin().cluster().updateSettings(settingsRequest).actionGet()); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/37887") public void testFollowerMappingIsUpdated() throws IOException { String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster"; String leaderIndex = "index1"; String followerIndex = "index2"; final int numberOfPrimaryShards = randomIntBetween(1, 3); final String leaderIndexSettings = getIndexSettings(numberOfPrimaryShards, between(0, 1), singletonMap(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), "true")); assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON)); ensureLeaderGreen(leaderIndex); final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class); final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class); Settings.Builder settingsBuilder = Settings.builder() .put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, followerIndex) .put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true); RestoreSnapshotRequest restoreRequest = new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST) .indices(leaderIndex).indicesOptions(indicesOptions).renamePattern("^(.*)$") .renameReplacement(followerIndex).masterNodeTimeout(new TimeValue(1L, TimeUnit.HOURS)) .indexSettings(settingsBuilder); // TODO: Eventually when the file recovery work is complete, we should test updated mappings by // indexing to the leader while the recovery is happening. However, into order to that test mappings // are updated prior to that work, we index documents in the clear session callback. This will // ensure a mapping change prior to the final mapping check on the follower side. for (CcrRestoreSourceService restoreSourceService : getLeaderCluster().getDataNodeInstances(CcrRestoreSourceService.class)) { restoreSourceService.addCloseSessionListener(s -> { final String source = String.format(Locale.ROOT, "{\"k\":%d}", 1); leaderClient().prepareIndex("index1", "doc", Long.toString(1)).setSource(source, XContentType.JSON).get(); }); } PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture(); restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future)); RestoreInfo restoreInfo = future.actionGet(); assertEquals(restoreInfo.totalShards(), restoreInfo.successfulShards()); assertEquals(0, restoreInfo.failedShards()); ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.clear(); clusterStateRequest.metaData(true); clusterStateRequest.indices(followerIndex); ClusterStateResponse clusterState = followerClient().admin().cluster().state(clusterStateRequest).actionGet(); IndexMetaData followerIndexMetadata = clusterState.getState().metaData().index(followerIndex); assertEquals(2, followerIndexMetadata.getMappingVersion()); MappingMetaData mappingMetaData = followerClient().admin().indices().prepareGetMappings("index2").get().getMappings() .get("index2").get("doc"); assertThat(XContentMapValues.extractValue("properties.k.type", mappingMetaData.sourceAsMap()), equalTo("long")); } private void assertExpectedDocument(String followerIndex, final int value) { final GetResponse getResponse = followerClient().prepareGet(followerIndex, "doc", Integer.toString(value)).get(); assertTrue("Doc with id [" + value + "] is missing", getResponse.isExists()); assertTrue((getResponse.getSource().containsKey("f"))); assertThat(getResponse.getSource().get("f"), equalTo(value)); } private ActionListener<RestoreService.RestoreCompletionResponse> waitForRestore(ClusterService clusterService, ActionListener<RestoreInfo> listener) { return new ActionListener<RestoreService.RestoreCompletionResponse>() { @Override public void onResponse(RestoreService.RestoreCompletionResponse restoreCompletionResponse) { if (restoreCompletionResponse.getRestoreInfo() == null) { final Snapshot snapshot = restoreCompletionResponse.getSnapshot(); final String uuid = restoreCompletionResponse.getUuid(); ClusterStateListener clusterStateListener = new ClusterStateListener() { @Override public void clusterChanged(ClusterChangedEvent changedEvent) { final RestoreInProgress.Entry prevEntry = restoreInProgress(changedEvent.previousState(), uuid); final RestoreInProgress.Entry newEntry = restoreInProgress(changedEvent.state(), uuid); if (prevEntry == null) { // When there is a master failure after a restore has been started, this listener might not be registered // on the current master and as such it might miss some intermediary cluster states due to batching. // Clean up listener in that case and acknowledge completion of restore operation to client. clusterService.removeListener(this); listener.onResponse(null); } else if (newEntry == null) { clusterService.removeListener(this); ImmutableOpenMap<ShardId, RestoreInProgress.ShardRestoreStatus> shards = prevEntry.shards(); RestoreInfo ri = new RestoreInfo(prevEntry.snapshot().getSnapshotId().getName(), prevEntry.indices(), shards.size(), shards.size() - RestoreService.failedShards(shards)); logger.debug("restore of [{}] completed", snapshot); listener.onResponse(ri); } else { // restore not completed yet, wait for next cluster state update } } }; clusterService.addListener(clusterStateListener); } else { listener.onResponse(restoreCompletionResponse.getRestoreInfo()); } } @Override public void onFailure(Exception t) { listener.onFailure(t); } }; } }
package org.elasticsearch.xpack.core; import org.apache.logging.log4j.LogManager; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.ssl.SslClientAuthenticationMode; import org.elasticsearch.common.ssl.SslVerificationMode; import org.elasticsearch.jdk.JavaVersion; import org.elasticsearch.xpack.core.security.SecurityField; import org.elasticsearch.xpack.core.security.authc.support.Hasher; import org.elasticsearch.xpack.core.ssl.SSLConfigurationSettings; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.function.Function; import javax.crypto.SecretKeyFactory; import javax.net.ssl.SSLContext; import static org.elasticsearch.xpack.core.security.SecurityField.USER_SETTING; /** * A container for xpack setting constants. */ public class XPackSettings { private static final boolean IS_DARWIN_AARCH64; static { final String name = System.getProperty("os.name"); final String arch = System.getProperty("os.arch"); IS_DARWIN_AARCH64 = "aarch64".equals(arch) && name.startsWith("Mac OS X"); } private XPackSettings() { throw new IllegalStateException("Utility class should not be instantiated"); } /** * Setting for controlling whether or not CCR is enabled. */ public static final Setting<Boolean> CCR_ENABLED_SETTING = Setting.boolSetting("xpack.ccr.enabled", true, Property.NodeScope); /** Setting for enabling or disabling security. Defaults to true. */ public static final Setting<Boolean> SECURITY_ENABLED = Setting.boolSetting("xpack.security.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling watcher. Defaults to true. */ public static final Setting<Boolean> WATCHER_ENABLED = Setting.boolSetting("xpack.watcher.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling graph. Defaults to true. */ public static final Setting<Boolean> GRAPH_ENABLED = Setting.boolSetting("xpack.graph.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling machine learning. Defaults to true. */ public static final Setting<Boolean> MACHINE_LEARNING_ENABLED = Setting.boolSetting("xpack.ml.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling auditing. Defaults to false. */ public static final Setting<Boolean> AUDIT_ENABLED = Setting.boolSetting("xpack.security.audit.enabled", false, Setting.Property.NodeScope); /** Setting for enabling or disabling document/field level security. Defaults to true. */ public static final Setting<Boolean> DLS_FLS_ENABLED = Setting.boolSetting("xpack.security.dls_fls.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling TLS. Defaults to false. */ public static final Setting<Boolean> TRANSPORT_SSL_ENABLED = Setting.boolSetting("xpack.security.transport.ssl.enabled", false, Property.NodeScope); /** Setting for enabling or disabling http ssl. Defaults to false. */ public static final Setting<Boolean> HTTP_SSL_ENABLED = Setting.boolSetting("xpack.security.http.ssl.enabled", false, Setting.Property.NodeScope); /** Setting for enabling or disabling the reserved realm. Defaults to true */ public static final Setting<Boolean> RESERVED_REALM_ENABLED_SETTING = Setting.boolSetting("xpack.security.authc.reserved_realm.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling the token service. Defaults to the value of https being enabled */ public static final Setting<Boolean> TOKEN_SERVICE_ENABLED_SETTING = Setting.boolSetting("xpack.security.authc.token.enabled", XPackSettings.HTTP_SSL_ENABLED, Setting.Property.NodeScope); /** Setting for enabling or disabling the api key service. Defaults to true */ public static final Setting<Boolean> API_KEY_SERVICE_ENABLED_SETTING = Setting.boolSetting("xpack.security.authc.api_key.enabled", true, Setting.Property.NodeScope); /** Setting for enabling or disabling FIPS mode. Defaults to false */ public static final Setting<Boolean> FIPS_MODE_ENABLED = Setting.boolSetting("xpack.security.fips_mode.enabled", false, Property.NodeScope); /** Setting for enabling enrollment process; set-up by the es start-up script */ public static final Setting<Boolean> ENROLLMENT_ENABLED = Setting.boolSetting("xpack.security.enrollment.enabled", false, Property.NodeScope); public static final Setting<Boolean> SECURITY_AUTOCONFIGURATION_ENABLED = Setting.boolSetting("xpack.security.autoconfiguration.enabled", true, Property.NodeScope); /* * SSL settings. These are the settings that are specifically registered for SSL. Many are private as we do not explicitly use them * but instead parse based on a prefix (eg *.ssl.*) */ private static final List<String> JDK11_CIPHERS = List.of( "TLS_AES_256_GCM_SHA384", "TLS_AES_128_GCM_SHA256", // TLSv1.3 cipher has PFS, AEAD, hardware support "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", // PFS, AEAD, hardware support "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", // PFS, AEAD, hardware support "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", // PFS, hardware support "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", // PFS, hardware support "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", // PFS, hardware support "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", // PFS, hardware support "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256", // AEAD, hardware support "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256", // hardware support "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA"); // hardware support private static final List<String> JDK12_CIPHERS = List.of( "TLS_AES_256_GCM_SHA384", "TLS_AES_128_GCM_SHA256", // TLSv1.3 cipher has PFS, AEAD, hardware support "TLS_CHACHA20_POLY1305_SHA256", // TLSv1.3 cipher has PFS, AEAD "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", // PFS, AEAD, hardware support "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", // PFS, AEAD, hardware support "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", // PFS, AEAD "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", // PFS, hardware support "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", // PFS, hardware support "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", // PFS, hardware support "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", // PFS, hardware support "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256", // AEAD, hardware support "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256", // hardware support "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA"); // hardware support public static final List<String> DEFAULT_CIPHERS = JavaVersion.current().compareTo(JavaVersion.parse("12")) > -1 ? JDK12_CIPHERS : JDK11_CIPHERS; /* * Do not allow insecure hashing algorithms to be used for password hashing */ public static final Setting<String> PASSWORD_HASHING_ALGORITHM = new Setting<>( new Setting.SimpleKey("xpack.security.authc.password_hashing.algorithm"), (s) -> { if (XPackSettings.FIPS_MODE_ENABLED.get(s)) { return Hasher.PBKDF2_STRETCH.name(); } else { return Hasher.BCRYPT.name(); } }, Function.identity(), v -> { if (Hasher.getAvailableAlgoStoredHash().contains(v.toLowerCase(Locale.ROOT)) == false) { throw new IllegalArgumentException("Invalid algorithm: " + v + ". Valid values for password hashing are " + Hasher.getAvailableAlgoStoredHash().toString()); } else if (v.regionMatches(true, 0, "pbkdf2", 0, "pbkdf2".length())) { try { SecretKeyFactory.getInstance("PBKDF2withHMACSHA512"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException( "Support for PBKDF2WithHMACSHA512 must be available in order to use any of the " + "PBKDF2 algorithms for the [xpack.security.authc.password_hashing.algorithm] setting.", e); } } }, Property.NodeScope); // TODO: This setting of hashing algorithm can share code with the one for password when pbkdf2_stretch is the default for both public static final Setting<String> SERVICE_TOKEN_HASHING_ALGORITHM = new Setting<>( new Setting.SimpleKey("xpack.security.authc.service_token_hashing.algorithm"), (s) -> "PBKDF2_STRETCH", Function.identity(), v -> { if (Hasher.getAvailableAlgoStoredHash().contains(v.toLowerCase(Locale.ROOT)) == false) { throw new IllegalArgumentException("Invalid algorithm: " + v + ". Valid values for password hashing are " + Hasher.getAvailableAlgoStoredHash().toString()); } else if (v.regionMatches(true, 0, "pbkdf2", 0, "pbkdf2".length())) { try { SecretKeyFactory.getInstance("PBKDF2withHMACSHA512"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException( "Support for PBKDF2WithHMACSHA512 must be available in order to use any of the " + "PBKDF2 algorithms for the [xpack.security.authc.service_token_hashing.algorithm] setting.", e); } } }, Property.NodeScope); public static final List<String> DEFAULT_SUPPORTED_PROTOCOLS; static { boolean supportsTLSv13 = false; try { SSLContext.getInstance("TLSv1.3"); supportsTLSv13 = true; } catch (NoSuchAlgorithmException e) { // BCJSSE in FIPS mode doesn't support TLSv1.3 yet. LogManager.getLogger(XPackSettings.class).debug("TLSv1.3 is not supported", e); } DEFAULT_SUPPORTED_PROTOCOLS = supportsTLSv13 ? Arrays.asList("TLSv1.3", "TLSv1.2", "TLSv1.1") : Arrays.asList("TLSv1.2", "TLSv1.1"); } public static final SslClientAuthenticationMode CLIENT_AUTH_DEFAULT = SslClientAuthenticationMode.REQUIRED; public static final SslClientAuthenticationMode HTTP_CLIENT_AUTH_DEFAULT = SslClientAuthenticationMode.NONE; public static final SslVerificationMode VERIFICATION_MODE_DEFAULT = SslVerificationMode.FULL; // http specific settings public static final String HTTP_SSL_PREFIX = SecurityField.setting("http.ssl."); private static final SSLConfigurationSettings HTTP_SSL = SSLConfigurationSettings.withPrefix(HTTP_SSL_PREFIX, true); // transport specific settings public static final String TRANSPORT_SSL_PREFIX = SecurityField.setting("transport.ssl."); private static final SSLConfigurationSettings TRANSPORT_SSL = SSLConfigurationSettings.withPrefix(TRANSPORT_SSL_PREFIX, true); /** Returns all settings created in {@link XPackSettings}. */ public static List<Setting<?>> getAllSettings() { ArrayList<Setting<?>> settings = new ArrayList<>(); settings.addAll(HTTP_SSL.getEnabledSettings()); settings.addAll(TRANSPORT_SSL.getEnabledSettings()); settings.add(SECURITY_ENABLED); settings.add(GRAPH_ENABLED); settings.add(MACHINE_LEARNING_ENABLED); settings.add(AUDIT_ENABLED); settings.add(WATCHER_ENABLED); settings.add(DLS_FLS_ENABLED); settings.add(TRANSPORT_SSL_ENABLED); settings.add(HTTP_SSL_ENABLED); settings.add(RESERVED_REALM_ENABLED_SETTING); settings.add(TOKEN_SERVICE_ENABLED_SETTING); settings.add(API_KEY_SERVICE_ENABLED_SETTING); settings.add(USER_SETTING); settings.add(PASSWORD_HASHING_ALGORITHM); settings.add(ENROLLMENT_ENABLED); settings.add(SECURITY_AUTOCONFIGURATION_ENABLED); return Collections.unmodifiableList(settings); } }
package com.eqt.tfi.util.az; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.GenericOptionsParser; /** * This is just here to learn what Azkaban is doing. * spits out all the arguments and vars it receives. * @author gman * */ public class OptionsPrinter { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if(args != null) { System.out.println(); System.out.println("Origional Arguments:"); for(String arg : args) System.out.println(arg); } GenericOptionsParser p = new GenericOptionsParser(args); Configuration conf = p.getConfiguration(); if(p.getRemainingArgs() != null) { System.out.println(); System.out.println(" System.out.println("args not picked up by a hadoop conf:"); for(String arg : p.getRemainingArgs()) System.out.println(arg); } Map<String, String> getenv = System.getenv(); System.out.println(); System.out.println(" System.out.println("Current system enviroment variables:"); for(String key : getenv.keySet()) System.out.println(key + "="+getenv.get(key)); System.out.println(); System.out.println(" System.out.println("Hadoop Configuration:"); for(Iterator<Entry<String, String>> it = conf.iterator();it.hasNext();) { Entry<String, String> next = it.next(); System.out.println(next.getKey() + ": " + next.getValue()); } } }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import com.facebook.R; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.reference.Reference; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.view.View.MeasureSpec.makeMeasureSpec; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState; import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_MOUNT; import static com.facebook.litho.ComponentsLogger.EVENT_PREPARE_MOUNT; import static com.facebook.litho.ComponentsLogger.EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH; import static com.facebook.litho.ComponentsLogger.PARAM_IS_DIRTY; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_MOUNTED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_MOVED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_NO_OP_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UNCHANGED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UNMOUNTED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UPDATED_COUNT; import static com.facebook.litho.ThreadUtils.assertMainThread; /** * Encapsulates the mounted state of a {@link Component}. Provides APIs to update state * by recycling existing UI elements e.g. {@link Drawable}s. * * @see #mount(LayoutState, Rect) * @see ComponentView * @see LayoutState */ class MountState { static final int ROOT_HOST_ID = 0; // Holds the current list of mounted items. // Should always be used within a draw lock. private final LongSparseArray<MountItem> mIndexToItemMap; // Holds a list with information about the components linked to the VisibilityOutputs that are // stored in LayoutState. An item is inserted in this map if its corresponding component is // visible. When the component exits the viewport, the item associated with it is removed from the // map. private final LongSparseArray<VisibilityItem> mVisibilityIdToItemMap; // Holds a list of MountItems that are currently mounted which can mount incrementally. private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems; // A map from test key to a list of one or more `TestItem`s which is only allocated // and populated during test runs. private final Map<String, Deque<TestItem>> mTestItemMap; private long[] mLayoutOutputsIds; // True if we are receiving a new LayoutState and we need to completely // refresh the content of the HostComponent. Always set from the main thread. private boolean mIsDirty; // Holds the list of known component hosts during a mount pass. private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>(); private static final Rect sTempRect = new Rect(); private final ComponentContext mContext; private final ComponentView mComponentView; private final Rect mPreviousLocalVisibleRect = new Rect(); private final PrepareMountStats mPrepareMountStats = new PrepareMountStats(); private final MountStats mMountStats = new MountStats(); private TransitionManager mTransitionManager; private int mPreviousTopsIndex; private int mPreviousBottomsIndex; private int mLastMountedComponentTreeId; private final MountItem mRootHostMountItem; public MountState(ComponentView view) { mIndexToItemMap = new LongSparseArray<>(); mVisibilityIdToItemMap = new LongSparseArray<>(); mCanMountIncrementallyMountItems = new LongSparseArray<>(); mContext = (ComponentContext) view.getContext(); mComponentView = view; mIsDirty = true; mTestItemMap = ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null; // The mount item representing the top-level ComponentView which // is always automatically mounted. mRootHostMountItem = ComponentsPools.acquireRootHostMountItem( HostComponent.create(), mComponentView, mComponentView); } /** * To be called whenever the components needs to start the mount process from scratch * e.g. when the component's props or layout change or when the components * gets attached to a host. */ void setDirty() { assertMainThread(); mIsDirty = true; mPreviousLocalVisibleRect.setEmpty(); } boolean isDirty() { assertMainThread(); return mIsDirty; } /** * Mount the layoutState on the pre-set HostView. * @param layoutState * @param localVisibleRect If this variable is null, then mount everything, since incremental * mount is not enabled. * Otherwise mount only what the rect (in local coordinates) contains */ void mount(LayoutState layoutState, Rect localVisibleRect) { assertMainThread(); ComponentsSystrace.beginSection("mount"); final ComponentTree componentTree = mComponentView.getComponent(); final ComponentsLogger logger = componentTree.getContext().getLogger(); if (logger != null) { logger.eventStart(EVENT_MOUNT, componentTree); } prepareTransitionManager(layoutState); if (mTransitionManager != null) { if (mIsDirty) { mTransitionManager.onNewTransitionContext(layoutState.getTransitionContext()); } mTransitionManager.onMountStart(); recordMountedItemsWithTransitionKeys( mTransitionManager, mIndexToItemMap, true /* isPreMount */); } if (mIsDirty) { suppressInvalidationsOnHosts(true); // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. prepareMount(layoutState); } mMountStats.reset(); final int componentTreeId = layoutState.getComponentTreeId(); final boolean isIncrementalMountEnabled = localVisibleRect != null; if (!isIncrementalMountEnabled || !performIncrementalMount(layoutState, localVisibleRect)) { for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i); final Component component = layoutOutput.getComponent(); ComponentsSystrace.beginSection(component.getSimpleName()); final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isMountable = !isIncrementalMountEnabled || isMountedHostWithChildContent(currentMountItem) || Rect.intersects(localVisibleRect, layoutOutput.getBounds()); if (isMountable && !isMounted) { mountLayoutOutput(i, layoutOutput, layoutState); } else if (!isMountable && isMounted) { unmountItem(mContext, i, mHostsByMarker); } else if (isMounted) { if (isIncrementalMountEnabled && canMountIncrementally(component)) { mountItemIncrementally(currentMountItem, layoutOutput.getBounds(), localVisibleRect); } if (mIsDirty) { final boolean useUpdateValueFromLayoutOutput = (componentTreeId >= 0) && (componentTreeId == mLastMountedComponentTreeId); final boolean itemUpdated = updateMountItemIfNeeded( layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput, logger); if (itemUpdated) { mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } } ComponentsSystrace.endSection(); } if (isIncrementalMountEnabled) { setupPreviousMountableOutputData(layoutState, localVisibleRect); } } mIsDirty = false; if (localVisibleRect != null) { mPreviousLocalVisibleRect.set(localVisibleRect); } processVisibilityOutputs(layoutState, localVisibleRect); if (mTransitionManager != null) { recordMountedItemsWithTransitionKeys( mTransitionManager, mIndexToItemMap, false /* isPreMount */); mTransitionManager.processTransitions(); } processTestOutputs(layoutState); suppressInvalidationsOnHosts(false); mLastMountedComponentTreeId = componentTreeId; if (logger != null) { final String logTag = componentTree.getContext().getLogTag(); logMountEnd(logger, logTag, componentTree, mMountStats); } ComponentsSystrace.endSection(); } private void processVisibilityOutputs(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect == null) { return; } for (int j = 0, size = layoutState.getVisibilityOutputCount(); j < size; j++) { final VisibilityOutput visibilityOutput = layoutState.getVisibilityOutputAt(j); final EventHandler visibleHandler = visibilityOutput.getVisibleEventHandler(); final EventHandler focusedHandler = visibilityOutput.getFocusedEventHandler(); final EventHandler fullImpressionHandler = visibilityOutput.getFullImpressionEventHandler(); final EventHandler invisibleHandler = visibilityOutput.getInvisibleEventHandler(); final long visibilityOutputId = visibilityOutput.getId(); final Rect visibilityOutputBounds = visibilityOutput.getBounds(); sTempRect.set(visibilityOutputBounds); final boolean isCurrentlyVisible = sTempRect.intersect(localVisibleRect); VisibilityItem visibilityItem = mVisibilityIdToItemMap.get(visibilityOutputId); if (isCurrentlyVisible) { // The component is visible now, but used to be outside the viewport. if (visibilityItem == null) { visibilityItem = ComponentsPools.acquireVisibilityItem(invisibleHandler); mVisibilityIdToItemMap.put(visibilityOutputId, visibilityItem); if (visibleHandler != null) { EventDispatcherUtils.dispatchOnVisible(visibleHandler); } } // Check if the component has entered the focused range. if (focusedHandler != null && !visibilityItem.isInFocusedRange()) { final View parent = (View) mComponentView.getParent(); if (hasEnteredFocusedRange( parent.getWidth(), parent.getHeight(), visibilityOutputBounds, sTempRect)) { visibilityItem.setIsInFocusedRange(); EventDispatcherUtils.dispatchOnFocused(focusedHandler); } } // If the component has not entered the full impression range yet, make sure to update the // information about the visible edges. if (fullImpressionHandler != null && !visibilityItem.isInFullImpressionRange()) { visibilityItem.setVisibleEdges(visibilityOutputBounds, sTempRect); if (visibilityItem.isInFullImpressionRange()) { EventDispatcherUtils.dispatchOnFullImpression(fullImpressionHandler); } } } else if (visibilityItem != null) { // The component is invisible now, but used to be visible. if (invisibleHandler != null) { EventDispatcherUtils.dispatchOnInvisible(invisibleHandler); } mVisibilityIdToItemMap.remove(visibilityOutputId); ComponentsPools.release(visibilityItem); } } } /** * Clears and re-populates the test item map if we are in e2e test mode. */ private void processTestOutputs(LayoutState layoutState) { if (mTestItemMap == null) { return; } for (Collection<TestItem> items : mTestItemMap.values()) { for (TestItem item : items) { ComponentsPools.release(item); } } mTestItemMap.clear(); for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) { final TestOutput testOutput = layoutState.getTestOutputAt(i); final long hostMarker = testOutput.getHostMarker(); final long layoutOutputId = testOutput.getLayoutOutputId(); final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId); final TestItem testItem = ComponentsPools.acquireTestItem(); testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker)); testItem.setBounds(testOutput.getBounds()); testItem.setTestKey(testOutput.getTestKey()); testItem.setContent(mountItem == null ? null : mountItem.getContent()); final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey()); final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items; updatedItems.add(testItem); mTestItemMap.put(testOutput.getTestKey(), updatedItems); } } private boolean isMountedHostWithChildContent(MountItem mountItem) { if (mountItem == null) { return false; } final Object content = mountItem.getContent(); if (!(content instanceof ComponentHost)) { return false; } final ComponentHost host = (ComponentHost) content; return host.getMountItemCount() > 0; } private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect.isEmpty()) { return; } final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops(); final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms(); final int mountableOutputCount = layoutState.getMountableOutputCount(); mPreviousTopsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) { mPreviousTopsIndex = i; break; } } mPreviousBottomsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) { mPreviousBottomsIndex = i; break; } } } private void clearVisibilityItems() { for (int i = mVisibilityIdToItemMap.size() - 1; i >= 0; i final VisibilityItem visibilityItem = mVisibilityIdToItemMap.valueAt(i); final EventHandler invisibleHandler = visibilityItem.getInvisibleHandler(); if (invisibleHandler != null) { EventDispatcherUtils.dispatchOnInvisible(invisibleHandler); } mVisibilityIdToItemMap.removeAt(i); ComponentsPools.release(visibilityItem); } } private void registerHost(long id, ComponentHost host) { host.suppressInvalidations(true); mHostsByMarker.put(id, host); } /** * Returns true if the component has entered the focused visible range. */ static boolean hasEnteredFocusedRange( int viewportWidth, int viewportHeight, Rect componentBounds, Rect componentVisibleBounds) { final int halfViewportArea = viewportWidth * viewportHeight / 2; final int totalComponentArea = computeRectArea(componentBounds); final int visibleComponentArea = computeRectArea(componentVisibleBounds); // The component has entered the focused range either if it is larger than half of the viewport // and it occupies at least half of the viewport or if it is smaller than half of the viewport // and it is fully visible. return (totalComponentArea >= halfViewportArea) ? (visibleComponentArea >= halfViewportArea) : componentBounds.equals(componentVisibleBounds); } private static int computeRectArea(Rect rect) { return rect.isEmpty() ? 0 : (rect.width() * rect.height()); } private void suppressInvalidationsOnHosts(boolean suppressInvalidations) { for (int i = mHostsByMarker.size() - 1; i >= 0; i mHostsByMarker.valueAt(i).suppressInvalidations(suppressInvalidations); } } private boolean updateMountItemIfNeeded( LayoutOutput layoutOutput, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, ComponentsLogger logger) { final Component layoutOutputComponent = layoutOutput.getComponent(); final Component itemComponent = currentMountItem.getComponent(); // 1. Check if the mount item generated from the old component should be updated. final boolean shouldUpdate = shouldUpdateMountItem( layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput, mIndexToItemMap, mLayoutOutputsIds, logger); // 2. Reset all the properties like click handler, content description and tags related to // this item if it needs to be updated. the update mount item will re-set the new ones. if (shouldUpdate) { unsetViewAttributes(currentMountItem); } // 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound. if (currentMountItem.isBound()) { itemComponent.getLifecycle().onUnbind( itemComponent.getScopedContext(), currentMountItem.getContent(), itemComponent); currentMountItem.setIsBound(false); } // 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput currentMountItem.init(layoutOutput.getComponent(), currentMountItem, layoutOutput); // 5. If the mount item is not valid for this component update its content and view attributes. if (shouldUpdate) { updateMountedContent(currentMountItem, layoutOutput, itemComponent); setViewAttributes(currentMountItem); } final Object currentContent = currentMountItem.getContent(); // 6. Set the mounted content on the Component and call the bind callback. layoutOutputComponent.getLifecycle().bind( layoutOutputComponent.getScopedContext(), currentContent, layoutOutputComponent); currentMountItem.setIsBound(true); // 7. Update the bounds of the mounted content. This needs to be done regardless of whether // the component has been updated or not since the mounted item might might have the same // size and content but a different position. updateBoundsForMountedLayoutOutput(layoutOutput, currentMountItem); maybeInvalidateAccessibilityState(currentMountItem); if (currentMountItem.getContent() instanceof Drawable) { maybeSetDrawableState( currentMountItem.getHost(), (Drawable) currentMountItem.getContent(), currentMountItem.getFlags(), currentMountItem.getNodeInfo()); } if (currentMountItem.getDisplayListDrawable() != null) { currentMountItem.getDisplayListDrawable().suppressInvalidations(false); } return shouldUpdate; } private static boolean shouldUpdateMountItem( LayoutOutput layoutOutput, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, LongSparseArray<MountItem> indexToItemMap, long[] layoutOutputsIds, ComponentsLogger logger) { final @LayoutOutput.UpdateState int updateState = layoutOutput.getUpdateState(); final Component currentComponent = currentMountItem.getComponent(); final ComponentLifecycle currentLifecycle = currentComponent.getLifecycle(); final Component nextComponent = layoutOutput.getComponent(); final ComponentLifecycle nextLifecycle = nextComponent.getLifecycle(); // If the two components have different sizes and the mounted content depends on the size we // just return true immediately. if (!sameSize(layoutOutput, currentMountItem) && nextLifecycle.isMountSizeDependent()) { return true; } if (useUpdateValueFromLayoutOutput) { if (updateState == LayoutOutput.STATE_UPDATED) { // Check for incompatible ReferenceLifecycle. if (currentLifecycle instanceof DrawableComponent && nextLifecycle instanceof DrawableComponent && currentLifecycle.shouldComponentUpdate(currentComponent, nextComponent)) { if (logger != null) { ComponentsLogger.LayoutOutputLog logObj = new ComponentsLogger.LayoutOutputLog(); logObj.currentId = indexToItemMap.keyAt( indexToItemMap.indexOfValue(currentMountItem)); logObj.currentLifecycle = currentLifecycle.toString(); logObj.nextId = layoutOutput.getId(); logObj.nextLifecycle = nextLifecycle.toString(); for (int i = 0; i < layoutOutputsIds.length; i++) { if (layoutOutputsIds[i] == logObj.currentId) { if (logObj.currentIndex == -1) { logObj.currentIndex = i; } logObj.currentLastDuplicatedIdIndex = i; } } if (logObj.nextId == logObj.currentId) { logObj.nextIndex = logObj.currentIndex; logObj.nextLastDuplicatedIdIndex = logObj.currentLastDuplicatedIdIndex; } else { for (int i = 0; i < layoutOutputsIds.length; i++) { if (layoutOutputsIds[i] == logObj.nextId) { if (logObj.nextIndex == -1) { logObj.nextIndex = i; } logObj.nextLastDuplicatedIdIndex = i; } } } logger.eventStart(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj); logger .eventEnd(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj, ACTION_SUCCESS); } return true; } return false; } else if (updateState == LayoutOutput.STATE_DIRTY) { return true; } } if (!currentLifecycle.callsShouldUpdateOnMount()) { return true; } return currentLifecycle.shouldComponentUpdate( currentComponent, nextComponent); } private static boolean sameSize(LayoutOutput layoutOutput, MountItem item) { final Rect layoutOutputBounds = layoutOutput.getBounds(); final Object mountedContent = item.getContent(); return layoutOutputBounds.width() == getWidthForMountedContent(mountedContent) && layoutOutputBounds.height() == getHeightForMountedContent(mountedContent); } private static int getWidthForMountedContent(Object content) { return content instanceof Drawable ? ((Drawable) content).getBounds().width() : ((View) content).getWidth(); } private static int getHeightForMountedContent(Object content) { return content instanceof Drawable ? ((Drawable) content).getBounds().height() : ((View) content).getHeight(); } private void updateBoundsForMountedLayoutOutput(LayoutOutput layoutOutput, MountItem item) { // MountState should never update the bounds of the top-level host as this // should be done by the ViewGroup containing the ComponentView. if (layoutOutput.getId() == ROOT_HOST_ID) { return; } layoutOutput.getMountBounds(sTempRect); final boolean forceTraversal = Component.isMountViewSpec(layoutOutput.getComponent()) && ((View) item.getContent()).isLayoutRequested(); applyBoundsToMountContent( item.getContent(), sTempRect.left, sTempRect.top, sTempRect.right, sTempRect.bottom, forceTraversal /* force */); } /** * Prepare the {@link MountState} to mount a new {@link LayoutState}. */ @SuppressWarnings("unchecked") private void prepareMount(LayoutState layoutState) { final ComponentTree component = mComponentView.getComponent(); final ComponentsLogger logger = component.getContext().getLogger(); final String logTag = component.getContext().getLogTag(); if (logger != null) { logger.eventStart(EVENT_PREPARE_MOUNT, component); } PrepareMountStats stats = unmountOrMoveOldItems(layoutState); if (logger != null) { logPrepareMountParams(logger, logTag, component, stats); } if (mHostsByMarker.get(ROOT_HOST_ID) == null) { // Mounting always starts with the root host. registerHost(ROOT_HOST_ID, mComponentView); // Root host is implicitly marked as mounted. mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem); } int outputCount = layoutState.getMountableOutputCount(); if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) { mLayoutOutputsIds = new long[layoutState.getMountableOutputCount()]; } for (int i = 0; i < outputCount; i++) { mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getId(); } if (logger != null) { logger.eventEnd(EVENT_PREPARE_MOUNT, component, ACTION_SUCCESS); } } /** * Determine whether to apply disappear animation to the given {@link MountItem} */ private static boolean isItemDisappearing( MountItem mountItem, TransitionContext transitionContext) { if (mountItem == null || mountItem.getViewNodeInfo() == null || transitionContext == null) { return false; } return transitionContext.isDisappearingKey(mountItem.getViewNodeInfo().getTransitionKey()); } /** * Go over all the mounted items from the leaves to the root and unmount only the items that are * not present in the new LayoutOutputs. * If an item is still present but in a new position move the item inside its host. * The condition where an item changed host doesn't need any special treatment here since we * mark them as removed and re-added when calculating the new LayoutOutputs */ private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) { mPrepareMountStats.reset(); if (mLayoutOutputsIds == null) { return mPrepareMountStats; } // Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there // but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively // all its mounted children. for (int i = 0; i < mLayoutOutputsIds.length; i++) { final int newPosition = newLayoutState.getLayoutOutputPositionForId(mLayoutOutputsIds[i]); final MountItem oldItem = getItemAt(i); if (isItemDisappearing(oldItem, newLayoutState.getTransitionContext())) { startUnmountDisappearingItem(i, oldItem.getViewNodeInfo().getTransitionKey()); final int lastDescendantOfItem = findLastDescendantOfItem(i, oldItem); // Disassociate disappearing items from current mounted items. The layout tree will not // contain disappearing items anymore, however they are kept separately in their hosts. removeDisappearingItemMappings(i, lastDescendantOfItem); // Skip this disappearing item and all its descendants. Do not unmount or move them yet. // We will unmount them after animation is completed. i = lastDescendantOfItem; continue; } if (newPosition == -1) { unmountItem(mContext, i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else { final long newHostMarker = newLayoutState.getMountableOutputAt(newPosition).getHostMarker(); if (oldItem == null) { // This was previously unmounted. mPrepareMountStats.unmountedCount++; } else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) { // If the id is the same but the parent host is different we simply unmount the item and // re-mount it later. If the item to unmount is a ComponentHost, all the children will be // recursively unmounted. unmountItem(mContext, i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else if (newPosition != i) { // If a MountItem for this id exists and the hostMarker has not changed but its position // in the outputs array has changed we need to update the position in the Host to ensure // the z-ordering. oldItem.getHost().moveItem(oldItem, i, newPosition); mPrepareMountStats.movedCount++; } else { mPrepareMountStats.unchangedCount++; } } } return mPrepareMountStats; } private void removeDisappearingItemMappings(int fromIndex, int toIndex) { for (int i = fromIndex; i <= toIndex; i++) { final MountItem item = getItemAt(i); // We do not need this mapping for disappearing items. mIndexToItemMap.remove(mLayoutOutputsIds[i]); // Likewise we no longer need host mapping for disappearing items. if (isHostSpec(item.getComponent())) { mHostsByMarker .removeAt(mHostsByMarker.indexOfValue((ComponentHost) item.getContent())); } } } /** * Find the index of last descendant of given {@link MountItem} */ private int findLastDescendantOfItem(int disappearingItemIndex, MountItem item) { for (int i = disappearingItemIndex + 1; i < mLayoutOutputsIds.length; i++) { if (!ComponentHostUtils.hasAncestorHost( getItemAt(i).getHost(), (ComponentHost) item.getContent())) { // No need to go further as the items that have common ancestor hosts are co-located. // This is the first non-descendant of given MountItem, therefore last descendant is the // item before. return i - 1; } } return mLayoutOutputsIds.length - 1; } private void updateMountedContent( MountItem item, LayoutOutput layoutOutput, Component previousComponent) { final Component<?> component = layoutOutput.getComponent(); if (isHostSpec(component)) { return; } final Object previousContent = item.getContent(); final ComponentLifecycle lifecycle = component.getLifecycle(); // Call unmount and mount in sequence to make sure all the the resources are correctly // de-allocated. It's possible for previousContent to equal null - when the root is // interactive we create a LayoutOutput without content in order to set up click handling. lifecycle.unmount(previousComponent.getScopedContext(), previousContent, previousComponent); lifecycle.mount(component.getScopedContext(), previousContent, component); } private void mountLayoutOutput(int index, LayoutOutput layoutOutput, LayoutState layoutState) { // 1. Resolve the correct host to mount our content to. ComponentHost host = resolveComponentHost(layoutOutput, mHostsByMarker); if (host == null) { // Host has not yet been mounted - mount it now. for (int hostMountIndex = 0, size = mLayoutOutputsIds.length; hostMountIndex < size; hostMountIndex++) { if (mLayoutOutputsIds[hostMountIndex] == layoutOutput.getHostMarker()) { final LayoutOutput hostLayoutOutput = layoutState.getMountableOutputAt(hostMountIndex); mountLayoutOutput(hostMountIndex, hostLayoutOutput, layoutState); break; } } host = resolveComponentHost(layoutOutput, mHostsByMarker); } final Component<?> component = layoutOutput.getComponent(); final ComponentLifecycle lifecycle = component.getLifecycle(); // 2. Generate the component's mount state (this might also be a ComponentHost View). Object content = acquireMountContent(component, host); if (content == null) { content = lifecycle.createMountContent(mContext); } lifecycle.mount( component.getScopedContext(), content, component); // 3. If it's a ComponentHost, add the mounted View to the list of Hosts. if (isHostSpec(component)) { ComponentHost componentHost = (ComponentHost) content; componentHost.setParentHostMarker(layoutOutput.getHostMarker()); registerHost(layoutOutput.getId(), componentHost); } // 4. Mount the content into the selected host. final MountItem item = mountContent(index, component, content, host, layoutOutput); // 5. Notify the component that mounting has completed lifecycle.bind(component.getScopedContext(), content, component); item.setIsBound(true); // 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling // bind might have triggered a layout request within a View. layoutOutput.getMountBounds(sTempRect); applyBoundsToMountContent( content, sTempRect.left, sTempRect.top, sTempRect.right, sTempRect.bottom, true /* force */); if (item.getDisplayListDrawable() != null) { item.getDisplayListDrawable().suppressInvalidations(false); } // 6. Update the mount stats mMountStats.mountedCount++; } // The content might be null because it's the LayoutSpec for the root host // (the very first LayoutOutput). private MountItem mountContent( int index, Component<?> component, Object content, ComponentHost host, LayoutOutput layoutOutput) { final MountItem item = ComponentsPools.acquireMountItem( component, host, content, layoutOutput); // Create and keep a MountItem even for the layoutSpec with null content // that sets the root host interactions. mIndexToItemMap.put(mLayoutOutputsIds[index], item); if (component.getLifecycle().canMountIncrementally()) { mCanMountIncrementallyMountItems.put(index, item); } layoutOutput.getMountBounds(sTempRect); host.mount(index, item, sTempRect); setViewAttributes(item); return item; } private Object acquireMountContent(Component<?> component, ComponentHost host) { final ComponentLifecycle lifecycle = component.getLifecycle(); if (isHostSpec(component)) { return host.recycleHost(); } return ComponentsPools.acquireMountContent(mContext, lifecycle.getId()); } private static void applyBoundsToMountContent( Object content, int left, int top, int right, int bottom, boolean force) { assertMainThread(); if (content instanceof View) { View view = (View) content; int width = right - left; int height = bottom - top; if (force || view.getMeasuredHeight() != height || view.getMeasuredWidth() != width) { view.measure( makeMeasureSpec(right - left, MeasureSpec.EXACTLY), makeMeasureSpec(bottom - top, MeasureSpec.EXACTLY)); } if (force || view.getLeft() != left || view.getTop() != top || view.getRight() != right || view.getBottom() != bottom) { view.layout(left, top, right, bottom); } } else if (content instanceof Drawable) { ((Drawable) content).setBounds(left, top, right, bottom); } else { throw new IllegalStateException("Unsupported mounted content " + content); } } private static boolean canMountIncrementally(Component<?> component) { return component.getLifecycle().canMountIncrementally(); } /** * Resolves the component host that will be used for the given layout output * being mounted. */ private static ComponentHost resolveComponentHost( LayoutOutput layoutOutput, LongSparseArray<ComponentHost> hostsByMarker) { final long hostMarker = layoutOutput.getHostMarker(); return hostsByMarker.get(hostMarker); } private static void setViewAttributes(MountItem item) { final Component<?> component = item.getComponent(); if (!isMountViewSpec(component)) { return; } final View view = (View) item.getContent(); final NodeInfo nodeInfo = item.getNodeInfo(); if (nodeInfo != null) { // 1. Setup click handler for the component, if applicable. setClickHandler(nodeInfo.getClickHandler(), view); // 2. Setup long click handler for the component, if applicable. setLongClickHandler(nodeInfo.getLongClickHandler(), view); // 3. Setup click handler for the component, if applicable. setTouchHandler(nodeInfo.getTouchHandler(), view); // 4. Set listeners for AccessibilityDelegate methods setAccessibilityDelegate(view, nodeInfo); // 5. Setup view tags for the component, if applicable. setViewTag(view, nodeInfo.getViewTag()); setViewTags(view, nodeInfo.getViewTags()); // 6. Set content description. setContentDescription(view, nodeInfo.getContentDescription()); // 7. Set setFocusable flag. setFocusable(view, nodeInfo.getFocusState()); } // 8. Set important for accessibility flag setImportantForAccessibility(view, item.getImportantForAccessibility()); final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo(); if (viewNodeInfo != null && !isHostSpec(component)) { // 9. Set view background, if applicable. Do this before padding // as it otherwise overrides the padding. setViewBackground(view, viewNodeInfo);
package com.faforever.client.i18n; import com.faforever.client.preferences.PreferencesService; import com.google.common.base.Strings; import javafx.beans.property.ReadOnlyListWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; @Service public class I18nImpl implements I18n { private static final Pattern MESSAGES_FILE_PATTERN = Pattern.compile("(.*[/\\\\]messages)(?:_([a-z]{2}))(?:_([a-z]{2}))?\\.properties", Pattern.CASE_INSENSITIVE); private final ReloadableResourceBundleMessageSource messageSource; private final PreferencesService preferencesService; private final ObservableList<Locale> availableLanguages; private Locale userSpecificLocale; @Inject public I18nImpl(ReloadableResourceBundleMessageSource messageSource, PreferencesService preferencesService) { this.messageSource = messageSource; this.preferencesService = preferencesService; availableLanguages = FXCollections.observableArrayList(); } @PostConstruct public void postConstruct() throws IOException { Locale locale = preferencesService.getPreferences().getLocalization().getLanguage(); if (locale != null) { userSpecificLocale = new Locale(locale.getLanguage(), locale.getCountry()); } else { userSpecificLocale = Locale.getDefault(); } loadAvailableLanguages(); } private void loadAvailableLanguages() throws IOException { // These are the default languages shipped with the client availableLanguages.addAll( Locale.US, new Locale("cs"), Locale.GERMAN, Locale.FRENCH, new Locale("ru"), Locale.CHINESE ); Path languagesDirectory = preferencesService.getLanguagesDirectory(); if (Files.notExists(languagesDirectory)) { return; } try (Stream<Path> dir = Files.list(languagesDirectory)) { dir .map(path -> MESSAGES_FILE_PATTERN.matcher(path.toString())) .filter(Matcher::matches) .forEach(matcher -> { messageSource.addBasenames(Paths.get(matcher.group(1)).toUri().toString()); availableLanguages.add(new Locale(matcher.group(2), Strings.nullToEmpty(matcher.group(3)))); }); } } @Override public String get(String key, Object... args) { return get(userSpecificLocale, key, args); } @Override public String get(Locale locale, String key, Object... args) { return messageSource.getMessage(key, args, locale); } @Override public Locale getUserSpecificLocale() { return this.userSpecificLocale; } @Override public String getQuantized(String singularKey, String pluralKey, long arg) { Object[] args = {arg}; if (Math.abs(arg) == 1) { return messageSource.getMessage(singularKey, args, userSpecificLocale); } return messageSource.getMessage(pluralKey, args, userSpecificLocale); } @Override public String number(int number) { return String.format(userSpecificLocale, "%d", number); } @Override public String numberWithSign(int number) { return String.format(userSpecificLocale, "%+d", number); } @Override public String number(double number) { return String.format(userSpecificLocale, "%f", number); } @Override public String rounded(double number, int digits) { return String.format(userSpecificLocale, "%." + digits + "f", number); } @Override public ReadOnlyListWrapper<Locale> getAvailableLanguages() { return new ReadOnlyListWrapper<>(availableLanguages); } }
package com.thoughtworks.acceptance; import com.bea.xml.stream.MXParserFactory; import com.bea.xml.stream.XMLOutputFactoryBase; import com.thoughtworks.acceptance.someobjects.Handler; import com.thoughtworks.acceptance.someobjects.Protocol; import com.thoughtworks.acceptance.someobjects.WithList; import com.thoughtworks.acceptance.someobjects.X; import com.thoughtworks.acceptance.someobjects.Y; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.xml.BEAStaxDriver; import com.thoughtworks.xstream.io.xml.QNameMap; import com.thoughtworks.xstream.io.xml.StaxDriver; import com.thoughtworks.xstream.io.xml.WstxDriver; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import java.util.ArrayList; public class QNameMappedConcreteClassesTest extends AbstractAcceptanceTest { public static final String XML_HEADER = "<?xml version='1.0' encoding='utf-8'?>"; protected QNameMap qnameMap; protected String namespace = getDefaultNS(WithList.class); public void testUsingNamespace() { // lets register some qnames QName qname = new QName(namespace, "withList", "w"); qnameMap.registerMapping(qname, WithList.class); WithList withList = new WithList(); withList.things = new ArrayList(); String expected ="" + XML_HEADER + "<w:withList xmlns:w=\"java://com.thoughtworks.acceptance.someobjects\">" + "<things></things>" + "</w:withList>"; assertBothWays(withList, expected); } public void testUsingDefaultNamespace() { qnameMap.setDefaultNamespace(namespace); xstream.alias("withList", WithList.class); WithList withList = new WithList(); withList.things = new ArrayList(); String expected = XML_HEADER + "<withList xmlns=\"java://com.thoughtworks.acceptance.someobjects\">" + "<things></things>" + "</withList>"; assertBothWays(withList, expected); } public void testUsingDefaultNamespaceAndPrefix() { qnameMap.setDefaultNamespace(namespace); qnameMap.setDefaultPrefix("x"); QName qname = new QName(namespace, "withList", "x"); qnameMap.registerMapping(qname, WithList.class); WithList withList = new WithList(); withList.things = new ArrayList(); String expected = XML_HEADER + "<x:withList xmlns:x=\"java://com.thoughtworks.acceptance.someobjects\">" + "<x:things></x:things>" + "</x:withList>"; assertBothWays(withList, expected); } public void testUsingDifferentNamespaces() { // lets register some qnames qnameMap.registerMapping(new QName(namespace, "withList", "w"), WithList.class); qnameMap.registerMapping(new QName("urn:foo", "things", "f"), "things"); WithList withList = new WithList(); withList.things = new ArrayList(); String expected = XML_HEADER + "<w:withList xmlns:w=\"java://com.thoughtworks.acceptance.someobjects\">" + "<f:things xmlns:f=\"urn:foo\"></f:things>" + "</w:withList>"; assertBothWays(withList, expected); } public void testUsingDifferentNamespacesWithAliases() { xstream.alias("handler", X.class); xstream.alias("protocol", Y.class); qnameMap.registerMapping(new QName(getDefaultNS(Handler.class)+1, "handler", "h"), "handler"); qnameMap.registerMapping(new QName(getDefaultNS(Protocol.class)+2, "protocol", "p"), "innerObj"); X x = new X(); x.aStr = "foo"; x.anInt = 42; x.innerObj = new Y(); x.innerObj.yField = "YField"; String expected = XML_HEADER + "<h:handler xmlns:h=\"java://com.thoughtworks.acceptance.someobjects1\">" + "<aStr>foo</aStr>" + "<anInt>42</anInt>" + "<p:protocol xmlns:p=\"java://com.thoughtworks.acceptance.someobjects2\">" + "<yField>YField</yField>" + "</p:protocol>" + "</h:handler>"; assertBothWays(x, expected); } protected HierarchicalStreamDriver createDriver() { // careful, called from inside base class constructor qnameMap = new QNameMap(); StaxDriver driver = new BEAStaxDriver(qnameMap); driver.setRepairingNamespace(false); return driver; } protected String getDefaultNS(Class type) { return "java://" + type.getPackage().getName(); } }
package StevenDimDoors.mod_pocketDim.core; import java.util.LinkedList; import java.util.List; import StevenDimDoors.mod_pocketDim.util.Point4D; public abstract class DimLink { protected Point4D source; protected DimLink parent; protected LinkTail tail; protected int orientation; protected List<DimLink> children; protected DimLink(Point4D source, DimLink parent, int orientation) { if (parent.source.getDimension() != source.getDimension()) { // Ban having children in other dimensions to avoid serialization issues with cross-dimensional tails throw new IllegalArgumentException("source and parent.source must have the same dimension."); } this.parent = parent; this.source = source; this.tail = parent.tail; this.children = new LinkedList<DimLink>(); parent.children.add(this); } protected DimLink(Point4D source, int linkType, int orientation) { if (linkType < LinkTypes.ENUM_MIN || linkType > LinkTypes.ENUM_MAX && linkType != LinkTypes.CLIENT_SIDE) { throw new IllegalArgumentException("The specified link type is invalid."); } this.orientation = orientation; this.parent = null; this.source = source; this.tail = new LinkTail(linkType, null); this.children = new LinkedList<DimLink>(); } public Point4D source() { return source; } public Point4D destination() { return tail.getDestination(); } public int getDestinationOrientation() { return PocketManager.getLink(source.getX(), source.getY(), source.getZ(), source.getDimension()).orientation(); } public boolean hasDestination() { return (tail.getDestination() != null); } public Iterable<DimLink> children() { return children; } public int childCount() { return children.size(); } public DimLink parent() { return parent; } public int linkType() { return tail.getLinkType(); } public int orientation() { return orientation; } public String toString() { return source + " -> " + (hasDestination() ? destination() : ""); } }
package com.flowpowered.commons; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; public class StringUtil { /** * Tests if this string starts with the specified prefix, ignoring case * * @param input the input * @param prefix the prefix * @return True if the input starts with the prefix when ignoring case, False if not */ public static boolean startsWithIgnoreCase(String input, String prefix) { if (input == null || prefix == null || prefix.length() > input.length()) { return false; } else { final char[] inputCharArray = input.toCharArray(); final char[] prefixCharArray = input.toCharArray(); for (int i = 0; i < prefixCharArray.length; i++) { if (!equalsIgnoreCase(prefixCharArray[i], inputCharArray[i])) { return false; } } return true; } } /** * Gets whether two characters equal each other, while ignoring case. * * @param input1 to use * @param input2 to use * @return True if input1 and input2 equal when ignoring case, False if not */ public static boolean equalsIgnoreCase(char input1, char input2) { return Character.toLowerCase(input1) == Character.toLowerCase(input2); } /** * Matches a value using a name and the value .toString() method * * @param values to look into * @param name to match against * @return a collection of values that matched */ public static <T> Collection<T> matchToString(Collection<T> values, String name) { List<T> result = new ArrayList<>(); for (T value : values) { if (value == null) { continue; } if (startsWithIgnoreCase(value.toString(), name)) { result.add(value); } } return result; } /** * Matches a named class using a name * * @param values to look into * @param name to match against * @return a collection of values that matched */ public static <T extends Named> Collection<T> matchName(Collection<T> values, String name) { List<T> result = new ArrayList<>(); for (T value : values) { if (value == null) { continue; } if (startsWithIgnoreCase(value.getName(), name)) { result.add(value); } } return result; } /** * Gets the named object with the shortest name from the values specified * * @param values to look into * @return the shortest value, or null if there are no values */ public static <T extends Named> T getShortest(Collection<T> values) { int shortestMatch = Integer.MAX_VALUE; T shortest = null; for (T value : values) { if (value.getName().length() < shortestMatch) { shortestMatch = value.getName().length(); shortest = value; } } return shortest; } /** * Wraps all components in between brackets delimited by ','-signs * * @param components to turn into a String * @return a String representation of the input */ public static String toString(Object... components) { return toNamedString(null, components); } /** * Converts a String expression of elements into an integer array<br> For example: "12-34, 35, 36, 11-0" * * @param elements to convert * @return the converted result */ public static Integer[] getIntArray(String elements) { if (elements == null || elements.isEmpty()) { return new Integer[0]; } List<Integer> values = new ArrayList<>(); int index; int start, end; for (String element : elements.split(",")) { element = element.trim(); index = element.indexOf('-'); try { if (index != -1) { start = Integer.parseInt(element.substring(0, index).trim()); end = Integer.parseInt(element.substring(index + 1).trim()); if (end == start) { values.add(start); } else if (end > start) { for (index = start; index <= end; index++) { values.add(index); } } else { for (index = start; index >= end; index values.add(index); } } } else { values.add(Integer.parseInt(element)); } } catch (NumberFormatException ex) { ex.printStackTrace(); } } return values.toArray(new Integer[0]); } /** * Wraps all components in between brackets delimited by ','-signs, appending the class name in front of it. * * @param object name to append in front * @param components to turn into a String * @return a String representation of the input */ public static String toNamedString(Object object, Object... components) { StringBuilder b = new StringBuilder(components.length * 5 + 2); if (object != null) { b.append(object.getClass().getSimpleName()).append(' '); } b.append('{'); for (int i = 0; i < components.length; i++) { if (i != 0) { b.append(", "); } b.append(components[i]); } b.append('}'); return b.toString(); } public static int getLevenshteinDistance(String s, String t) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } /* The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length()+1 by t.length()+1, we maintain two single-dimensional arrays of length s.length()+1. The first, d, is the 'current working' distance array that maintains the newest distance cost counts as we iterate through the characters of String s. Each time we increment the index of String t we are comparing, d is copied to p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.) Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two very large strings. */ int n = s.length(); // length of s int m = t.length(); // length of t if (n == 0) { return m; } else if (m == 0) { return n; } int p[] = new int[n + 1]; //'previous' cost array, horizontally int d[] = new int[n + 1]; // cost array, horizontally int _d[]; //placeholder to assist in swapping p and d // indexes into strings s and t int i; // iterates through s int j; // iterates through t char t_j; // jth character of t int cost; // cost for (i = 0; i <= n; i++) { p[i] = i; } for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); d[0] = j; for (i = 1; i <= n; i++) { cost = s.charAt(i - 1) == t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[n]; } private static Pattern escapeRegexPattern = Pattern.compile("[^a-zA-Z0-9]"); public static String escapeRegex(String str) { return escapeRegexPattern.matcher(str).replaceAll("\\\\$0"); } }
package com.github.andone.launcher; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Pattern { private final int x; private final int y; public static List<Pattern> getPatterns() { return Arrays.asList( new Pattern(4, 0), new Pattern(0, 4), new Pattern(0, 3), new Pattern(3, 0), new Pattern(1, 1), new Pattern(0, 2), new Pattern(2, 0), new Pattern(1, 0), new Pattern(0, 1) ); } public static List<List<Cell>> getValidRegions(int x, int y, Pizza pizza) { List<List<Cell>> regions = new ArrayList<>(); for (Pattern pattern : getPatterns()) { int dx = pattern.x; int dy = pattern.y; for (int i = -1; i <= 1; i += 2) { for (int j = -1; j <= 1; j += 2) { int x2 = x + dx * i; int y2 = y + dy * j; if (isValidRegion(x + x2, y + y2, pizza)) { regions.add(cellsInRegion(x, y, x2, y2, pizza)); } } } } return regions; } private static boolean isValidRegion(int x, int y, Pizza pizza) { return x < pizza.getRows() && y < pizza.getCols() && x >= 0 && y >= 0; } private static List<Cell> cellsInRegion(int x0, int y0, int dx, int dy, Pizza pizza) { List<Cell> region = new ArrayList<>(); for (int i = x0; i <= dx; i++) { for (int j = y0; j <= dy; j++) { region.add(pizza.get(i, j)); } } return region; } public Pattern(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } }
package com.github.davidmoten.rx.jdbc; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.apache.commons.io.IOUtils; import rx.Observable; import rx.util.functions.Func1; import rx.util.functions.Functions; public final class Util { private static final Logger log = Logger.getLogger(Util.class); public static int parametersPerSetCount(String sql) { // TODO account for ? characters in string constants return countOccurrences(sql, '?'); } private static int countOccurrences(String haystack, char needle) { int count = 0; for (int i = 0; i < haystack.length(); i++) { if (haystack.charAt(i) == needle) count++; } return count; } public static <T> Observable<? extends T> flatten( Observable<Observable<T>> o) { return o.flatMap(Functions.<Observable<T>> identity()); } public static void closeQuietly(PreparedStatement ps) { try { if (ps != null && !ps.isClosed()) { try { ps.cancel(); log.debug("cancelled " + ps); } catch (SQLException e) { log.debug(e.getMessage()); } ps.close(); log.debug("closed " + ps); } } catch (SQLException e) { e.printStackTrace(); } } // public <T,R> Observable<Observable<R>> onFinishedAll(final Observable<T> // ob, Func1<T,Observable<R>> f, Action0 action){ public static void closeQuietly(Connection connection) { try { if (connection != null && !connection.isClosed()) { connection.close(); log.debug("closed " + connection); } } catch (SQLException e) { log.debug(e.getMessage()); } } public static void closeQuietlyIfAutoCommit(Connection connection) { try { if (connection != null && !connection.isClosed() && connection.getAutoCommit()) closeQuietly(connection); } catch (SQLException e) { throw new RuntimeException(e); } } public static void commit(Connection connection) { if (connection != null) try { connection.commit(); log.debug("committed"); } catch (SQLException e) { throw new RuntimeException(e); } } public static void rollback(Connection connection) { if (connection != null) try { connection.rollback(); log.debug("rolled back"); } catch (SQLException e) { throw new RuntimeException(e); } } public static void closeQuietly(ResultSet rs) { try { if (rs != null && !rs.isClosed()) { rs.close(); log.debug("closed " + rs); } } catch (SQLException e) { log.debug(e.getMessage()); } } public static boolean isAutoCommit(Connection con) { try { return con.getAutoCommit(); } catch (SQLException e) { throw new RuntimeException(e); } } public static Func1<Integer, List<Object>> TO_EMPTY_LIST = new Func1<Integer, List<Object>>() { @Override public List<Object> call(Integer t1) { return Collections.emptyList(); }; }; public static <R, S> Func1<R, S> constant(final S s) { return new Func1<R, S>() { @Override public S call(R t1) { return s; } }; } public static <T> Func1<T, T> delay(final int delayMs) { return new Func1<T, T>() { @Override public T call(T t) { try { Thread.sleep(delayMs); } catch (InterruptedException e) { // ignore } return t; } }; } public static <T> Func1<ResultSet, T> autoMap(final Class<T> cls) { return new Func1<ResultSet, T>() { @Override public T call(ResultSet rs) { return autoMap(rs, cls); } }; } public static <T> T autoMap(ResultSet rs, Class<T> cls) { try { int n = rs.getMetaData().getColumnCount(); for (Constructor<?> c : cls.getDeclaredConstructors()) { if (n == c.getParameterTypes().length) { return autoMap(rs, cls, c); } } throw new RuntimeException("constructor with number of parameters=" + n + " not found in " + cls); } catch (SQLException e) { throw new RuntimeException(e); } } private static <T> T autoMap(ResultSet rs, Class<T> cls, Constructor<?> c) { Class<?>[] types = c.getParameterTypes(); List<Object> list = new ArrayList<Object>(); for (int i = 0; i < types.length; i++) { list.add(autoMap(getObject(rs, types[i], i + 1), types[i])); } return newInstance(c, list); } @SuppressWarnings("unchecked") private static <T> T newInstance(Constructor<?> c, List<Object> list) { try { return (T) c.newInstance(list.toArray()); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } public static Object autoMap(Object o, Class<?> cls) { if (o == null) return o; else if (cls.isAssignableFrom(o.getClass())) { return o; } else { if (o instanceof java.sql.Date) { java.sql.Date d = (java.sql.Date) o; if (cls.isAssignableFrom(Date.class)) return new Date(d.getTime()); else if (cls.isAssignableFrom(Long.class)) return d.getTime(); else return o; } else if (o instanceof java.sql.Timestamp) { Timestamp t = (java.sql.Timestamp) o; if (cls.isAssignableFrom(Date.class)) return new Date(t.getTime()); else if (cls.isAssignableFrom(Long.class)) return t.getTime(); else return o; } else if (o instanceof java.sql.Time) { Time t = (java.sql.Time) o; if (cls.isAssignableFrom(Date.class)) return new Date(t.getTime()); else if (cls.isAssignableFrom(Long.class)) return t.getTime(); else return o; } else if (o instanceof Blob) { // TODO return o; } else if (o instanceof Clob) { // TODO return o; } else return o; } } public static <T> Object getObject(final ResultSet rs, Class<T> cls, int i) { try { final int type = rs.getMetaData().getColumnType(i); // TODO java.util.Calendar support // TODO XMLGregorian Calendar support if (type == Types.DATE) return rs.getDate(i, Calendar.getInstance(UTC)); else if (type == Types.TIME) return rs.getTime(i, Calendar.getInstance(UTC)); else if (type == Types.TIMESTAMP) return rs.getTimestamp(i, Calendar.getInstance(UTC)); else if (type == Types.CLOB && cls.equals(String.class)) { Clob c = rs.getClob(i); Reader reader = c.getCharacterStream(); String result = IOUtils.toString(reader); reader.close(); c.free(); return result; } else if (type == Types.CLOB && Reader.class.isAssignableFrom(cls)) { Clob c = rs.getClob(i); Reader r = c.getCharacterStream(); return createFreeOnCloseReader(c, r); } else if (type == Types.BLOB && cls.equals(byte[].class)) { Blob b = rs.getBlob(i); InputStream is = b.getBinaryStream(); byte[] result = IOUtils.toByteArray(is); is.close(); b.free(); return result; } else if (type == Types.BLOB && InputStream.class.isAssignableFrom(cls)) { final Blob b = rs.getBlob(i); final InputStream is = rs.getBlob(i).getBinaryStream(); return createFreeOnCloseInputStream(b, is); } else return rs.getObject(i); } catch (SQLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } private static InputStream createFreeOnCloseInputStream(final Blob b, final InputStream is) { return new InputStream() { @Override public int read() throws IOException { return is.read(); } @Override public void close() throws IOException { try { is.close(); } finally { try { b.free(); } catch (SQLException e) { log.debug(e.getMessage()); } } } }; } private static Reader createFreeOnCloseReader(final Clob b, final Reader r) { return new Reader() { @Override public void close() throws IOException { try { r.close(); } finally { try { b.free(); } catch (SQLException e) { log.debug(e.getMessage()); } } } @Override public int read(char[] cbuf, int off, int len) throws IOException { return r.read(cbuf, off, len); } }; } private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); public static void setParameters(PreparedStatement ps, List<Object> params) throws SQLException { for (int i = 1; i <= params.size(); i++) { Object o = params.get(i - 1); if (o == null) ps.setObject(i, o); else { Class<?> cls = o.getClass(); if (Clob.class.isAssignableFrom(cls)) { setClob(ps, i, o, cls); } else if (Blob.class.isAssignableFrom(cls)) { setBlob(ps, i, o, cls); } else if (Time.class.isAssignableFrom(cls)) { Calendar cal = Calendar.getInstance(UTC); ps.setTime(i, (Time) o, cal); } else if (Timestamp.class.isAssignableFrom(cls)) { Calendar cal = Calendar.getInstance(UTC); ps.setTimestamp(i, (Timestamp) o, cal); } else if (java.sql.Date.class.isAssignableFrom(cls)) { Calendar cal = Calendar.getInstance(UTC); ps.setDate(i, (java.sql.Date) o, cal); } else ps.setObject(i, o); } } } private static void setBlob(PreparedStatement ps, int i, Object o, Class<?> cls) throws SQLException { final InputStream is; if (o instanceof byte[]) { is = new ByteArrayInputStream((byte[]) o); } else if (o instanceof InputStream) is = (InputStream) o; else throw new RuntimeException("cannot insert parameter of type " + cls + " into blob column " + i); Blob c = ps.getConnection().createBlob(); OutputStream os = c.setBinaryStream(1); copy(is, os); ps.setBlob(i, c); } private static void setClob(PreparedStatement ps, int i, Object o, Class<?> cls) throws SQLException { final Reader r; if (o instanceof String) r = new StringReader((String) o); else if (o instanceof Reader) r = (Reader) o; else throw new RuntimeException("cannot insert parameter of type " + cls + " into clob column " + i); Clob c = ps.getConnection().createClob(); Writer w = c.setCharacterStream(1); copy(r, w); ps.setClob(i, c); } private static int copy(Reader input, Writer output) { try { return IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } } private static int copy(InputStream input, OutputStream output) { try { return IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } } public static final Func1<Reader, String> READER_TO_STRING = new Func1<Reader, String>() { @Override public String call(Reader r) { try { return IOUtils.toString(r); } catch (IOException e) { throw new RuntimeException(e); } } }; }
package org.endeavourhealth.dataassurance.logic; import org.apache.commons.lang3.StringUtils; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI; import org.endeavourhealth.dataassurance.dal.PersonPatientDAL; import org.endeavourhealth.dataassurance.dal.PersonPatientDAL_Jdbc; import org.endeavourhealth.dataassurance.helpers.SearchTermsParser; import org.endeavourhealth.dataassurance.models.Patient; import org.endeavourhealth.dataassurance.models.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class PersonPatientLogic { private static final Logger LOG = LoggerFactory.getLogger(PersonPatientLogic.class); static PersonPatientDAL dal; public PersonPatientLogic() { if (dal == null) dal = new PersonPatientDAL_Jdbc(); } public List<Person> findPersonsInOrganisations(Set<String> organisationIds, String searchTerms) throws Exception { List<Person> result = new ArrayList<>(); if (organisationIds == null || organisationIds.size() == 0) { LOG.error("No access to any organisations"); return result; } if (!StringUtils.isEmpty(searchTerms)) { SearchTermsParser parser = new SearchTermsParser(searchTerms); if (parser.hasNhsNumber()) { LOG.debug("Searching NHS Number"); List<Person> matches = dal.searchByNhsNumber(organisationIds, parser.getNhsNumber()); if (matches != null && matches.size() > 0) result.addAll(matches); } if (parser.hasEmisNumber()) { LOG.debug("Searching Local Id"); List<Person> matches = dal.searchByLocalId(organisationIds, parser.getEmisNumber()); if (matches != null && matches.size() > 0) result.addAll(matches); } if (parser.hasDateOfBirth()) { LOG.debug("Searching DOB"); List<Person> matches = dal.searchByDateOfBirth(organisationIds, parser.getDateOfBirth()); if (matches != null && matches.size() > 0) result.addAll(matches); } if (parser.hasNames()) { LOG.debug("Searching names"); List<Person> matches = dal.searchByNames(organisationIds, parser.getNames()); if (matches != null && matches.size() > 0) result.addAll(matches); } } for (Person person : result) { if (person.getName() == null || person.getName().isEmpty()) person.setName("Unknown"); } return result; } public List<Patient> getPatientsForPerson(Set<String> serviceIds, String personId) throws Exception { return dal.getPatientsByNhsNumber(serviceIds, personId); } public Patient getPatient(Set<String> serviceIds, String serviceId, String systemId, String patientId) { if (!serviceIds.contains(serviceId)) return null; return dal.getPatient(serviceId, systemId, patientId); } }
package com.jsh.dao.materials; import org.hibernate.Query; import com.jsh.base.BaseDAO; import com.jsh.util.JshException; import com.jsh.model.po.DepotHead; import com.jsh.model.po.DepotItem; import com.jsh.util.PageUtil; import com.jsh.util.SearchConditionUtil; public class DepotItemDAO extends BaseDAO<DepotItem> implements DepotItemIDAO { /** * dao * @return */ @Override public Class<DepotItem> getEntityClass() { return DepotItem.class; } @SuppressWarnings("unchecked") @Override public void findByType(PageUtil<DepotItem> pageUtil,String type,Integer ProjectId,Long MId,String MonthTime,Boolean isPrev) throws JshException { //,createSQLQuerysql Query query; StringBuffer queryString = new StringBuffer(); if(isPrev) { queryString.append("select sum(BasicNumber) as BasicNumber from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type +"'"); if(ProjectId!=null) { queryString.append(" and DepotId='" + ProjectId +"'"); } queryString.append(" and MaterialId ="+ MId + " and jsh_depothead.OperTime <'"+ MonthTime +"-01 00:00:00' "); query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } else { queryString.append("select sum(BasicNumber) as BasicNumber from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type +"'"); if(ProjectId!=null) { queryString.append(" and DepotId='" + ProjectId +"'"); } queryString.append(" and MaterialId ="+ MId + " and jsh_depothead.OperTime >='"+ MonthTime +"-01 00:00:00' and jsh_depothead.OperTime <='"+ MonthTime +"-31 59:59:59' "); query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); } @SuppressWarnings("unchecked") @Override public void findPriceByType(PageUtil<DepotItem> pageUtil,String type,Integer ProjectId,Long MId,String MonthTime,Boolean isPrev) throws JshException { //,createSQLQuerysql Query query; StringBuffer queryString = new StringBuffer(); if (isPrev) { queryString.append("select sum(AllPrice) as AllPrice from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type + "'"); if (ProjectId != null) { queryString.append(" and DepotId='" + ProjectId + "'"); } queryString.append(" and MaterialId =" + MId + " and jsh_depothead.OperTime <'" + MonthTime + "-01 00:00:00' "); query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } else { queryString.append("select sum(AllPrice) as AllPrice from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type + "'"); if (ProjectId != null) { queryString.append(" and DepotId='" + ProjectId + "'"); } queryString.append(" and MaterialId =" + MId + " and jsh_depothead.OperTime >='" + MonthTime + "-01 00:00:00' and jsh_depothead.OperTime <='" + MonthTime + "-31 59:59:59' "); query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); } @SuppressWarnings("unchecked") @Override public void buyOrSale(PageUtil<DepotItem> pageUtil,String type, String subType,Long MId,String MonthTime, String sumType) throws JshException { //,createSQLQuerysql Query query; if(sumType.equals("Number")) { query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery("select sum(BasicNumber) as BasicNumber from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type +"' and subType='" + subType +"' and MaterialId ="+ MId + " and jsh_depothead.OperTime >='"+ MonthTime +"-01 00:00:00' and jsh_depothead.OperTime <='"+ MonthTime +"-31 59:59:59' " + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } else { query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery("select sum(AllPrice) as AllPrice from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and type='" + type +"' and subType='" + subType +"' and MaterialId ="+ MId + " and jsh_depothead.OperTime >='"+ MonthTime +"-01 00:00:00' and jsh_depothead.OperTime <='"+ MonthTime +"-31 59:59:59' " + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); } pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); } @SuppressWarnings("unchecked") @Override public void findGiftByType(PageUtil<DepotItem> pageUtil,String subType,Integer ProjectId,Long MId,String type) throws JshException { //,createSQLQuerysql Query query; StringBuffer queryString = new StringBuffer(); queryString.append("select sum(BasicNumber) as BasicNumber from jsh_depotitem,jsh_depothead where jsh_depotitem.HeaderId = jsh_depothead.id and jsh_depothead.SubType='" + subType +"'"); if(ProjectId!=null) { if(type.equals("in")){ queryString.append(" and jsh_depotitem.AnotherDepotId='" + ProjectId +"'"); } else if(type.equals("out")){ queryString.append(" and jsh_depotitem.DepotId='" + ProjectId +"'"); } } queryString.append(" and jsh_depotitem.MaterialId ="+ MId); query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); } }
// MasterController.java package de.htwg.battleship.controller.impl; import de.htwg.battleship.controller.IMasterController; import de.htwg.battleship.controller.Viewer; import de.htwg.battleship.model.IPlayer; import de.htwg.battleship.model.impl.Ship; import de.htwg.battleship.observer.impl.Observable; import de.htwg.battleship.util.StatCollection; /** * MasterController is an implementation of the master controller. * @author Moritz Sauter (SauterMoritz@gmx.de) * @version 1.00 * @since 2014-12-16 */ public class MasterController extends Observable implements IMasterController { /** * Internal Ship controller. */ private final ShipController shipController; /** * Internal shoot controller. */ private final ShootController shootController; /** * Internal win controller. */ private final WinController winController; /** * Saves the first Player. */ private final IPlayer player1; /** * Saves the second Player. */ private final IPlayer player2; /** * Presentation of the Game. */ private Viewer view; /** * Public Constructor. * @param player1 player one * @param player2 player two */ public MasterController(final IPlayer player1, final IPlayer player2) { this.shipController = new ShipController(); this.shootController = new ShootController(player1, player2); this.winController = new WinController(player1, player2); this.player1 = player1; this.player2 = player2; this.view = null; } @Override public final void shoot(final int x, final int y, final IPlayer player) { boolean first; first = (player == this.player1); this.setViewer(new HitMissViewer(shootController.shoot(x, y, first))); this.win(); } @Override public final void placeShip(final int x, final int y, final boolean orientation, final IPlayer player) { if (!shipController.placeShip( new Ship((player.getOwnBoard().getShips() + 2), orientation, x, y), player)) { this.setViewer(new PlaceErrorViewer()); this.view = new PlaceViewer(player); } if (player.getOwnBoard().getShips() == StatCollection.SHIP_NUMBER_MAX) { this.view = new PlaceFieldViewer(player); } notifyObserver(); } @Override public final void win() { IPlayer winner = winController.win(); if (winner == null) { return; } this.setViewer(new WinPlayer(winner)); System.exit(0); } @Override public final String getString() { return view.getString(); } @Override public final void setViewer(final Viewer view) { this.view = view; notifyObserver(); } @Override public final IPlayer getPlayer1() { return player1; } @Override public final IPlayer getPlayer2() { return player2; } }
package com.svlada.ssh; import org.apache.commons.lang3.Validate; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.svlada.ssh.logger.JschLogger; /** * Helper class for building {@link Session} objects. * * @author vladimir.stankovic (svlada@gmail.com) * */ public class PublicKeySshSession { public static class Builder { private String host; private String username; private int port; private String privateKeyPath; private com.jcraft.jsch.Logger logger; private void validate() { Validate.notBlank(host); Validate.notBlank(username); Validate.notBlank(privateKeyPath); if (port < 1) { throw new IllegalArgumentException("Port number must start with 1."); } } public Session build() { validate(); if (logger != null) { JSch.setLogger(new JschLogger()); } JSch jsch = new JSch(); Session session = null; try { jsch.addIdentity(privateKeyPath); session = jsch.getSession(username, host, port); session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); } catch (JSchException e) { throw new RuntimeException("Failed to create Jsch Session object.", e); } return session; } public Builder logger(com.jcraft.jsch.Logger logger) { this.logger = logger; return this; } public Builder host(String host) { this.host = host; return this; } public Builder username(String username) { this.username = username; return this; } public Builder port(int port) { this.port = port; return this; } public Builder privateKeyPath(String privateKeyPath) { this.privateKeyPath = privateKeyPath; return this; } } }
package com.tenable.io.api; import com.tenable.io.api.agentGroups.AgentGroupsApi; import com.tenable.io.api.agents.AgentsApi; import com.tenable.io.api.filters.FiltersApi; import com.tenable.io.api.folders.FolderHelper; import com.tenable.io.api.permissions.PermissionsApi; import com.tenable.io.api.scannerGroups.ScannerGroupsApi; import com.tenable.io.api.editors.EditorApi; import com.tenable.io.api.file.FileApi; import com.tenable.io.api.exlusions.ExclusionsApi; import com.tenable.io.api.folders.FoldersApi; import com.tenable.io.api.groups.GroupsApi; import com.tenable.io.api.plugins.PluginsApi; import com.tenable.io.api.policies.PoliciesApi; import com.tenable.io.api.scanners.ScannersApi; import com.tenable.io.api.scans.ScanHelper; import com.tenable.io.api.scans.ScansApi; import com.tenable.io.api.server.ServerApi; import com.tenable.io.api.targetGroups.TargetGroupsApi; import com.tenable.io.api.users.UsersApi; import com.tenable.io.api.workbenches.WorkbenchHelper; import com.tenable.io.api.workbenches.WorkbenchesApi; import com.tenable.io.core.services.AsyncHttpService; public class TenableIoClient implements AutoCloseable { private static String DEFAULT_TENABLE_IO_SCHEME = "https"; private static String DEFAULT_TENABLE_IO_HOST = "cloud.tenable.com"; private String impersonateUsername = null; private String accessKey; private String secretKey; private String tenableIoHost; private String tenableIoScheme; private AsyncHttpService asyncHttpService; private UsersApi usersApi = null; private ScansApi scansApi = null; private FoldersApi foldersApi = null; private PoliciesApi policiesApi = null; private EditorApi editorApi = null; private FileApi fileApi = null; private FiltersApi filtersApi = null; private PluginsApi pluginsApi = null; private GroupsApi userGroupsApi = null; private ScannerGroupsApi scannerGroupsApi = null; private ScannersApi scannersApi = null; private ExclusionsApi exclusionsApi = null; private AgentsApi agentsApi = null; private AgentGroupsApi agentGroupsApi = null; private TargetGroupsApi targetGroupsApi = null; private PermissionsApi permissionsApi = null; private ServerApi serverApi = null; private WorkbenchesApi workbenchesApi = null; private ScanHelper scanHelper = null; private WorkbenchHelper workbenchHelper = null; private FolderHelper folderHelper = null; /** * Instantiates a new Tenable IO client from environment variables. * Needs JVM params tenableIoAccessKey and tenableIoSecretKey or environment variables TENABLEIO_ACCESS_KEY and TENABLEIO_SECRET_KEY */ public TenableIoClient() { // first check the JVM param accessKey = System.getProperty( "tenableIoAccessKey" ); secretKey = System.getProperty( "tenableIoSecretKey" ); tenableIoScheme = System.getProperty( "tenableIoScheme" ); tenableIoHost = System.getProperty( "tenableIoHost" ); // if not there, default to environment variables if( accessKey == null || secretKey == null ) { accessKey = System.getenv( "TENABLEIO_ACCESS_KEY" ); secretKey = System.getenv( "TENABLEIO_SECRET_KEY" ); } if( tenableIoScheme == null ) { tenableIoScheme = System.getProperty( "TENABLE_IO_SCHEME" ); if( tenableIoScheme == null ) tenableIoScheme = DEFAULT_TENABLE_IO_SCHEME; } if( tenableIoHost == null ) { tenableIoHost = System.getProperty( "TENABLE_IO_HOST" ); if( tenableIoHost == null ) tenableIoHost = DEFAULT_TENABLE_IO_HOST; } asyncHttpService = new AsyncHttpService( accessKey, secretKey ); } /** * Instantiates a new Tenable IO client. * * @param accessKey the access key * @param secretKey the secret key */ public TenableIoClient( String accessKey, String secretKey ) { this.accessKey = accessKey; this.secretKey = secretKey; tenableIoScheme = System.getProperty( "tenableIoScheme" ); tenableIoHost = System.getProperty( "tenableIoHost" ); if( tenableIoScheme == null ) { tenableIoScheme = System.getProperty( "TENABLE_IO_SCHEME" ); if( tenableIoScheme == null ) tenableIoScheme = DEFAULT_TENABLE_IO_SCHEME; } if( tenableIoHost == null ) { tenableIoHost = System.getProperty( "TENABLE_IO_HOST" ); if( tenableIoHost == null ) tenableIoHost = DEFAULT_TENABLE_IO_HOST; } asyncHttpService = new AsyncHttpService( accessKey, secretKey ); } /** * Instantiates a new Tenable IO client which impersonates the given user. * Only used via the {@link #impersonate( String ) impersonate} method * * @param accessKey the access key * @param secretKey the secret key * @param impersonateUsername the username to impersonate */ private TenableIoClient( String accessKey, String secretKey, String impersonateUsername ) { this.accessKey = accessKey; this.secretKey = secretKey; this.impersonateUsername = impersonateUsername; asyncHttpService = new AsyncHttpService( accessKey, secretKey, impersonateUsername ); } /** * Instantiates a new Tenable IO client, using the given proxy * Note: this constructor is only used for development/debug and TURNS OFF SSL VALIDATION * * @param asyncHttpService the asyncHttpService to use */ TenableIoClient( AsyncHttpService asyncHttpService ) { this.asyncHttpService = asyncHttpService; } /** * Returns a new client which impersonates the given user * * @param username The username to impersonate * @return The new client, which impersonates the given user */ public TenableIoClient impersonate( String username ) { return new TenableIoClient( accessKey, secretKey, username ); } /** * Closes this resource, relinquishing any underlying resources. * This method is invoked automatically on objects managed by the * {@code try}-with-resources statement. * * @throws Exception if this resource cannot be closed */ @Override public void close() throws Exception { if( asyncHttpService != null ) asyncHttpService.close(); } /** * Gets users API helper. * * @return the users API helper */ synchronized public UsersApi getUsersApi() { if( usersApi == null ) usersApi = new UsersApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return usersApi; } /** * Gets scans api. * * @return the scans api */ synchronized public ScansApi getScansApi() { if( scansApi == null ) scansApi = new ScansApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return scansApi; } /** * Gets folders api. * * @return the folders api */ synchronized public FoldersApi getFoldersApi() { if( foldersApi == null ) foldersApi = new FoldersApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return foldersApi; } /** * Gets policies api. * * @return the policies api */ synchronized public PoliciesApi getPoliciesApi() { if( policiesApi == null ) policiesApi = new PoliciesApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return policiesApi; } /** * Gets editor api. * * @return the editor api */ synchronized public EditorApi getEditorApi() { if( editorApi == null ) editorApi = new EditorApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return editorApi; } /** * Gets file api. * * @return the file api */ synchronized public FileApi getFileApi() { if( fileApi == null ) fileApi = new FileApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return fileApi; } /** * Gets filters api. * * @return the filters api */ synchronized public FiltersApi getFiltersApi() { if( filtersApi == null ) filtersApi = new FiltersApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return filtersApi; } /** * Gets plugins api. * * @return the plugins api */ synchronized public PluginsApi getPluginsApi() { if( pluginsApi == null ) pluginsApi = new PluginsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return pluginsApi; } /** * Gets user groups api. * * @return the user groups api */ synchronized public GroupsApi getUserGroupsApi() { if( userGroupsApi == null ) userGroupsApi = new GroupsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return userGroupsApi; } /** * Gets scanner groups api. * * @return the scanner groups api */ synchronized public ScannerGroupsApi getScannerGroupsApi() { if( scannerGroupsApi == null ) scannerGroupsApi = new ScannerGroupsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return scannerGroupsApi; } /** * Gets scanners api. * * @return the scanners api */ synchronized public ScannersApi getScannersApi() { if( scannersApi == null ) scannersApi = new ScannersApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return scannersApi; } /** * Gets exclusions api. * * @return the exclusions api */ synchronized public ExclusionsApi getExclusionsApi() { if( exclusionsApi == null ) exclusionsApi = new ExclusionsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return exclusionsApi; } /** * Gets agents api. * * @return the agents api */ synchronized public AgentsApi getAgentsApi() { if( agentsApi == null ) agentsApi = new AgentsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return agentsApi; } /** * Gets agent groups api. * * @return the agent groups api */ synchronized public AgentGroupsApi getAgentGroupsApi() { if( agentGroupsApi == null ) agentGroupsApi = new AgentGroupsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return agentGroupsApi; } /** * Gets asset lists api. * * @return the asset lists api */ synchronized public TargetGroupsApi getTargetGroupsApi() { if( targetGroupsApi == null ) targetGroupsApi = new TargetGroupsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return targetGroupsApi; } synchronized public PermissionsApi getPermissionsApi() { if( permissionsApi == null ) permissionsApi = new PermissionsApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return permissionsApi; } /** * Gets server api. * * @return the server api */ synchronized public ServerApi getServerApi() { if( serverApi == null ) serverApi = new ServerApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return serverApi; } /** * Gets workbenches api. * * @return the workbenches api */ synchronized public WorkbenchesApi getWorkbenchesApi() { if( workbenchesApi == null ) workbenchesApi = new WorkbenchesApi( asyncHttpService, getTenableIoScheme(), getTenableIoHost() ); return workbenchesApi; } /** * Gets scan helper. * * @return the scan helper */ synchronized public ScanHelper getScanHelper() { if( scanHelper == null ) scanHelper = new ScanHelper( this ); return scanHelper; } /** * Gets workbench helper. * * @return the workbench helper */ synchronized public WorkbenchHelper getWorkbenchHelper() { if( workbenchHelper == null ) workbenchHelper = new WorkbenchHelper( this ); return workbenchHelper; } /** * Gets folder helper. * * @return the folder helper */ synchronized public FolderHelper getFolderHelper() { if( folderHelper == null ) folderHelper = new FolderHelper( this ); return folderHelper; } private String getTenableIoHost() { return tenableIoHost; } private String getTenableIoScheme() { return tenableIoScheme; } }
package com.yahoo.memory; import static com.yahoo.memory.UnsafeUtil.unsafe; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.Cleaner; //TODO-JDK9 jdk.internal.ref.Cleaner; import sun.nio.ch.FileChannelImpl; class AllocateDirectMap implements Map { private static final Logger LOG = LoggerFactory.getLogger(AllocateDirectMap.class); private static final int MAP_RO = 0; private static final int MAP_RW = 1; private static final Method FILE_CHANNEL_IMPL_MAP0_METHOD; private static final Method FILE_CHANNEL_IMPL_UNMAP0_METHOD; private static final Method MAPPED_BYTE_BUFFER_LOAD0_METHOD; private static final Method MAPPED_BYTE_BUFFER_ISLOADED0_METHOD; static final Method MAPPED_BYTE_BUFFER_FORCE0_METHOD; static { try { FILE_CHANNEL_IMPL_MAP0_METHOD = FileChannelImpl.class .getDeclaredMethod("map0", int.class, long.class, long.class); FILE_CHANNEL_IMPL_MAP0_METHOD.setAccessible(true); FILE_CHANNEL_IMPL_UNMAP0_METHOD = FileChannelImpl.class .getDeclaredMethod("unmap0", long.class, long.class); FILE_CHANNEL_IMPL_UNMAP0_METHOD.setAccessible(true); MAPPED_BYTE_BUFFER_LOAD0_METHOD = MappedByteBuffer.class .getDeclaredMethod("load0", long.class, long.class); MAPPED_BYTE_BUFFER_LOAD0_METHOD.setAccessible(true); MAPPED_BYTE_BUFFER_ISLOADED0_METHOD = MappedByteBuffer.class .getDeclaredMethod("isLoaded0", long.class, long.class, int.class); MAPPED_BYTE_BUFFER_ISLOADED0_METHOD.setAccessible(true); MAPPED_BYTE_BUFFER_FORCE0_METHOD = MappedByteBuffer.class .getDeclaredMethod("force0", FileDescriptor.class, long.class, long.class); MAPPED_BYTE_BUFFER_FORCE0_METHOD.setAccessible(true); } catch (final Exception e) { throw new RuntimeException("Could not reflect static methods: " + e); } } private final Deallocator deallocator; private final Cleaner cleaner; final long capacityBytes; final RandomAccessFile raf; final long nativeBaseOffset; final boolean resourceReadOnly; //called from AllocateDirectWritableMap constructor AllocateDirectMap(final File file, final long fileOffsetBytes, final long capacityBytes, final boolean localReadOnly) { this.capacityBytes = capacityBytes; resourceReadOnly = isFileReadOnly(file); final long fileLength = file.length(); if ((localReadOnly || resourceReadOnly) && ((fileOffsetBytes + capacityBytes) > fileLength)) { throw new IllegalArgumentException( "Read-only mode and requested map length is greater than current file length: " + "Requested Length = " + (fileOffsetBytes + capacityBytes) + ", Current File Length = " + fileLength); } raf = mapper(file, fileOffsetBytes, capacityBytes, resourceReadOnly); nativeBaseOffset = map(raf.getChannel(), resourceReadOnly, fileOffsetBytes, capacityBytes); deallocator = new Deallocator(nativeBaseOffset, capacityBytes, raf); cleaner = Cleaner.create(this, deallocator); } @Override public void load() { madvise(); // Performance optimization. Read a byte from each page to bring it into memory. final int ps = NioBits.pageSize(); final int count = NioBits.pageCount(capacityBytes); long offset = nativeBaseOffset; for (int i = 0; i < count; i++) { unsafe.getByte(offset); offset += ps; } } @Override public boolean isLoaded() { try { final int pageCount = NioBits.pageCount(capacityBytes); return (boolean) MAPPED_BYTE_BUFFER_ISLOADED0_METHOD //isLoaded0 is effectively static, so ZERO_READ_ONLY_DIRECT_BYTE_BUFFER is not modified .invoke(AccessByteBuffer.ZERO_READ_ONLY_DIRECT_BYTE_BUFFER, nativeBaseOffset, capacityBytes, pageCount); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while loading", e.getClass())); } } @Override public void close() { doClose(); } boolean doClose() { if (deallocator.deallocate(false)) { // This Cleaner.clean() call effectively just removes the Cleaner from the internal linked // list of all cleaners. It will delegate to Deallocator.deallocate() which will be a no-op // because the valid state is already changed. cleaner.clean(); return true; } else { return false; } } StepBoolean getValid() { return deallocator.getValid(); } // Private methods /** * called by load(). Calls the native method load0 in MappedByteBuffer.java, implemented * in MappedByteBuffer.c. See reference at top of class. load0 allows setting a mapping length * of greater than 2GB. */ private void madvise() { try { MAPPED_BYTE_BUFFER_LOAD0_METHOD //load0 is effectively static, so ZERO_READ_ONLY_DIRECT_BYTE_BUFFER is not modified .invoke(AccessByteBuffer.ZERO_READ_ONLY_DIRECT_BYTE_BUFFER, nativeBaseOffset, capacityBytes); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while loading", e.getClass())); } } //Does the actual mapping work, resourceReadOnly must already be set private static RandomAccessFile mapper(final File file, final long fileOffset, final long capacityBytes, final boolean resourceReadOnly) { final String mode = resourceReadOnly ? "r" : "rw"; final RandomAccessFile raf; try { raf = new RandomAccessFile(file, mode); if ((fileOffset + capacityBytes) > raf.length()) { raf.setLength(fileOffset + capacityBytes); } } catch (final IOException e) { throw new RuntimeException(e); } return raf; } /** * Creates a mapping of the FileChannel starting at position and of size length to pages * in the OS. This may throw OutOfMemory error if you have exhausted memory. * You can try to force garbage collection and re-attempt. * * <p>map0 is a native method of FileChannelImpl.java implemented in FileChannelImpl.c. * See reference at top of class.</p> * * @param fileChannel the FileChannel * @param position the offset in bytes into the FileChannel * @param lengthBytes the length in bytes * @return the native base offset address * @throws RuntimeException Encountered an exception while mapping */ private static long map(final FileChannel fileChannel, final boolean resourceReadOnly, final long position, final long lengthBytes) { final int pagePosition = (int) (position % unsafe.pageSize()); final long mapPosition = position - pagePosition; final long mapSize = lengthBytes + pagePosition; final int mapMode = resourceReadOnly ? MAP_RO : MAP_RW; try { final long nativeBaseOffset = (long) FILE_CHANNEL_IMPL_MAP0_METHOD.invoke(fileChannel, mapMode, mapPosition, mapSize); return nativeBaseOffset; } catch (final InvocationTargetException e) { throw new RuntimeException("Exception while mapping", e.getTargetException()); } catch (final IllegalAccessException e) { throw new RuntimeException("Exception while mapping", e); } } private static boolean isFileReadOnly(final File file) { if (System.getProperty("os.name").startsWith("Windows")) { return !file.canWrite(); } //All Unix-like OSes final Path path = Paths.get(file.getAbsolutePath()); PosixFileAttributes attributes = null; try { attributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); } catch (final IOException e) { // File presence is guaranteed. Ignore e.printStackTrace(); } if (attributes == null) { return false; } final Set<PosixFilePermission> permissions = attributes.permissions(); int bits = 0; bits |= ((permissions.contains(PosixFilePermission.OWNER_READ)) ? 1 << 8 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_WRITE)) ? 1 << 7 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_EXECUTE)) ? 1 << 6 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_READ)) ? 1 << 5 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_WRITE)) ? 1 << 4 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_EXECUTE)) ? 1 << 3 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_READ)) ? 1 << 2 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_WRITE)) ? 1 << 1 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) ? 1 : 0); // Here we are going to ignore the Owner Write & Execute bits to allow root/owner testing. return ((bits & 0477) == 0444); } private static final class Deallocator implements Runnable { private final RandomAccessFile myRaf; private final FileChannel myFc; //This is the only place the actual native offset is kept for use by unsafe.freeMemory(); private final long actualNativeBaseOffset; private final long myCapacity; private final StepBoolean valid = new StepBoolean(true); //only place for this Deallocator(final long nativeBaseOffset, final long capacityBytes, final RandomAccessFile raf) { BaseState.currentDirectMemoryMapAllocations_.incrementAndGet(); BaseState.currentDirectMemoryMapAllocated_.addAndGet(capacityBytes); myRaf = raf; assert (myRaf != null); myFc = myRaf.getChannel(); actualNativeBaseOffset = nativeBaseOffset; assert (actualNativeBaseOffset != 0); myCapacity = capacityBytes; assert (myCapacity != 0); } StepBoolean getValid() { return valid; } @Override public void run() { deallocate(true); } boolean deallocate(final boolean calledFromCleaner) { if (valid.change()) { if (calledFromCleaner) { // Warn about non-deterministic resource cleanup. LOG.warn("A WritableMapHandle was not closed manually"); } try { unmap(); } finally { BaseState.currentDirectMemoryMapAllocations_.decrementAndGet(); BaseState.currentDirectMemoryMapAllocated_.addAndGet(-myCapacity); } return true; } else { return false; } } /** * Removes existing mapping. <i>unmap0</i> is a native method in FileChannelImpl.c. See * reference at top of class. */ private void unmap() throws RuntimeException { try { FILE_CHANNEL_IMPL_UNMAP0_METHOD.invoke(myFc, actualNativeBaseOffset, myCapacity); myRaf.close(); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while freeing memory", e.getClass())); } } } //End of class Deallocator }
package edu.asu.conceptpower.web; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import edu.asu.conceptpower.wrapper.ConceptEntryWrapper; import edu.mit.jwi.item.POS; @Component public class ConceptSearchBean { private String word; private POS pos; private Map<POS, String> posMap; private List<ConceptEntryWrapper> foundConcepts; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public List<ConceptEntryWrapper> getFoundConcepts() { return foundConcepts; } public void setFoundConcepts(List<ConceptEntryWrapper> foundConcepts) { this.foundConcepts = foundConcepts; } public POS getPos() { return pos; } public void setPos(POS pos) { this.pos = pos; } public Map<POS, String> getPosMap() { posMap = new LinkedHashMap<POS, String>(); posMap.put(POS.NOUN, "Noun"); posMap.put(POS.VERB, "Verb"); posMap.put(POS.ADVERB, "Adverb"); posMap.put(POS.ADJECTIVE, "Adjective"); return posMap; } public void setPosMap(Map<POS, String> posMap) { this.posMap = posMap; } }
package com.yahoo.omid.tso; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Random; public class CacheEvaluation { final static int ENTRIES = 1000000; final static int WARMUP_ROUNDS = 20; final static int ROUNDS = 20; Histogram hist = new Histogram(ENTRIES * 100); public void testEntriesAge(int asoc, PrintWriter writer) { LongCache cache = new LongCache(ENTRIES, asoc); Random random = new Random(); long seed = random.nextLong(); writer.println("# Random seed: " + seed); random.setSeed(seed); int removals = 0; long totalAge = 0; double tempStdDev = 0; double tempAvg = 0; int i = 0; int largestDeletedTimestamp = 0; for (; i < ENTRIES * WARMUP_ROUNDS; ++i) { long removed = cache.set(random.nextLong(), i); if (removed > largestDeletedTimestamp) { largestDeletedTimestamp = (int) removed; } if (i % ENTRIES == 0) { int round = i / ENTRIES + 1; System.err.format("Warmup [%d/%d]\n", round, WARMUP_ROUNDS); } } long time = System.nanoTime(); for (; i < ENTRIES * (WARMUP_ROUNDS + ROUNDS); ++i) { long removed = cache.set(random.nextLong(), i); if (removed > largestDeletedTimestamp) { largestDeletedTimestamp = (int) removed; } int gap = i - largestDeletedTimestamp; removals++; totalAge += gap; double oldAvg = tempAvg; tempAvg += (gap - tempAvg) / removals; tempStdDev += (gap - oldAvg) * (gap - tempAvg); hist.add(gap); if (i % ENTRIES == 0) { int round = i / ENTRIES - WARMUP_ROUNDS + 1; System.err.format("Progress [%d/%d]\n", round, ROUNDS); } } long elapsed = System.nanoTime() - time; double elapsedSeconds = (elapsed / (double) 1000000000); long totalOps = ENTRIES * ROUNDS; writer.println("# Elapsed (s): " + elapsedSeconds); writer.println("# Elapsed per 100 ops (ms): " + (elapsed / (double) totalOps / 100 / (double) 1000000)); writer.println("# Ops per s : " + (totalOps / elapsedSeconds)); double avgAge = totalAge / (double) removals; // LOG.info("Avg gap: " + (avgAge )); writer.println("# Avg gap: " + (tempAvg)); writer.println("# Std dev gap: " + Math.sqrt((tempStdDev / ENTRIES))); hist.print(writer); // System.out.println(hist.toString()); // assertThat(avgAge, is(greaterThan(entries * .9 ))); } public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int[] asoc = new int[] { 1, 2, 4, 8, 16, 32 }; for (int i = 0; i < asoc.length; ++i) { PrintWriter writer = new PrintWriter(asoc[i] + ".out", "UTF-8"); new CacheEvaluation().testEntriesAge(asoc[i], writer); writer.close(); } } }
package components; import com.badlogic.ashley.core.Component; public class UserCommitmentComponent implements Component { public float xCommitment, yCommitment; public CityBlockComponent destination; //Each schedule block has a timeBlock identifier, therefore we can store the time block corresponding to the current/last commitment so we don't make many decisions per time block public int commitmentTimeBlock = -1; }
package cpw.mods.fml.client; import java.io.IOException; import java.io.InputStream; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Iterator; import java.util.Properties; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.imageio.ImageIO; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.resources.FileResourcePack; import net.minecraft.client.resources.FolderResourcePack; import net.minecraft.client.resources.IResourcePack; import net.minecraft.crash.CrashReport; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.Level; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Drawable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.SharedDrawable; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ICrashCallable; import cpw.mods.fml.common.ProgressManager; import cpw.mods.fml.common.ProgressManager.ProgressBar; import cpw.mods.fml.common.asm.FMLSanityChecker; /** * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public class SplashProgress { private static Drawable d; private static volatile boolean pause = false; private static volatile boolean done = false; private static Thread thread; private static int angle = 0; private static final Lock lock = new ReentrantLock(true); private static SplashFontRenderer fontRenderer; private static final IResourcePack mcPack = Minecraft.getMinecraft().mcDefaultResourcePack; private static final IResourcePack fmlPack = createFmlResourcePack(); private static int fontTexture; private static ResourceLocation fontLocation = new ResourceLocation("textures/font/ascii.png"); private static int logoTexture; private static ResourceLocation logoLocation = new ResourceLocation("textures/gui/title/mojang.png"); private static int forgeTexture; private static ResourceLocation forgeLocation = new ResourceLocation("fml", "textures/gui/forge.png"); private static ResourceLocation configLocation = new ResourceLocation("fml", "splash.properties"); private static final Properties config = loadConfig(); private static final boolean enabled = Boolean.parseBoolean(config.getProperty("enabled")); private static final int backgroundColor = getInt("background"); private static final int fontColor = getInt("font"); private static final int barBorderColor = getInt("barBorder"); private static final int barColor = getInt("bar"); private static final int barBackgroundColor = getInt("barBackground"); public static void start() { if(!enabled) return; // getting debug info out of the way, while we still can FMLCommonHandler.instance().registerCrashCallable(new ICrashCallable() { public String call() throws Exception { return "' Vendor: '" + GL11.glGetString(GL11.GL_VENDOR) + "' Version: '" + GL11.glGetString(GL11.GL_VERSION) + "' Renderer: '" + GL11.glGetString(GL11.GL_RENDERER) + "'"; } public String getLabel() { return "GL info"; } }); CrashReport report = CrashReport.makeCrashReport(new Throwable(), "Loading screen debug info"); System.out.println(report.getCompleteReport()); fontTexture = GL11.glGenTextures(); loadTexture(mcPack, fontTexture, fontLocation); logoTexture = GL11.glGenTextures(); loadTexture(mcPack, logoTexture, logoLocation); forgeTexture = GL11.glGenTextures(); loadTexture(fmlPack, forgeTexture, forgeLocation); try { d = new SharedDrawable(Display.getDrawable()); Display.getDrawable().releaseContext(); d.makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } Thread mainThread = Thread.currentThread(); thread = new Thread(new Runnable() { private final int barWidth = 400; private final int barHeight = 20; private final int textHeight2 = 20; private final int barOffset = 55; public void run() { setGL(); while(!done) { ProgressBar first = null, penult = null, last = null; Iterator<ProgressBar> i = ProgressManager.barIterator(); while(i.hasNext()) { if(first == null) first = i.next(); else { penult = last; last = i.next(); } } GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); // matrix setup int w = Display.getWidth(); int h = Display.getHeight(); GL11.glViewport(0, 0, w, h); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(320 - w/2, 320 + w/2, 240 + h/2, 240 - h/2, -1, 1); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); // mojang logo setColor(backgroundColor); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glBindTexture(GL11.GL_TEXTURE_2D, logoTexture); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0, 0); GL11.glVertex2f(320 - 256, 240 - 256); GL11.glTexCoord2f(0, 1); GL11.glVertex2f(320 - 256, 240 + 256); GL11.glTexCoord2f(1, 1); GL11.glVertex2f(320 + 256, 240 + 256); GL11.glTexCoord2f(1, 0); GL11.glVertex2f(320 + 256, 240 - 256); GL11.glEnd(); GL11.glDisable(GL11.GL_TEXTURE_2D); // bars if(first != null) { GL11.glPushMatrix(); GL11.glTranslatef(320 - (float)barWidth / 2, 310, 0); drawBar(first); if(penult != null) { GL11.glTranslatef(0, barOffset, 0); drawBar(penult); } if(last != null) { GL11.glTranslatef(0, barOffset, 0); drawBar(last); } GL11.glPopMatrix(); } angle += 1; // forge logo setColor(backgroundColor); GL11.glTranslatef(680, 420, 0); GL11.glRotatef(angle, 0, 0, 1); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glBindTexture(GL11.GL_TEXTURE_2D, forgeTexture); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0, 0); GL11.glVertex2f(-50, -50); GL11.glTexCoord2f(0, 1); GL11.glVertex2f(-50, 50); GL11.glTexCoord2f(1, 1); GL11.glVertex2f(50, 50); GL11.glTexCoord2f(1, 0); GL11.glVertex2f(50, -50); GL11.glEnd(); GL11.glDisable(GL11.GL_TEXTURE_2D); Display.update(); if(pause) { clearGL(); setGL(); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } } clearGL(); } private void setColor(int color) { GL11.glColor3ub((byte)((color >> 16) & 0xFF), (byte)((color >> 8) & 0xFF), (byte)(color & 0xFF)); } private void drawBox(int w, int h) { GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(0, 0); GL11.glVertex2f(0, h); GL11.glVertex2f(w, h); GL11.glVertex2f(w, 0); GL11.glEnd(); } private void drawBar(ProgressBar b) { GL11.glPushMatrix(); // title - message setColor(fontColor); GL11.glScalef(2, 2, 1); GL11.glEnable(GL11.GL_TEXTURE_2D); fontRenderer.drawString(b.getTitle() + " - " + b.getMessage(), 0, 0, 0x000000); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glPopMatrix(); // border GL11.glPushMatrix(); GL11.glTranslatef(0, textHeight2, 0); setColor(barBorderColor); drawBox(barWidth, barHeight); // interior setColor(barBackgroundColor); GL11.glTranslatef(1, 1, 0); drawBox(barWidth - 2, barHeight - 2); // slidy part setColor(barColor); drawBox((barWidth - 2) * b.getStep() / b.getSteps(), barHeight - 2); // progress text String progress = "" + b.getStep() + "/" + b.getSteps(); GL11.glTranslatef(((float)barWidth - 2 - fontRenderer.getStringWidth(progress))/ 2, 2, 0); setColor(fontColor); GL11.glScalef(2, 2, 1); GL11.glEnable(GL11.GL_TEXTURE_2D); fontRenderer.drawString(progress, 0, 0, 0x000000); GL11.glPopMatrix(); } private void setGL() { lock.lock(); try { Display.getDrawable().makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } GL11.glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glEnable(GL11.GL_TEXTURE_2D); if(fontRenderer == null) { fontRenderer = new SplashFontRenderer(); } GL11.glDisable(GL11.GL_TEXTURE_2D); } private void clearGL() { Minecraft mc = Minecraft.getMinecraft(); mc.displayWidth = Display.getWidth(); mc.displayHeight = Display.getHeight(); mc.resize(mc.displayWidth, mc.displayHeight); GL11.glClearColor(1, 1, 1, 1); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, .1f); try { Display.getDrawable().releaseContext(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { lock.unlock(); } } }); thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { FMLLog.log(Level.ERROR, e, "Splash thread Exception"); Minecraft.getMinecraft().crashed(CrashReport.makeCrashReport(e, "Splash thread")); } }); thread.start(); } /** * Call before you need to explicitly modify GL context state during loading. * Resource loading doesn't usually require this call. * Call {@link #resume()} when you're done. * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public static void pause() { if(!enabled) return; pause = true; lock.lock(); try { d.releaseContext(); Display.getDrawable().makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public static void resume() { if(!enabled) return; pause = false; try { Display.getDrawable().releaseContext(); d.makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } lock.unlock(); } public static void finish() { if(!enabled) return; try { done = true; thread.join(); d.releaseContext(); Display.getDrawable().makeCurrent(); GL11.glDeleteTextures(fontTexture); GL11.glDeleteTextures(logoTexture); GL11.glDeleteTextures(forgeTexture); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } private static IResourcePack createFmlResourcePack() { if(FMLSanityChecker.fmlLocation.isDirectory()) { return new FolderResourcePack(FMLSanityChecker.fmlLocation); } else { return new FileResourcePack(FMLSanityChecker.fmlLocation); } } private static Properties loadConfig() { InputStream s = null; try { s = fmlPack.getInputStream(configLocation); Properties config = new Properties(); config.load(s); return config; } catch(IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(s); } } private static int getInt(String name) { return Integer.decode(config.getProperty(name)); } private static void loadTexture(IResourcePack pack, int name, ResourceLocation location) { InputStream s = null; try { s = pack.getInputStream(location); TextureUtil.uploadTextureImageAllocate(name, ImageIO.read(pack.getInputStream(location)), false, false); } catch(IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(s); } } private static class SplashFontRenderer extends FontRenderer { public SplashFontRenderer() { super(Minecraft.getMinecraft().gameSettings, fontLocation, null, false); super.onResourceManagerReload(null); } @Override protected void bindTexture(ResourceLocation location) { if(location != locationFontTexture) throw new IllegalArgumentException(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTexture); } @Override protected InputStream getResourceInputStream(ResourceLocation location) throws IOException { return Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(location); } } public static void drawVanillaScreen() throws LWJGLException { if(!enabled) { Minecraft.getMinecraft().loadScreen(); } } public static void clearVanillaResources(TextureManager renderEngine, ResourceLocation mojangLogo) { if(!enabled) { renderEngine.deleteTexture(mojangLogo); } } }
package de.comeight.crystallogy.items.armor; import java.util.List; import de.comeight.crystallogy.blocks.materials.CustomArmorMaterials; import de.comeight.crystallogy.handler.ItemHandler; import de.comeight.crystallogy.util.ToolTipBuilder; import de.comeight.crystallogy.util.Utilities; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; public class Armor_combined extends BaseArmor { private static final String ID = "armor_combined_"; public Armor_combined(int renderIndexIn, EntityEquipmentSlot equipmentSlotIn) { super(CustomArmorMaterials.CRYSTALL_COMBINED, renderIndexIn, equipmentSlotIn, ID + equipmentSlotIn.getName()); } public String getID(){ return ID + armorType.getName(); } public boolean isPlayerWearingFullArmor(EntityPlayer player){ if (player.inventory.armorItemInSlot(3) != null && player.inventory.armorItemInSlot(3).getItem() == ItemHandler.armorHelmet_combined && player.inventory.armorItemInSlot(2) != null && player.inventory.armorItemInSlot(2).getItem() == ItemHandler.armorChestplate_combined && player.inventory.armorItemInSlot(1) != null && player.inventory.armorItemInSlot(1).getItem() == ItemHandler.armorLeggins_combined && player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(0).getItem() == ItemHandler.armorBoots_combined) { return true; } return false; } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { int index = -1; if (!isPlayerWearingFullArmor(player) || (index = hasEnergyCrystal(player)) == -1) { disableCapabilities(world, player); } else{ if(itemStack.getItem() == ItemHandler.armorChestplate_combined){ enableCapabilities(world, player); if(!world.isRemote){ if(player.capabilities.isFlying){ damageEnergyCrystal(player, index); } else{ if(Utilities.getRandInt(0, 5) == 0){ damageEnergyCrystal(player, index); } } } } } } private void enableCapabilities(World world, EntityPlayer player){ if(!player.capabilities.isCreativeMode){ player.capabilities.allowFlying = true; player.capabilities.disableDamage = true; } if(!world.isRemote){ player.capabilities.setPlayerWalkSpeed(0.12F); player.capabilities.setFlySpeed(0.06F); } } private void disableCapabilities(World world, EntityPlayer player){ if(!player.capabilities.isCreativeMode){ player.capabilities.allowFlying = false; player.capabilities.isFlying = false; player.capabilities.disableDamage = false; } if(!world.isRemote){ player.capabilities.setPlayerWalkSpeed(0.1F); player.capabilities.setFlySpeed(0.05F); } } private int hasEnergyCrystal(EntityPlayer player){ for(int i = 0; i < player.inventory.mainInventory.length; i++){ if(player.inventory.mainInventory[i] != null && player.inventory.mainInventory[i].getItem() == ItemHandler.energyCrystal){ if(player.inventory.mainInventory[i].getItemDamage() < player.inventory.mainInventory[i].getMaxDamage()){ return i; } } } return -1; } private void damageEnergyCrystal(EntityPlayer player, int index){ player.inventory.getStackInSlot(index).damageItem(1, player); } @Override public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) { if(GuiScreen.isShiftKeyDown()){ tooltip.add(""); tooltip.add(TextFormatting.DARK_PURPLE + "When completely equipped:"); tooltip.add(TextFormatting.BLUE + "-Flight"); tooltip.add(TextFormatting.BLUE + "-Full damage protection (except void damage)"); tooltip.add(TextFormatting.BLUE + "+20% Speed"); } else{ ToolTipBuilder.addShiftForMoreDetails(tooltip); } super.addInformation(stack, playerIn, tooltip, advanced); } }
package cz.jcu.prf.uai.javamugs.logic; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class Game { public Game(int offset, byte difficulty, PressChart pressChart) { // TODO... } public Report tick(double curretTime, Chord chord) { throw new NotImplementedException(); } public void end() { throw new NotImplementedException(); } }
package de.SweetCode.SweetDB.DataSet; import de.SweetCode.SweetDB.DataType.DataType; import de.SweetCode.SweetDB.Table.Table; import java.util.logging.Level; import java.util.logging.Logger; public class Field<T> { private Table table; private String name; private T value; public Field(Table table, String name, T value) { this.table = table; this.name = name; this.value = value; } /** * Returns the name of the field. * @return */ public String getName() { return this.name; } /** * Returns the value of the field. * @return */ public T getValue() { return this.value; } /** * * @param dataType * @param <V> * @return */ public <V> V as(DataType dataType) { return (V) dataType.parse(this.value.toString()); } /** * * @param clazz * @param <V> * @return */ public <V> V as(V clazz) { return (V) clazz.getClass().cast(this.value); } /** * Updates the value. * @param value */ public boolean update(T value) { if(this.value == value) { return true; } T tmp = this.value; this.value = value; if(!(this.table.getSyntax().validate(this))) { this.value = tmp; if(this.table.getDatabase().isDebugging()) { Logger.getLogger("SweetDB").log( Level.INFO, String.format( "SweetDB - Field (Method: Update) (%s|%s) - Invalid Value: %s", this.getName(), this.value.toString(), value.toString() ) ); throw new IllegalArgumentException("You provided an invalid value."); } else { return false; } } if(this.table.getDatabase().isAutosave()) { this.table.store(); } return true; } }
package de.lessvoid.nifty.elements; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import de.lessvoid.nifty.EndNotify; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.FocusHandler; import de.lessvoid.nifty.controls.NiftyInputControl; import de.lessvoid.nifty.effects.Effect; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.effects.EffectManager; import de.lessvoid.nifty.effects.Falloff; import de.lessvoid.nifty.elements.render.ElementRenderer; import de.lessvoid.nifty.elements.render.TextRenderer; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.input.mouse.MouseInputEvent; import de.lessvoid.nifty.layout.LayoutPart; import de.lessvoid.nifty.layout.align.HorizontalAlign; import de.lessvoid.nifty.layout.align.VerticalAlign; import de.lessvoid.nifty.layout.manager.LayoutManager; import de.lessvoid.nifty.loaderv2.types.ElementType; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.render.RenderStateType; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.MouseOverHandler; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.nifty.tools.TimeProvider; import de.lessvoid.xml.tools.MethodInvoker; /** * The Element. * @author void */ public class Element { /** * Time before we start an automated click when mouse button is holded. */ private static final long REPEATED_CLICK_START_TIME = 100; /** * The time between automatic clicks. */ private static final long REPEATED_CLICK_TIME = 100; /** * the logger. */ private static Logger log = Logger.getLogger(Element.class.getName()); /** * element type. */ private ElementType elementType; /** * our identification. */ private String id; /** * the parent element. */ private Element parent; /** * the child elements. */ private ArrayList < Element > elements = new ArrayList < Element >(); /** * The LayoutManager we should use for all child elements. */ private LayoutManager layoutManager; /** * The LayoutPart for layout this element. */ private LayoutPart layoutPart; /** * The ElementRenderer we should use to render this element. */ private ElementRenderer[] elementRenderer; /** * the effect manager for this element. */ private EffectManager effectManager; /** * Element interaction. */ private ElementInteraction interaction; /** * Nifty instance this element is attached to. */ private Nifty nifty; /** * The focus handler this element is attached to. */ private FocusHandler focusHandler; /** * enable element. */ private boolean enabled; /** * visible element. */ private boolean visible; /** * this is set to true, when there's no interaction with the element * possible. this happens when the onEndScreen effect starts. */ private boolean done; /** * mouse down flag. */ private boolean mouseDown; /** * visible to mouse events. */ private boolean visibleToMouseEvents; /** * Last position of mouse X. */ private int lastMouseX; /** * Last position of mouse Y. */ private int lastMouseY; /** * mouse first click down time. */ private long mouseDownTime; /** * Time the last repeat has been activated. */ private long lastRepeatStartTime; /** * clip children. */ private boolean clipChildren; /** * attached control when this element is an control. */ private NiftyInputControl attachedInputControl = null; /** * remember if we've calculated this constraint ourself. */ private boolean isCalcWidthConstraint; /** * remember if we've calculated this constraint ourself. */ private boolean isCalcHeightConstraint; /** * focusable. */ private boolean focusable = false; /** * screen we're connected to. */ private Screen screen; /** * TimeProvider. */ private TimeProvider time; private boolean parentClipArea = false; private int parentClipX; private int parentClipY; private int parentClipWidth; private int parentClipHeight; /** * construct new instance of Element. * @param newNifty Nifty * @param newElementType elementType * @param newId the id * @param newParent new parent * @param newFocusHandler the new focus handler * @param newVisibleToMouseEvents visible to mouse * @param newTimeProvider TimeProvider * @param newElementRenderer the element renderer */ public Element( final Nifty newNifty, final ElementType newElementType, final String newId, final Element newParent, final FocusHandler newFocusHandler, final boolean newVisibleToMouseEvents, final TimeProvider newTimeProvider, final ElementRenderer ... newElementRenderer) { initialize( newNifty, newElementType, newId, newParent, newElementRenderer, new LayoutPart(), newFocusHandler, newVisibleToMouseEvents, newTimeProvider); } /** * construct new instance of Element using the given layoutPart instance. * @param newNifty Nifty * @param newElementType element type * @param newId the id * @param newParent new parent * @param newLayoutPart the layout part * @param newFocusHandler the new focus handler * @param newVisibleToMouseEvents visible to mouse * @param newTimeProvider TimeProvider * @param newElementRenderer the element renderer */ public Element( final Nifty newNifty, final ElementType newElementType, final String newId, final Element newParent, final LayoutPart newLayoutPart, final FocusHandler newFocusHandler, final boolean newVisibleToMouseEvents, final TimeProvider newTimeProvider, final ElementRenderer ... newElementRenderer) { initialize( newNifty, newElementType, newId, newParent, newElementRenderer, newLayoutPart, newFocusHandler, newVisibleToMouseEvents, newTimeProvider); } /** * initialize this instance helper. * @param newNifty Nifty * @param newElementType element * @param newId the id * @param newParent parent * @param newElementRenderer the element renderer to use * @param newLayoutPart the layoutPart to use * @param newFocusHandler the focus handler that this element is attached to * @param newVisibleToMouseEvents visible to mouse * @param timeProvider TimeProvider to use */ private void initialize( final Nifty newNifty, final ElementType newElementType, final String newId, final Element newParent, final ElementRenderer[] newElementRenderer, final LayoutPart newLayoutPart, final FocusHandler newFocusHandler, final boolean newVisibleToMouseEvents, final TimeProvider timeProvider) { this.nifty = newNifty; this.elementType = newElementType; this.id = newId; this.parent = newParent; this.elementRenderer = newElementRenderer; this.effectManager = new EffectManager(); this.layoutPart = newLayoutPart; this.enabled = true; this.visible = true; this.done = false; this.focusHandler = newFocusHandler; this.visibleToMouseEvents = newVisibleToMouseEvents; this.time = timeProvider; this.setMouseDown(false, 0); this.interaction = new ElementInteraction(nifty); } /** * get the id of this element. * @return the id */ public String getId() { return id; } /** * get parent. * @return parent */ public Element getParent() { return parent; } /** * get element state as string. * @param offset offset string * @return the element state as string. */ public String getElementStateString(final String offset) { String pos = " style [" + getElementType().getAttributes().get("style") + "], state [" + getState() + "]," + " position [" + getX() + ", " + getY() + ", " + getWidth() + ", " + getHeight() + "], constraint [" + outputSizeValue(layoutPart.getBoxConstraints().getX()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getY()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getWidth()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getHeight()) + "]" + " focusable [" + focusable + "] mouseable [" + visibleToMouseEvents + "]"; return pos; } private String getState() { if (isEffectActive(EffectEventId.onStartScreen)) { return "starting"; } if (isEffectActive(EffectEventId.onEndScreen)) { return "ending"; } if (!visible) { return "hidden"; } return "normal"; } /** * Output SizeValue. * @param value SizeValue * @return value string */ private String outputSizeValue(final SizeValue value) { if (value == null) { return "null"; } else { return value.toString(); } } /** * get x. * @return x position of this element. */ public int getX() { return layoutPart.getBox().getX(); } /** * get y. * @return the y position of this element. */ public int getY() { return layoutPart.getBox().getY(); } /** * get height. * @return the height of this element. */ public int getHeight() { return layoutPart.getBox().getHeight(); } /** * get width. * @return the width of this element. */ public int getWidth() { return layoutPart.getBox().getWidth(); } /** * get all child elements of this element. * @return the list of child elements */ public List < Element > getElements() { return elements; } /** * add a child element. * @param widget the child to add */ public void add(final Element widget) { elements.add(widget); } /** * render this element. * @param r the RenderDevice to use */ public void render(final NiftyRenderEngine r) { // render element only when it is visible if (visible) { r.saveState(RenderStateType.allStates()); // begin rendering / pre effectManager.begin(r, this); effectManager.renderPre(r, this); // render element if (elementRenderer != null) { for (ElementRenderer renderer : elementRenderer) { renderer.render(this, r); } } // finish rendering / post effectManager.renderPost(r, this); effectManager.end(r); if (clipChildren) { r.enableClip(getX(), getY(), getX() + getWidth(), getY() + getHeight()); } // now render child elements for (int i = 0; i < elements.size(); i++) { Element p = elements.get(i); p.render(r); } if (clipChildren) { r.disableClip(); } r.restoreState(); r.saveState(RenderStateType.allStates()); effectManager.renderOverlay(r, this); r.restoreState(); } } /** * Set a new LayoutManager. * @param newLayout the new LayoutManager to use. */ public void setLayoutManager(final LayoutManager newLayout) { this.layoutManager = newLayout; } /** * pre-process constraint width. */ private void preProcessConstraintWidth() { for (Element e : elements) { e.preProcessConstraintWidth(); } // try the original width value first SizeValue myWidth = getConstraintWidth(); // is it empty and we have an layoutManager there's still hope for a width constraint if (layoutManager != null && (myWidth == null || isCalcWidthConstraint)) { // collect all child layoutPart that have a fixed pixel size in a list List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >(); for (Element e : elements) { SizeValue childWidth = e.getConstraintWidth(); if (childWidth != null && childWidth.isPixel()) { layoutPartChild.add(e.layoutPart); } } // if all (!) child elements have a pixel fixed width we can calculate a new width constraint for this element! if (elements.size() == layoutPartChild.size()) { SizeValue newWidth = layoutManager.calculateConstraintWidth(layoutPartChild); if (newWidth != null) { // log.info("pre processed new width for element: " + getId() + ": " + newWidth.getValueAsInt(0)); setConstraintWidth(newWidth); isCalcWidthConstraint = true; } } } } /** * pre process constraint height. */ private void preProcessConstraintHeight() { for (Element e : elements) { e.preProcessConstraintHeight(); } // try the original height value first SizeValue myHeight = getConstraintHeight(); // is it empty and we have an layoutManager there's still hope for a height constraint if (layoutManager != null && (myHeight == null || isCalcHeightConstraint)) { // collect all child layoutPart that have a fixed px size in a list List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >(); for (Element e : elements) { SizeValue childHeight = e.getConstraintHeight(); if (childHeight != null && childHeight.isPixel()) { layoutPartChild.add(e.layoutPart); } } // if all (!) child elements have a px fixed height we can calculate a new height constraint for this element! if (elements.size() == layoutPartChild.size()) { SizeValue newHeight = layoutManager.calculateConstraintHeight(layoutPartChild); if (newHeight != null) { // log.info("pre processed new height for element: " + getId() + ": " + newHeight.getValueAsInt(0)); setConstraintHeight(newHeight); isCalcHeightConstraint = true; } } } } public void processLayout() { for (Element w : elements) { TextRenderer textRenderer = w.getRenderer(TextRenderer.class); if (textRenderer != null) { textRenderer.setWidthConstraint(w, w.getConstraintWidth(), getWidth(), nifty.getRenderEngine()); } } if (layoutManager != null) { // we need a list of LayoutPart and not of Element, so we'll build one on the fly here List < LayoutPart > layoutPartChild = new ArrayList < LayoutPart >(); for (Element w : elements) { layoutPartChild.add(w.layoutPart); } // use out layoutManager to layout our children layoutManager.layoutElements(layoutPart, layoutPartChild); // repeat this step for all child elements for (Element w : elements) { w.processLayout(); } } if (clipChildren) { for (Element w : elements) { w.setParentClipArea(getX(), getY(), getWidth(), getHeight()); } } } /** * layout this element and all it's children. */ public void layoutElements() { prepareLayout(); processLayout(); } private void prepareLayout() { preProcessConstraintWidth(); preProcessConstraintHeight(); } private void setParentClipArea(final int x, final int y, final int width, final int height) { parentClipArea = true; parentClipX = x; parentClipY = y; parentClipWidth = width; parentClipHeight = height; for (Element w : elements) { w.setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight); } } /** * reset all effects. */ public void resetEffects() { mouseDown = false; effectManager.reset(); for (Element w : elements) { w.resetEffects(); } } public void resetAllEffects() { mouseDown = false; effectManager.resetAll(); for (Element w : elements) { w.resetAllEffects(); } } public void resetSingleEffect(final EffectEventId effectEventId) { mouseDown = false; effectManager.resetSingleEffect(effectEventId); for (Element w : elements) { w.resetSingleEffect(effectEventId); } } public void resetMouseDown() { mouseDown = false; for (Element w : elements) { w.resetMouseDown(); } } /** * set new x position constraint. * @param newX new x constraint. */ public void setConstraintX(final SizeValue newX) { layoutPart.getBoxConstraints().setX(newX); } /** * set new y position constraint. * @param newY new y constaint. */ public void setConstraintY(final SizeValue newY) { layoutPart.getBoxConstraints().setY(newY); } /** * set new width constraint. * @param newWidth new width constraint. */ public void setConstraintWidth(final SizeValue newWidth) { layoutPart.getBoxConstraints().setWidth(newWidth); } /** * set new height constraint. * @param newHeight new height constraint. */ public void setConstraintHeight(final SizeValue newHeight) { layoutPart.getBoxConstraints().setHeight(newHeight); } /** * get current width constraint. * @return current width constraint */ public SizeValue getConstraintWidth() { return layoutPart.getBoxConstraints().getWidth(); } /** * get current height constraint. * @return current height constraint. */ public SizeValue getConstraintHeight() { return layoutPart.getBoxConstraints().getHeight(); } /** * set new horizontal align. * @param newHorizontalAlign new horizontal align. */ public void setConstraintHorizontalAlign(final HorizontalAlign newHorizontalAlign) { layoutPart.getBoxConstraints().setHorizontalAlign(newHorizontalAlign); } /** * set new vertical align. * @param newVerticalAlign new vertical align. */ public void setConstraintVerticalAlign(final VerticalAlign newVerticalAlign) { layoutPart.getBoxConstraints().setVerticalAlign(newVerticalAlign); } /** * get current horizontal align. * @return current horizontal align. */ public HorizontalAlign getConstraintHorizontalAlign() { return layoutPart.getBoxConstraints().getHorizontalAlign(); } /** * get current vertical align. * @return current vertical align. */ public VerticalAlign getConstraintVerticalAlign() { return layoutPart.getBoxConstraints().getVerticalAlign(); } /** * register an effect for this element. * @param theId the effect id * @param e the effect */ public void registerEffect( final EffectEventId theId, final Effect e) { log.fine("[" + this.getId() + "] register: " + theId.toString() + "(" + e.getStateString() + ")"); effectManager.registerEffect(theId, e); } /** * on start screen event. * @param effectEventId the effect event id to start * @param effectEndNotiy the EffectEndNotify event we should activate */ public void startEffect(final EffectEventId effectEventId, final EndNotify effectEndNotiy) { if (effectEventId == EffectEventId.onStartScreen) { done = false; } if (effectEventId == EffectEventId.onEndScreen) { done = true; } // whenever the effect ends we forward to this event // that checks first, if all child elements are finished // and when yes forwards to the actual effectEndNotify event. // this way we ensure that all child finished the effects // before forwarding this to the real event handler. // little bit tricky though :/ LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotiy); // start the effect for ourself effectManager.startEffect(effectEventId, this, time, forwardToSelf); // notify all child elements of the start effect for (Element w : getElements()) { w.startEffect(effectEventId, forwardToSelf); } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(true); } } // just in case there was no effect activated, we'll check here, if we're already done forwardToSelf.perform(); } public void startEffect(final EffectEventId effectEventId) { startEffect(effectEventId, null); } /** * stop the given effect. * @param effectEventId effect event id to stop */ public void stopEffect(final EffectEventId effectEventId) { effectManager.stopEffect(effectEventId); // notify all child elements of the start effect for (Element w : getElements()) { w.stopEffect(effectEventId); } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(false); } } } /** * check if a certain effect is still active. travels down to child elements. * @param effectEventId the effect type id to check * @return true, if the effect has ended and false otherwise */ public boolean isEffectActive(final EffectEventId effectEventId) { for (Element w : getElements()) { if (w.isEffectActive(effectEventId)) { return true; } } return effectManager.isActive(effectEventId); } /** * enable this element. */ public void enable() { enabled = true; } /** * disable this element. */ public void disable() { enabled = false; } /** * is this element enabled? * @return true, if enabled and false otherwise. */ public boolean isEnabled() { return enabled; } /** * show this element. */ public void show() { // don't show if show is still in progress if (isEffectActive(EffectEventId.onShow)) { return; } // stop any onHide effects when a new onShow effect is about to be started if (isEffectActive(EffectEventId.onHide)) { resetSingleEffect(EffectEventId.onHide); } // show internalShow(); startEffect(EffectEventId.onShow, new EndNotify() { public void perform() { } }); } public void setVisible(final boolean visibleParam) { if (visibleParam) { show(); } else { hide(); } } private void internalShow() { visible = true; for (Element element : elements) { element.internalShow(); } } /** * hide this element. */ public void hide() { // don't hide if not visible if (!isVisible()) { return; } // don't hide if hide is still in progress if (isEffectActive(EffectEventId.onHide)) { return; } // stop any onShow effects when a new onHide effect is about to be started if (isEffectActive(EffectEventId.onShow)) { resetSingleEffect(EffectEventId.onShow); } // start effect and shizzle startEffect(EffectEventId.onHide, new EndNotify() { public void perform() { focusHandler.lostKeyboardFocus(Element.this); focusHandler.lostMouseFocus(Element.this); resetEffects(); internalHide(); } }); } public void showWithoutEffects() { internalShow(); } public void hideWithoutEffect() { // don't hide if not visible if (!isVisible()) { return; } focusHandler.lostKeyboardFocus(Element.this); focusHandler.lostMouseFocus(Element.this); resetEffects(); internalHide(); } private void internalHide() { visible = false; for (Element element : elements) { element.internalHide(); } } /** * check if this element is visible. * @return true, if this element is visible and false otherwise. */ public boolean isVisible() { return visible; } /** * set a new Falloff. * @param newFalloff new Falloff */ public void setHotSpotFalloff(final Falloff newFalloff) { effectManager.setFalloff(newFalloff); } public Falloff getFalloff() { return effectManager.getFalloff(); } /** * Checks if this element can handle mouse events. * @return true can handle mouse events, false can't handle them */ boolean canHandleMouseEvents() { if (isEffectActive(EffectEventId.onStartScreen)) { return false; } if (isEffectActive(EffectEventId.onEndScreen)) { return false; } if (!visible) { return false; } if (done) { return false; } if (!visibleToMouseEvents) { return false; } if (!focusHandler.canProcessMouseEvents(this)) { return false; } return true; } /** * This should check of the mouse event is inside the current element and if it is * forward the event to it's child. The purpose of this is to build a list of all * elements from front to back that are available for a certain mouse position. * @param mouseEvent MouseInputEvent * @param eventTime time this event occured in ms * @param mouseOverHandler MouseOverHandler to fill */ public void buildMouseOverElements( final MouseInputEvent mouseEvent, final long eventTime, final MouseOverHandler mouseOverHandler) { if (!canHandleMouseEvents()) { return; } if (isInside(mouseEvent)) { mouseOverHandler.addElement(this); for (Element w : getElements()) { w.buildMouseOverElements(mouseEvent, eventTime, mouseOverHandler); } } } /** * MouseEvent. * @param mouseEvent mouse event * @param eventTime event time */ public boolean mouseEvent(final MouseInputEvent mouseEvent, final long eventTime) { for (Element w : getElements()) { if (w.mouseEvent(mouseEvent, eventTime)) { return true; } } if (!canHandleMouseEvents()) { return false; } effectManager.handleHover(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); boolean mouseInside = isInside(mouseEvent); if (interaction.isOnClickRepeat()) { if (mouseInside && isMouseDown() && mouseEvent.isLeftButton()) { long deltaTime = eventTime - mouseDownTime; if (deltaTime > REPEATED_CLICK_START_TIME) { long pastTime = deltaTime - REPEATED_CLICK_START_TIME; long repeatTime = pastTime - lastRepeatStartTime; if (repeatTime > REPEATED_CLICK_TIME) { lastRepeatStartTime = pastTime; if (onClick(mouseEvent)) { return true; } } } } } if (mouseInside && !isMouseDown()) { if (mouseEvent.isLeftButton()) { setMouseDown(true, eventTime); if (focusable) { focusHandler.requestExclusiveMouseFocus(this); focusHandler.setKeyFocus(this); } return onClick(mouseEvent); } } else if (!mouseEvent.isLeftButton() && isMouseDown()) { setMouseDown(false, eventTime); effectManager.stopEffect(EffectEventId.onClick); focusHandler.lostMouseFocus(this); if (mouseInside) { onRelease(); } } if (isMouseDown()) { onClickMouseMove(mouseEvent); } return false; } /** * Handle the MouseOverEvent. Must not call child elements. This is handled by caller. * @param mouseEvent mouse event * @param eventTime event time * @return true the mouse event has been eated and false when the mouse event can be processed further down */ public boolean mouseOverEvent(final MouseInputEvent mouseEvent, final long eventTime) { boolean eatMouseEvent = false; if (interaction.onMouseOver(this, mouseEvent)) { eatMouseEvent = true; } return eatMouseEvent; } /** * checks to see if the given mouse position is inside of this element. * @param inputEvent MouseInputEvent * @return true when inside, false otherwise */ private boolean isInside(final MouseInputEvent inputEvent) { return isMouseInsideElement(inputEvent.getMouseX(), inputEvent.getMouseY()); } public boolean isMouseInsideElement(final int mouseX, final int mouseY) { if (parentClipArea) { // System.out.println("x: " + mouseX + ", y: " + mouseY + " [" + this.id + "] " + getX() + ", " + getY() + ", " + (getX() + getWidth()) + ", " + (getY() + getHeight()) + " [" + parentWithClipChildred.getId() + "] " + parentWithClipChildred.getX() + ", " + parentWithClipChildred.getY() + ", " + (parentWithClipChildred.getX() + parentWithClipChildred.getWidth()) + ", " + (parentWithClipChildred.getY() + parentWithClipChildred.getHeight())); // must be inside the parent to continue if (mouseX >= parentClipX && mouseX <= (parentClipX + parentClipWidth) && mouseY > (parentClipY) && mouseY < (parentClipY + parentClipHeight)) { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } else { return false; } } else { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } } /** * on click method. * @param inputEvent event */ public boolean onClick(final MouseInputEvent inputEvent) { effectManager.startEffect(EffectEventId.onClick, this, time, null); lastMouseX = inputEvent.getMouseX(); lastMouseY = inputEvent.getMouseY(); return interaction.onClick(inputEvent); } public void onClick() { effectManager.startEffect(EffectEventId.onClick, this, time, null); interaction.onClick(); } public void onRelease() { interaction.onRelease(); } /** * on click mouse move method. * @param inputEvent MouseInputEvent */ private void onClickMouseMove(final MouseInputEvent inputEvent) { if (lastMouseX == inputEvent.getMouseX() && lastMouseY == inputEvent.getMouseY()) { return; } lastMouseX = inputEvent.getMouseX(); lastMouseY = inputEvent.getMouseY(); interaction.onClickMouseMoved(inputEvent); } /** * set on click method for the given screen. * @param methodInvoker the method to invoke * @param useRepeat repeat on click (true) or single event (false) */ public void setOnClickMethod(final MethodInvoker methodInvoker, final boolean useRepeat) { interaction.setOnClickMethod(methodInvoker, useRepeat); } public void setOnReleaseMethod(final MethodInvoker onReleaseMethod) { interaction.setOnReleaseMethod(onReleaseMethod); } /** * Set on click mouse move method. * @param methodInvoker the method to invoke */ public void setOnClickMouseMoveMethod(final MethodInvoker methodInvoker) { interaction.setOnClickMouseMoved(methodInvoker); } /** * set mouse down. * @param newMouseDown new state of mouse button. * @param eventTime the time in ms the event occured */ private void setMouseDown(final boolean newMouseDown, final long eventTime) { this.mouseDownTime = eventTime; this.lastRepeatStartTime = 0; this.mouseDown = newMouseDown; } /** * is mouse down. * @return mouse down state. */ private boolean isMouseDown() { return mouseDown; } /** * find an element by name. * * @param name the name of the element (id) * @return the element or null */ public Element findElementByName(final String name) { if (id != null && id.equals(name)) { return this; } for (Element e : elements) { Element found = e.findElementByName(name); if (found != null) { return found; } } return null; } /** * set a new alternate key. * @param newAlternateKey new alternate key to use */ public void setOnClickAlternateKey(final String newAlternateKey) { interaction.setAlternateKey(newAlternateKey); } /** * set alternate key. * @param alternateKey new alternate key */ public void setAlternateKey(final String alternateKey) { effectManager.setAlternateKey(alternateKey); for (Element e : elements) { e.setAlternateKey(alternateKey); } } /** * get the effect manager. * @return the EffectManager */ public EffectManager getEffectManager() { return effectManager; } /** * Set a New EffectManager. * @param effectManagerParam new Effectmanager */ public void setEffectManager(final EffectManager effectManagerParam) { effectManager = effectManagerParam; } /** * On start screen event. * @param newScreen screen */ public void onStartScreen(final Screen newScreen) { screen = newScreen; for (Element e : elements) { e.onStartScreen(newScreen); } if (focusable) { focusHandler.addElement(this); } if (attachedInputControl != null) { attachedInputControl.onStartScreen(screen); } } /** * * @param <T> the ElementRenderer type * @param requestedRendererClass the special ElementRenderer type to check for * @return the ElementRenderer that matches the class */ public < T extends ElementRenderer > T getRenderer(final Class < T > requestedRendererClass) { for (ElementRenderer renderer : elementRenderer) { if (requestedRendererClass.isInstance(renderer)) { return requestedRendererClass.cast(renderer); } } return null; } /** * Set visible to mouse flag. * @param newVisibleToMouseEvents true or false */ public void setVisibleToMouseEvents(final boolean newVisibleToMouseEvents) { this.visibleToMouseEvents = newVisibleToMouseEvents; } /** * keyboard event. * @param inputEvent keyboard event */ public void keyEvent(final KeyboardInputEvent inputEvent) { if (attachedInputControl != null) { attachedInputControl.keyEvent(inputEvent); } } /** * Set clip children. * @param clipChildrenParam clip children flag */ public void setClipChildren(final boolean clipChildrenParam) { this.clipChildren = clipChildrenParam; } /** * Is clip children enabled? * @return clip children */ public boolean isClipChildren() { return this.clipChildren; } /** * Set the focus to this element. */ public void setFocus() { if (nifty != null && nifty.getCurrentScreen() != null) { if (focusable) { focusHandler.setKeyFocus(this); } } } /** * attach an input control to this element. * @param newInputControl input control */ public void attachInputControl(final NiftyInputControl newInputControl) { attachedInputControl = newInputControl; } /** * attach popup. * @param screenController screencontroller */ public void attachPopup(final ScreenController screenController) { log.fine("attachPopup(" + screenController + ") to element [" + id + "]"); attach(interaction.getOnClickMethod(), screenController); attach(interaction.getOnClickMouseMoveMethod(), screenController); attach(interaction.getOnReleaseMethod(), screenController); } /** * attach method. * @param method method * @param screenController method controller */ private void attach(final MethodInvoker method, final ScreenController screenController) { method.setFirst(screenController); for (Element e : elements) { e.attachPopup(screenController); } } /** * LocalEndNotify helper class. * @author void */ public class LocalEndNotify implements EndNotify { /** * event id. */ private EffectEventId effectEventId; /** * end notify. */ private EndNotify effectEndNotiy; /** * create it. * @param effectEventIdParam event id * @param effectEndNotiyParam end notify */ public LocalEndNotify(final EffectEventId effectEventIdParam, final EndNotify effectEndNotiyParam) { effectEventId = effectEventIdParam; effectEndNotiy = effectEndNotiyParam; } /** * perform. */ public void perform() { // notify parent if: // a) the effect is done for ourself // b) the effect is done for all of our children if (!isEffectActive(effectEventId)) { // all fine. we can notify the actual event handler if (effectEndNotiy != null) { effectEndNotiy.perform(); } } } } /** * set id. * @param newId new id */ public void setId(final String newId) { this.id = newId; } /** * get element type. * @return element type */ public ElementType getElementType() { return elementType; } /** * get element renderer. * @return element renderer array */ public ElementRenderer[] getElementRenderer() { return elementRenderer; } /** * set focusable flag. * @param newFocusable focusable flag */ public void setFocusable(final boolean newFocusable) { this.focusable = newFocusable; for (Element e : elements) { e.setFocusable(newFocusable); } } /** * @return the attachedInputControl */ public NiftyInputControl getAttachedInputControl() { return attachedInputControl; } /** * remove this and all children from the focushandler. */ public void removeFromFocusHandler() { if (screen != null) { if (screen.getFocusHandler() != null) { screen.getFocusHandler().remove(this); for (Element element : elements) { element.removeFromFocusHandler(); } } } } /** * set a new style. * @param newStyle new style to set */ public void setStyle(final String newStyle) { removeStyle(elementType.getAttributes().get("style")); elementType.getAttributes().set("style", newStyle); elementType.applyStyles(nifty.getDefaultStyleResolver()); elementType.applyAttributes(this, elementType.getAttributes(), nifty.getRenderEngine()); elementType.applyEffects(nifty, screen, this); elementType.applyInteract(nifty, screen, this); // log.info("after setStyle [" + newStyle + "]\n" + elementType.output(0)); } void removeStyle(final String style) { elementType.getAttributes().removeWithTag(style); // log.info("after removeStyle [" + style + "]\n" + elementType.output(0)); } /** * add additional input handler to this element or childs of the elements. * @param handler additiona handler */ public void addInputHandler(final KeyInputHandler handler) { if (attachedInputControl != null) { attachedInputControl.addInputHandler(handler); } for (Element element : elements) { element.addInputHandler(handler); } } public < T extends Controller > T findControl(final String elementName, final Class < T > requestedControlClass) { Element element = findElementByName(elementName); if (element == null) { return null; } return element.getControl(requestedControlClass); } /** * Get Control from element. * @param <T> Type * @param requestedControlClass requested class * @return controller or null */ public < T extends Controller > T getControl(final Class < T > requestedControlClass) { if (attachedInputControl != null) { T t = attachedInputControl.getControl(requestedControlClass); if (t != null) { return t; } } else { for (Element element : elements) { T t = element.getControl(requestedControlClass); if (t != null) { return t; } } } return null; } /** * is focusable? * @return focusable */ public boolean isFocusable() { return focusable; } /** * Set onMouseOverMethod. * @param onMouseOverMethod new on mouse over method */ public void setOnMouseOverMethod(final MethodInvoker onMouseOverMethod) { this.interaction.setOnMouseOver(onMouseOverMethod); } /** * Get LayoutPart. * @return LayoutPart */ public LayoutPart getLayoutPart() { return layoutPart; } /** * Get Element Interaction. * @return current ElementInteraction */ public ElementInteraction getInteraction() { return interaction; } /** * Set Element Interaction. * @param elementInteractionParam ElementInteraction */ public void setInteraction(final ElementInteraction elementInteractionParam) { interaction = elementInteractionParam; } /** * Is this element visible to mouse events. * @return true visible and false not visible */ public boolean isVisibleToMouseEvents() { return visibleToMouseEvents; } public void setPaddingLeft(final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingLeft(paddingValue); } public void setPaddingRight(final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingRight(paddingValue); } public void setPaddingTop(final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingTop(paddingValue); } public void setPaddingBottom(final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingBottom(paddingValue); } public String toString() { return id + " (" + super.toString() + ")"; } public boolean isStarted() { return isEffectActive(EffectEventId.onStartScreen); } }
package ikube; import ikube.cluster.IClusterManager; import ikube.database.IDataBase; import ikube.listener.ListenerManager; import ikube.listener.Scheduler; import ikube.model.IndexContext; import ikube.model.Server; import ikube.model.faq.Attachment; import ikube.model.faq.Faq; import ikube.toolkit.ApplicationContextManager; import ikube.toolkit.FileUtilities; import ikube.toolkit.PerformanceTester; import ikube.toolkit.data.DataGeneratorFour; import ikube.toolkit.data.DataGeneratorMedical; import ikube.toolkit.data.IDataGenerator; import java.io.File; import java.io.InputStream; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.springframework.context.ApplicationContext; import com.hazelcast.core.Hazelcast; /** * This is the base class for tests that start up the application context. Generally we don't want to start the context for several reasons * not the least of which is that it is time consuming, but in some cases we do. Most tests should be mocked using Mockito and Jmockit. * * This class will start the {@link ApplicationContextManager} and initialize the context. This means that the data sources will be started, * and injected into Jndi, the aspects will be woven in, Hazelcast will be started, ultimately almost like starting a server, which is nice * for integration tests, but not so nice for unit tests that we want to run in a fraction of a second. This startup process can take up to * 30 seconds, clearly not nice for a unit test. * * @author Michael Couck * @since 21.11.10 * @version 01.00 */ public abstract class BaseTest extends ATest { private static final Logger LOGGER = Logger.getLogger(BaseTest.class); protected static ApplicationContext APPLICATION_CONTEXT; protected static EntityManagerFactory ENTITY_MANAGER_FACTORY; protected static boolean INITIALIZED = Boolean.FALSE; @BeforeClass public static void beforeClass() { shutdownSchedules(); if (INITIALIZED) { return; } INITIALIZED = Boolean.TRUE; // Close down all the instances in the environment because we will be conflicting // with each other. Generally there will be none, but the Tomcat shutdown command // does not always work APPLICATION_CONTEXT = ApplicationContextManager.getApplicationContext(); IClusterManager clusterManager = ApplicationContextManager.getBean(IClusterManager.class); Server server = clusterManager.getServer(); Hazelcast.getTopic(IConstants.SHUTDOWN_TOPIC).publish(server); try { // We'll sleep for a while to give the other servers a time to shut down Thread.sleep(30000); final int iterations = 0; final IDataBase dataBase = ApplicationContextManager.getBean(IDataBase.class); PerformanceTester.execute(new PerformanceTester.APerform() { @Override public void execute() throws Exception { Class<?>[] classes = new Class[] { Faq.class, Attachment.class }; IDataGenerator dataGenerator = new DataGeneratorFour(dataBase, iterations, classes); dataGenerator.before(); dataGenerator.generate(); File file = FileUtilities.findFileRecursively(new File("."), "doctors.xml"); InputStream inputStream = file.toURI().toURL().openStream(); DataGeneratorMedical dataGeneratorMedical = new DataGeneratorMedical(dataBase); dataGeneratorMedical.setInputStream(inputStream); dataGenerator.before(); dataGenerator.generate(); } }, "Data generator insertion : ", iterations); } catch (Exception e) { LOGGER.error("Exception inserting the data for the base test : ", e); } shutdownSchedules(); } @AfterClass public static void afterClass() { shutdownSchedules(); } protected static final void shutdownSchedules() { Scheduler.shutdown(); ListenerManager.removeListeners(); } protected IndexContext<?> indexContext; public BaseTest(Class<?> subClass) { super(subClass); indexContext = ApplicationContextManager.getBean("indexContext"); } }
package de.onyxbits.raccoon.gui; import java.util.List; import java.util.Locale; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import com.akdeniz.googleplaycrawler.GooglePlayAPI; import com.akdeniz.googleplaycrawler.GooglePlayException; import de.onyxbits.raccoon.App; import de.onyxbits.raccoon.io.Archive; /** * A worker for initializing a new archive. This class will log into the * provided account, get a new android id and save the whole thing to the * credentials file. * * @author patrick * */ public class InitWorker extends SwingWorker<String, String> { private Archive archive; private InitView initView; /** * * @param a * archive. It must have a valid username/password in it, but does * not need to have anything on disk, yet. It will get an aid filled * in and the credentials will also be written to file. */ public InitWorker(Archive a, InitView callback) { this.archive = a; this.initView = callback; } protected void process(List<String> chunks) { initView.doInProgress(); } @Override protected String doInBackground() throws Exception { publish(""); // Register the account with GPlay. GooglePlayAPI service = App.createConnection(archive); service.setLocalization(Locale.getDefault().getCountry()); if ("".equals(archive.getAndroidId())) { service.checkin(); service.login(); service.uploadDeviceConfig(); } else { service.login(); } // Persist credentials through a separate object... Archive a = new Archive(archive.getRoot()); a.setUserId(archive.getUserId()); a.setPassword(archive.getPassword()); a.setAndroidId(service.getAndroidID()); a.saveCredentials(); // ... and transport back the new aid, so we only modify the submitted // archive on the UI thread. return service.getAndroidID(); } @Override protected void done() { try { archive.setAndroidId(get()); initView.doRemount(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { if (e.getCause() instanceof GooglePlayException) { initView.doErrorMessage(); } // e.printStackTrace(); } } }
package org.apache.lucene.search.exposed.facet; import org.apache.lucene.search.exposed.TermProvider; import java.io.IOException; import java.util.List; public class FacetMapFactory { public enum IMPL {stable, pass2, pass1long, pass1packed} // stable is well-tested, pass2 is deprecated and pass1long is experimental public static IMPL defaultImpl = IMPL.pass2; public static FacetMap createMap(int docCount, List<TermProvider> providers) throws IOException { return createMap(docCount, providers, defaultImpl); } public static FacetMap createMap( int docCount, List<TermProvider> providers, IMPL impl) throws IOException { switch (impl) { case stable: return FacetMapTripleFactory.createMap(docCount, providers); case pass2: return FacetMapDualFactory.createMap(docCount, providers); case pass1long: return FacetMapSingleLongFactory.createMap(docCount, providers); case pass1packed: return FacetMapSinglePackedFactory.createMap(docCount, providers); default: throw new UnsupportedOperationException( "The implementation '" + impl + "' is unknown"); } } }
package de.skuzzle.inject.async; import static com.google.common.base.Preconditions.checkArgument; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Module; import de.skuzzle.inject.async.annotation.Async; import de.skuzzle.inject.async.annotation.Scheduled; import de.skuzzle.inject.async.internal.AsyncModule; import de.skuzzle.inject.async.internal.context.ContextModule; import de.skuzzle.inject.async.internal.runnables.RunnablesModule; /** * Entry point for enabling asynchronous method support within your guice application. * * <pre> * public class MyModule extends AbstractModule { * * &#64;Override * public void configure() { * GuiceAsync.enableFor(binder()); * // ... * } * } * </pre> * * Please see the JavaDoc of the {@link Async} and {@link Scheduled} annotation for * further usage information. * * @author Simon Taddiken * @see Async * @see Scheduled */ public final class GuiceAsync { private GuiceAsync() { // hidden constructor } /** * Enable support for the {@link Async} annotation in classes that are used with the * injector that will be created from the given {@link Binder}. * * @param binder The binder to register with. */ public static void enableFor(Binder binder) { checkArgument(binder != null, "binder must not be null"); binder.install(createModule()); } /** * Creates a module that can be used to enable asynchronous method support. * * @return A module that exposes all bindings needed for asynchronous method support. * @since 0.2.0 */ public static Module createModule() { final GuiceAsync principal = new GuiceAsync(); return new AbstractModule() { @Override protected void configure() { install(new AsyncModule(principal)); install(new ContextModule(principal)); install(new RunnablesModule(principal)); } }; } }
package de.tblsoft.solr.pipeline; import de.tblsoft.solr.util.IOUtils; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; public class XmlReader extends AbstractReader { @Override public void read() { try { String filename = getProperty("filename", null); String absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), filename); List<String> fileList = IOUtils.getFiles(absoluteFilename); XMLReader myReader = XMLReaderFactory.createXMLReader(); ContentHandler mySerializer = new PipelineSaxContentHandler(executer); boolean firstFile = true; TransformerHandler lastHandler = null; List<String> transformationFiles = getPropertyAsList("transformations", new ArrayList<>()); for (String file : transformationFiles) { TransformerHandler currentHandler = getTransformerHandler(file); if (firstFile) { firstFile = false; myReader.setContentHandler(currentHandler); lastHandler = currentHandler; continue; } lastHandler.setResult(new SAXResult(currentHandler)); lastHandler = currentHandler; } if (lastHandler == null) { myReader.setContentHandler(mySerializer); } else { lastHandler.setResult(new SAXResult(mySerializer)); } for (String sourceFile : fileList) { InputStream in = IOUtils.getInputStream(sourceFile); myReader.parse(new InputSource(in)); in.close(); } } catch(Exception e){ throw new RuntimeException(e); } } TransformerHandler getTransformerHandler(String fileName) throws TransformerConfigurationException { fileName = IOUtils.getAbsoluteFile(getBaseDir(),fileName); if(fileName.endsWith(".stx")) { SAXTransformerFactory stxFactory = new net.sf.joost.trax.TransformerFactoryImpl(); return stxFactory.newTransformerHandler(new StreamSource(fileName)); } if(fileName.endsWith(".xsl")) { SAXTransformerFactory xslFactory = (SAXTransformerFactory) TransformerFactory.newInstance();; return xslFactory.newTransformerHandler(new StreamSource(fileName)); } throw new IllegalArgumentException("Only the filetypes xsl and stx are supported."); } }
package editor.gui.settings; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.StringJoiner; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import editor.collection.deck.Category; import editor.database.FormatConstraints; import editor.database.attributes.CardAttribute; import editor.database.card.Card; import editor.database.version.DatabaseVersion; import editor.database.version.UpdateFrequency; import editor.gui.MainFrame; import editor.gui.display.CardTable; import editor.gui.display.CategoryList; import editor.gui.editor.CalculateHandPanel; import editor.gui.editor.CategoryEditorPanel; import editor.gui.generic.ScrollablePanel; import editor.gui.generic.VerticalButtonList; import editor.util.UnicodeSymbols; /** * This class is a dialog that allows the user to change various properties about * the program. * * @author Alec Roelke */ public class SettingsDialog extends JDialog { /** * Settings structure containing global settings. */ private static Settings settings; /** * List of the latest warnings from the last time the inventory was loaded. */ private static List<String> inventoryWarnings; /** * Location to store settings and default location to store other data. */ public static final Path EDITOR_HOME = Path.of(System.getProperty("user.home"), ".mtgworkstation"); /** * Pattern to match when parsing an ARGB color from a string to a @link{java.awt.Color} */ public static final Pattern COLOR_PATTERN = Pattern.compile("^#([0-9a-fA-F]{2})?([0-9a-fA-F]{6})$"); /** * Number of cards in a playset. */ public static final int PLAYSET_SIZE = 4; /** * File containing serialized settings. */ public static final Path PROPERTIES_FILE = EDITOR_HOME.resolve("settings.json"); /** * List of possible sites to download card images from. */ public static final List<String> IMAGE_SOURCES = List.of("Scryfall", "Gatherer"); /** * List of possible choices for mana value during analysis for cards that have * more than one. */ public static final List<String> MANA_VALUE_OPTIONS = List.of("Minimum", "Maximum", "Average", "Real"); /** * Create the preview panel for a color chooser that customizes the stripe color * of a #CardTable. * * @param chooser #JColorChooser to create the new preview panel for */ private static void createStripeChooserPreview(JColorChooser chooser) { Box preview = new Box(BoxLayout.Y_AXIS); TableModel model = new AbstractTableModel() { @Override public int getColumnCount() { return 4; } @Override public int getRowCount() { return 4; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return "Sample Text"; } }; CardTable table = new CardTable(model); table.setStripeColor(chooser.getColor()); preview.add(table); chooser.getSelectionModel().addChangeListener((e) -> table.setStripeColor(chooser.getColor())); chooser.setPreviewPanel(preview); } /** * If the given file is contained the current directory, make it a relative file to * the current working directory. If it is the current working directory, make it * "." Otherwise, keep it what it is. * * @param f #File to relativize * @return relativized version of the given file. */ private static File relativize(File f) { Path p = new File(".").getAbsoluteFile().getParentFile().toPath(); Path fp = f.getAbsoluteFile().toPath(); if (fp.startsWith(p)) { fp = p.relativize(fp); if (fp.toString().isEmpty()) f = new File("."); else f = fp.toFile(); } return f; } /** * Add a new preset category. * * @param category specification of the preset category to add */ public static void addPresetCategory(Category category) { settings = new SettingsBuilder(settings).addPresetCategory(category).build(); } /** * Load global settings from the settings file. This does not affect card tags. * * @throws IOException if an error occurred during loading */ public static void load() throws IOException { if (Files.exists(PROPERTIES_FILE)) settings = MainFrame.SERIALIZER.fromJson(String.join("\n", Files.readAllLines(PROPERTIES_FILE)), Settings.class); else resetDefaultSettings(); } /** * Set program settings back to their default values. This does not change card tags. */ public static void resetDefaultSettings() { settings = new SettingsBuilder().defaults().build(); } /** * Save preferences to file whose name is specified by the value of {@link #PROPERTIES_FILE}. * Also save tags to the separate tags file. * * @throws IOException if an exception occurred during saving. */ public static void save() throws IOException { if (!Card.tags.isEmpty()) { Files.createDirectories(Path.of(settings.inventory().tags()).getParent()); Files.writeString(Path.of(settings.inventory().tags()), MainFrame.SERIALIZER.toJson(Card.tags.entrySet().stream().collect(Collectors.toMap((e) -> e.getKey().multiverseid().get(0), Map.Entry::getValue)))); } else Files.deleteIfExists(Path.of(settings.inventory().tags())); Files.writeString(PROPERTIES_FILE, MainFrame.SERIALIZER.toJson(settings)); } /** * Update the recently-edited files. * * @param files list of recently-edited files */ public static void setRecents(List<String> files) { settings = new SettingsBuilder(settings).recentsFiles(files).build(); } /** * Update the directory to start the file chooser in. * * @param dir starting directory for file chooser */ public static void setStartingDir(String dir) { settings = new SettingsBuilder(settings).cwd(dir).build(); } /** * @return The global settings structure. * @see Settings */ public static Settings settings() { return settings; } /** * Set the version of the inventory to know when it is out of date. * * @param version new version of the inventory */ public static void setInventoryVersion(DatabaseVersion version) { settings = new SettingsBuilder(settings).inventoryVersion(version).build(); } /** * Set whether or not to show warnings after finishing loading the inventory. * * @param warn whether or not to show warnings */ public static void setShowInventoryWarnings(boolean warn) { settings = new SettingsBuilder(settings).inventoryWarn(warn).build(); } public static void setInventoryWarnings(List<String> warnings) { inventoryWarnings = new ArrayList<>(warnings); } /** List of preset categories. */ private CategoryList categoriesList; /** Check boxes indicating which columns to show in editor tables. */ private Map<CardAttribute, JCheckBox> editorColumnCheckBoxes; /** Color chooser for the color of editor tables' alternate stripes. */ private JColorChooser editorStripeColor; /** Spinner allowing setting the number of rows to display in whitelists/blacklists in the category editor. */ private JSpinner explicitsSpinner; /** Color chooser for the background of card images in the hand tab. */ private JColorChooser handBGColor; /** Check boxes indicating which columns to show in the inventory table. */ private Map<CardAttribute, JCheckBox> inventoryColumnCheckBoxes; /** Text field controlling the directory to store the inventory in once it is downloaded. */ private JTextField inventoryDirField; /** Text field controlling the name of the file to be downloaded. */ private JTextField inventoryFileField; /** Text field controlling the web site that the inventory should be downloaded from. */ private JTextField inventorySiteField; /** Color chooser for the color of alternate inventory table stripes. */ private JColorChooser inventoryStripeColor; /** Button indicating the rounding mode for the expected counts tab in the editor. */ private List<JRadioButton> modeButtons; /** MainFrame showing the dialog. */ private MainFrame parent; /** Spinner for the number of recent files to save. */ private JSpinner recentSpinner; /** Spinner allowing setting the maximum number of rows for category panels. */ private JSpinner rowsSpinner; /** Color chooser for the background of the card scan tab. */ private JColorChooser scanBGChooser; /** Text field containing the directory to look for card scans in. */ private JTextField scansDirField; /** Number of cards to draw in the starting hand. */ private JSpinner startingSizeSpinner; /** Check box indicating whether or not warnings after loading cards should be suppressed. */ private JCheckBox suppressCheckBox; /** Combo box indicating how often to download updates. */ private JComboBox<UpdateFrequency> updateBox; private JCheckBox cmdrCheck; /** Radio button indicting to check only the main deck by default for a commander. */ private JRadioButton cmdrMainDeck; /** Radio button indicating to check all lists by default for a commander. */ private JRadioButton cmdrAllLists; /** Radio button indicating to check a specific list, if it exists, for a commander by default. */ private JRadioButton cmdrList; /** Default name of the list to look in if checking only a single one or commander. */ private JTextField cmdrListName; private JCheckBox sideCheck; /** Text field specifying the default name of the list to use as sideboard if present. */ private JTextField sideField; /** Combo box showing possible sites to download cards from. */ private JComboBox<String> imgSourceBox; /** Check box indicating whether or not to limit the number of cached images to save. */ private JCheckBox limitImageBox; /** Spinner containing the number of cached image to allow. */ private JSpinner limitImageSpinner; /** Combo box showing possible ways to analyze mana value. */ private JComboBox<String> manaValueBox; /** Check boxes indicating which layouts to count as lands if their back faces are lands. */ private List<JCheckBox> landsCheckBoxes; /** Sections for dividing analysis bars. */ private String[] sections; /** Color choosers for changing the colors of the bar sections. */ private Map<String, JColorChooser> sectionChoosers; /** * Create a new SettingsDialog. * * @param owner parent of the dialog */ public SettingsDialog(MainFrame owner) { super(owner, "Preferences", Dialog.ModalityType.APPLICATION_MODAL); setResizable(false); parent = owner; // Tree DefaultMutableTreeNode root = new DefaultMutableTreeNode("Preferences"); DefaultMutableTreeNode inventoryNode = new DefaultMutableTreeNode("Inventory"); root.add(inventoryNode); DefaultMutableTreeNode inventoryAppearanceNode = new DefaultMutableTreeNode("Appearance"); inventoryNode.add(inventoryAppearanceNode); DefaultMutableTreeNode editorNode = new DefaultMutableTreeNode("Editor"); DefaultMutableTreeNode editorCategoriesNode = new DefaultMutableTreeNode("Preset Categories"); editorNode.add(editorCategoriesNode); DefaultMutableTreeNode editorAppearanceNode = new DefaultMutableTreeNode("Appearance"); editorNode.add(editorAppearanceNode); DefaultMutableTreeNode handAppearanceNode = new DefaultMutableTreeNode("Sample Hand"); editorNode.add(handAppearanceNode); DefaultMutableTreeNode formatsNode = new DefaultMutableTreeNode("Formats"); editorNode.add(formatsNode); DefaultMutableTreeNode manaAnalysisNode = new DefaultMutableTreeNode("Mana Analysis"); editorNode.add(manaAnalysisNode); root.add(editorNode); // Settings panels JPanel settingsPanel = new JPanel(); settingsPanel.setLayout(new CardLayout()); add(settingsPanel, BorderLayout.CENTER); // Inventory paths Box inventoryPanel = new Box(BoxLayout.Y_AXIS); inventoryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); settingsPanel.add(inventoryPanel, new TreePath(inventoryNode.getPath()).toString()); // Inventory site Box inventorySitePanel = new Box(BoxLayout.X_AXIS); inventorySitePanel.add(new JLabel("Inventory Site:")); JLabel siteStarLabel = new JLabel("*"); siteStarLabel.setForeground(Color.RED); inventorySitePanel.add(siteStarLabel); inventorySitePanel.add(Box.createHorizontalStrut(5)); inventorySiteField = new JTextField(15); inventorySitePanel.add(inventorySiteField); inventorySitePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, inventorySitePanel.getPreferredSize().height)); inventoryPanel.add(inventorySitePanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Inventory file name Box inventoryFilePanel = new Box(BoxLayout.X_AXIS); inventoryFilePanel.add(new JLabel("Inventory File:")); JLabel fileStarLabel = new JLabel("*"); fileStarLabel.setForeground(Color.RED); inventoryFilePanel.add(fileStarLabel); inventoryFilePanel.add(Box.createHorizontalStrut(5)); inventoryFileField = new JTextField(10); inventoryFilePanel.add(inventoryFileField); inventoryFilePanel.add(Box.createHorizontalStrut(5)); JLabel currentVersionLabel = new JLabel(); currentVersionLabel.setFont(new Font(currentVersionLabel.getFont().getFontName(), Font.ITALIC, currentVersionLabel.getFont().getSize())); inventoryFilePanel.add(currentVersionLabel); inventoryFilePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, inventoryFilePanel.getPreferredSize().height)); inventoryPanel.add(inventoryFilePanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Inventory file directory Box inventoryDirPanel = new Box(BoxLayout.X_AXIS); inventoryDirPanel.add(new JLabel("Inventory File Location:")); inventoryDirPanel.add(Box.createHorizontalStrut(5)); inventoryDirField = new JTextField(25); JFileChooser inventoryChooser = new JFileChooser(); inventoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); inventoryChooser.setAcceptAllFileFilterUsed(false); inventoryDirPanel.add(inventoryDirField); inventoryDirPanel.add(Box.createHorizontalStrut(5)); JButton inventoryDirButton = new JButton(String.valueOf(UnicodeSymbols.ELLIPSIS)); inventoryDirButton.addActionListener((e) -> { if (inventoryChooser.showDialog(null, "Select Folder") == JFileChooser.APPROVE_OPTION) { File f = relativize(inventoryChooser.getSelectedFile()); inventoryDirField.setText(f.getPath()); inventoryChooser.setCurrentDirectory(f); } }); inventoryDirPanel.add(inventoryDirButton); inventoryDirPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, inventoryDirPanel.getPreferredSize().height)); inventoryPanel.add(inventoryDirPanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Card scans directory Box scansDirPanel = new Box(BoxLayout.X_AXIS); scansDirPanel.add(new JLabel("Card Images Location:")); scansDirPanel.add(Box.createHorizontalStrut(5)); scansDirField = new JTextField(25); JFileChooser scansChooser = new JFileChooser(); scansChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); scansChooser.setAcceptAllFileFilterUsed(false); scansDirPanel.add(scansDirField); scansDirPanel.add(Box.createHorizontalStrut(5)); JButton scansDirButton = new JButton(String.valueOf(UnicodeSymbols.ELLIPSIS)); scansDirButton.addActionListener((e) -> { if (scansChooser.showDialog(null, "Select Folder") == JFileChooser.APPROVE_OPTION) { File f = relativize(scansChooser.getSelectedFile()); scansDirField.setText(f.getPath()); scansChooser.setCurrentDirectory(f); } }); scansDirPanel.add(scansDirButton); scansDirPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, scansDirPanel.getPreferredSize().height)); inventoryPanel.add(scansDirPanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Card images source JPanel imgSourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); imgSourcePanel.add(new JLabel("Download card images from:")); imgSourcePanel.add(Box.createHorizontalStrut(5)); imgSourcePanel.add(imgSourceBox = new JComboBox<>(IMAGE_SOURCES.toArray(String[]::new))); imgSourcePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, imgSourcePanel.getPreferredSize().height)); inventoryPanel.add(imgSourcePanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Number of card images to keep JPanel imgLimitPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); limitImageBox = new JCheckBox("Limit downloaded card images to:"); imgLimitPanel.add(limitImageBox); limitImageSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); imgLimitPanel.add(limitImageSpinner); limitImageBox.addActionListener((e) -> limitImageSpinner.setEnabled(limitImageBox.isSelected())); imgLimitPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, imgLimitPanel.getPreferredSize().height)); inventoryPanel.add(imgLimitPanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Check for update on startup JPanel updatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); updatePanel.add(new JLabel("Update inventory on:")); updatePanel.add(Box.createHorizontalStrut(5)); updateBox = new JComboBox<>(UpdateFrequency.values()); updatePanel.add(updateBox); updatePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, updatePanel.getPreferredSize().height)); inventoryPanel.add(updatePanel); inventoryPanel.add(Box.createVerticalStrut(5)); // Show warnings from loading inventory JPanel suppressPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); suppressCheckBox = new JCheckBox("Show warnings after loading inventory"); suppressPanel.add(suppressCheckBox); suppressPanel.add(Box.createHorizontalStrut(5)); JButton viewWarningsButton = new JButton("View Warnings"); viewWarningsButton.addActionListener((e) -> { StringJoiner join = new StringJoiner("<li>", "<html>", "</ul></html>"); join.add("Warnings from last inventory load:<ul style=\"margin-top:0;margin-left:20pt\">"); for (String warning : inventoryWarnings) join.add(warning); JOptionPane.showMessageDialog(this, join.toString(), "Inventory Warnings", JOptionPane.WARNING_MESSAGE); }); suppressPanel.add(viewWarningsButton); suppressPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, suppressPanel.getPreferredSize().height)); inventoryPanel.add(suppressPanel); inventoryPanel.add(Box.createVerticalGlue()); // Warning panel JPanel pathWarningPanel = new JPanel(new BorderLayout()); JLabel pathWarningLabel = new JLabel("*Warning: Changing these settings may break functionality"); pathWarningLabel.setFont(new Font(pathWarningLabel.getFont().getFontName(), Font.ITALIC, pathWarningLabel.getFont().getSize())); pathWarningLabel.setForeground(Color.RED); pathWarningPanel.add(pathWarningLabel); pathWarningPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, pathWarningLabel.getPreferredSize().height)); inventoryPanel.add(pathWarningPanel); // Inventory appearance ScrollablePanel inventoryAppearancePanel = new ScrollablePanel(ScrollablePanel.TRACK_WIDTH); inventoryAppearancePanel.setLayout(new BoxLayout(inventoryAppearancePanel, BoxLayout.Y_AXIS)); JScrollPane inventoryAppearanceScroll = new JScrollPane(inventoryAppearancePanel); inventoryAppearanceScroll.setBorder(BorderFactory.createEmptyBorder()); settingsPanel.add(inventoryAppearanceScroll, new TreePath(inventoryAppearanceNode.getPath()).toString()); // Columns JPanel inventoryColumnsPanel = new JPanel(new GridLayout(0, 5)); inventoryColumnsPanel.setBorder(BorderFactory.createTitledBorder("Columns")); inventoryColumnCheckBoxes = new HashMap<>(); var inventoryAttributes = Arrays.stream(CardAttribute.inventoryValues()).sorted((a, b) -> { return a.toString().compareTo(b.toString()); }).collect(Collectors.toList()); for (CardAttribute characteristic : inventoryAttributes) { JCheckBox checkBox = new JCheckBox(characteristic.toString()); inventoryColumnCheckBoxes.put(characteristic, checkBox); inventoryColumnsPanel.add(checkBox); } inventoryAppearancePanel.add(inventoryColumnsPanel); // Stripe color JPanel inventoryColorPanel = new JPanel(new BorderLayout()); inventoryColorPanel.setBorder(BorderFactory.createTitledBorder("Stripe Color")); inventoryStripeColor = new JColorChooser(); createStripeChooserPreview(inventoryStripeColor); inventoryColorPanel.add(inventoryStripeColor); inventoryAppearancePanel.add(inventoryColorPanel); // Card image background color JPanel scanBGPanel = new JPanel(new BorderLayout()); scanBGPanel.setBorder(BorderFactory.createTitledBorder("Image Background Color")); scanBGChooser = new JColorChooser(); scanBGChooser.getSelectionModel().addChangeListener((e) -> parent.setImageBackground(scanBGChooser.getColor())); scanBGPanel.add(scanBGChooser); inventoryAppearancePanel.add(scanBGPanel); // Editor Box editorPanel = new Box(BoxLayout.Y_AXIS); editorPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); settingsPanel.add(editorPanel, new TreePath(editorNode.getPath()).toString()); // Recent count Box recentPanel = new Box(BoxLayout.X_AXIS); recentPanel.add(new JLabel("Recent file count:")); recentPanel.add(Box.createHorizontalStrut(5)); recentSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); recentPanel.add(recentSpinner); recentPanel.add(Box.createHorizontalStrut(5)); JLabel recentInfoLabel = new JLabel("(Changes will not be visible until program restart)"); recentInfoLabel.setFont(new Font(recentInfoLabel.getFont().getFontName(), Font.ITALIC, recentInfoLabel.getFont().getSize())); recentPanel.add(recentInfoLabel); recentPanel.setMaximumSize(new Dimension(recentPanel.getPreferredSize().width + 10, recentPanel.getPreferredSize().height)); recentPanel.setAlignmentX(LEFT_ALIGNMENT); editorPanel.add(recentPanel); editorPanel.add(Box.createVerticalStrut(5)); // Whitelist and blacklist rows to show Box explicitsPanel = new Box(BoxLayout.X_AXIS); explicitsPanel.add(new JLabel("Blacklist/Whitelist rows to display:")); explicitsPanel.add(Box.createHorizontalStrut(5)); explicitsSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); explicitsPanel.add(explicitsSpinner); explicitsPanel.setMaximumSize(new Dimension(explicitsPanel.getPreferredSize().width + 5, explicitsPanel.getPreferredSize().height)); explicitsPanel.setAlignmentX(LEFT_ALIGNMENT); editorPanel.add(explicitsPanel); editorPanel.add(Box.createVerticalStrut(5)); // Mana value choice for analysis JPanel manaValuePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); manaValuePanel.add(new JLabel("Mana value to analyze:")); manaValuePanel.add(Box.createHorizontalStrut(5)); manaValueBox = new JComboBox<>(MANA_VALUE_OPTIONS.toArray(String[]::new)); manaValuePanel.add(manaValueBox); manaValuePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, manaValuePanel.getPreferredSize().height)); manaValuePanel.setAlignmentX(LEFT_ALIGNMENT); editorPanel.add(manaValuePanel); editorPanel.add(Box.createVerticalStrut(5)); // Which layouts to count lands on back sides JPanel landsPanel = new JPanel(new FlowLayout(0, 0, FlowLayout.LEADING)); landsPanel.setBorder(BorderFactory.createTitledBorder("Count lands on back sides for layouts:")); landsCheckBoxes = Arrays.stream(editor.database.card.CardLayout.values()).filter((l) -> l.isMultiFaced).map((l) -> new JCheckBox(l.toString(), settings.editor().backFaceLands().contains(l))).collect(Collectors.toList()); for (JCheckBox box : landsCheckBoxes) landsPanel.add(box); landsPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, landsPanel.getPreferredSize().height)); landsPanel.setAlignmentX(LEFT_ALIGNMENT); editorPanel.add(landsPanel); editorPanel.add(Box.createVerticalStrut(5)); editorPanel.add(Box.createVerticalGlue()); // Editor categories JPanel categoriesPanel = new JPanel(); categoriesPanel.setLayout(new BorderLayout(5, 0)); categoriesPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); settingsPanel.add(categoriesPanel, new TreePath(editorCategoriesNode.getPath()).toString()); categoriesList = new CategoryList("<html><i>&lt;Double-click to add or edit&gt;</i></html>"); categoriesPanel.add(new JScrollPane(categoriesList), BorderLayout.CENTER); // Category modification buttons VerticalButtonList categoryModPanel = new VerticalButtonList("+", String.valueOf(UnicodeSymbols.ELLIPSIS), String.valueOf(UnicodeSymbols.MINUS)); categoryModPanel.get("+").addActionListener((e) -> CategoryEditorPanel.showCategoryEditor(this).ifPresent(categoriesList::addCategory)); categoryModPanel.get(String.valueOf(UnicodeSymbols.ELLIPSIS)).addActionListener((e) -> { if (categoriesList.getSelectedIndex() >= 0) { CategoryEditorPanel.showCategoryEditor(this, Optional.of(categoriesList.getCategoryAt(categoriesList.getSelectedIndex()))).ifPresent((s) -> { categoriesList.setCategoryAt(categoriesList.getSelectedIndex(), s); }); } }); categoryModPanel.get(String.valueOf(UnicodeSymbols.MINUS)).addActionListener((e) -> { if (categoriesList.getSelectedIndex() >= 0) categoriesList.removeCategoryAt(categoriesList.getSelectedIndex()); }); categoriesPanel.add(categoryModPanel, BorderLayout.EAST); // Editor appearance Box editorAppearancePanel = new Box(BoxLayout.Y_AXIS); settingsPanel.add(editorAppearancePanel, new TreePath(editorAppearanceNode.getPath()).toString()); // Editor category rows Box rowsPanel = new Box(BoxLayout.X_AXIS); rowsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0)); rowsPanel.add(new JLabel("Initial displayed rows in categories:")); rowsPanel.add(Box.createHorizontalStrut(5)); rowsSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); rowsPanel.add(rowsSpinner); rowsPanel.setMaximumSize(new Dimension(rowsPanel.getPreferredSize().width + 5, rowsPanel.getPreferredSize().height)); rowsPanel.setAlignmentX(LEFT_ALIGNMENT); editorAppearancePanel.add(rowsPanel); // Editor table columns JPanel editorColumnsPanel = new JPanel(new GridLayout(0, 5)); editorColumnsPanel.setBorder(BorderFactory.createTitledBorder("Columns")); editorColumnCheckBoxes = new HashMap<>(); var editorAttributes = Arrays.stream(CardAttribute.displayableValues()).sorted((a, b) -> { return a.toString().compareTo(b.toString()); }).collect(Collectors.toList()); for (CardAttribute characteristic : editorAttributes) { JCheckBox checkBox = new JCheckBox(characteristic.toString()); editorColumnCheckBoxes.put(characteristic, checkBox); editorColumnsPanel.add(checkBox); } editorColumnsPanel.setAlignmentX(LEFT_ALIGNMENT); editorAppearancePanel.add(editorColumnsPanel); // Editor table stripe color JPanel editorColorPanel = new JPanel(new BorderLayout()); editorColorPanel.setBorder(BorderFactory.createTitledBorder("Stripe Color")); editorStripeColor = new JColorChooser(); createStripeChooserPreview(editorStripeColor); editorColorPanel.add(editorStripeColor); editorColorPanel.setAlignmentX(LEFT_ALIGNMENT); editorAppearancePanel.add(editorColorPanel); editorAppearancePanel.add(Box.createVerticalGlue()); // Sample hand ScrollablePanel sampleHandPanel = new ScrollablePanel(ScrollablePanel.TRACK_WIDTH); sampleHandPanel.setLayout(new BoxLayout(sampleHandPanel, BoxLayout.Y_AXIS)); JScrollPane sampleHandScroll = new JScrollPane(sampleHandPanel); sampleHandScroll.setBorder(BorderFactory.createEmptyBorder()); settingsPanel.add(sampleHandScroll, new TreePath(handAppearanceNode.getPath()).toString()); sampleHandPanel.add(Box.createVerticalStrut(5)); // Starting Size Box startingSizePanel = new Box(BoxLayout.X_AXIS); startingSizePanel.add(Box.createHorizontalStrut(5)); startingSizePanel.add(new JLabel("Starting Size:")); startingSizePanel.add(Box.createHorizontalStrut(5)); startingSizeSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); startingSizePanel.add(startingSizeSpinner); startingSizePanel.add(Box.createHorizontalGlue()); startingSizePanel.setMaximumSize(new Dimension(startingSizePanel.getPreferredSize().width + 5, startingSizePanel.getPreferredSize().height)); startingSizePanel.setAlignmentX(LEFT_ALIGNMENT); sampleHandPanel.add(startingSizePanel); sampleHandPanel.add(Box.createVerticalStrut(5)); // Expected counts round mode Box expectedRoundPanel = new Box(BoxLayout.X_AXIS); expectedRoundPanel.add(Box.createHorizontalStrut(5)); expectedRoundPanel.add(new JLabel("Expected Category Count Round Mode:")); expectedRoundPanel.add(Box.createHorizontalStrut(5)); ButtonGroup roundGroup = new ButtonGroup(); modeButtons = new ArrayList<>(); for (String mode : CalculateHandPanel.ROUND_MODE.keySet().stream().sorted().collect(Collectors.toList())) { JRadioButton modeButton = new JRadioButton(mode); roundGroup.add(modeButton); expectedRoundPanel.add(modeButton); expectedRoundPanel.add(Box.createHorizontalStrut(5)); modeButtons.add(modeButton); } expectedRoundPanel.setMaximumSize(expectedRoundPanel.getPreferredSize()); expectedRoundPanel.setAlignmentX(LEFT_ALIGNMENT); sampleHandPanel.add(expectedRoundPanel); sampleHandPanel.add(Box.createVerticalStrut(5)); // Sample hand background color JPanel handBGColorPanel = new JPanel(new BorderLayout()); handBGColorPanel.setBorder(BorderFactory.createTitledBorder("Background Color")); handBGColor = new JColorChooser(); handBGColor.getSelectionModel().addChangeListener((e) -> parent.setHandBackground(handBGColor.getColor())); handBGColorPanel.add(handBGColor); handBGColorPanel.setAlignmentX(LEFT_ALIGNMENT); sampleHandPanel.add(handBGColorPanel); // Format constraints Box formatsPanel = Box.createVerticalBox(); settingsPanel.add(formatsPanel, new TreePath(formatsNode.getPath()).toString()); // Formats table JTable formatsTable = new JTable(new DefaultTableModel(FormatConstraints.FORMAT_NAMES.stream() .map((f) -> FormatConstraints.CONSTRAINTS.get(f).toArray(f)) .toArray(Object[][]::new), FormatConstraints.DATA_NAMES.toArray(String[]::new)) { @Override public Class<?> getColumnClass(int column) { return FormatConstraints.CLASSES.get(column); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }); formatsTable.setFillsViewportHeight(true); JScrollPane formatsPane = new JScrollPane(formatsTable); formatsPane.setAlignmentX(LEFT_ALIGNMENT); formatsPanel.add(formatsPane); // Mana analysis ScrollablePanel manaAnalysisPanel = new ScrollablePanel(ScrollablePanel.TRACK_WIDTH); manaAnalysisPanel.setLayout(new BoxLayout(manaAnalysisPanel, BoxLayout.Y_AXIS)); JScrollPane manaAnalysisScroll = new JScrollPane(manaAnalysisPanel); manaAnalysisScroll.setBorder(BorderFactory.createEmptyBorder()); settingsPanel.add(manaAnalysisScroll, new TreePath(manaAnalysisNode.getPath()).toString()); // Mana analysis section color selector Box manaAnalysisColorPanel = Box.createVerticalBox(); manaAnalysisColorPanel.setBorder(BorderFactory.createTitledBorder("Plot Sections")); sections = new String[] { "Nothing", "Colorless", "White", "Blue", "Black", "Red", "Green", "Multicolored", "Creature", "Artifact", "Enchantment", "Planeswalker", "Instant", "Sorcery" }; sectionChoosers = Arrays.stream(sections).collect(Collectors.toMap(Function.identity(), (c) -> new JColorChooser())); Box manaAnalysisSectionPanel = Box.createHorizontalBox(); manaAnalysisSectionPanel.add(new JLabel("Color for:")); manaAnalysisSectionPanel.add(Box.createHorizontalStrut(2)); var sectionsBox = new JComboBox<>(sections); var original = sectionsBox.getRenderer(); sectionsBox.setRenderer((list, value, index, isSelected, cellHasFocus) -> { Component label = original.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); JPanel panel = new JPanel(new BorderLayout()); panel.setForeground(label.getForeground()); panel.setBackground(label.getBackground()); panel.add(label, BorderLayout.CENTER); JPanel color = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(sectionChoosers.get(value).getColor()); g.fillRect(1, 1, getWidth() - 3, getHeight() - 3); g.setColor(Color.BLACK); g.drawRect(1, 1, getWidth() - 3, getHeight() - 3); } }; color.setPreferredSize(new Dimension(label.getPreferredSize().height, label.getPreferredSize().height)); color.setForeground(label.getForeground()); color.setBackground(label.getBackground()); panel.add(color, BorderLayout.EAST); return panel; }); sectionsBox.setMaximumSize(sectionsBox.getPreferredSize()); manaAnalysisSectionPanel.add(sectionsBox); manaAnalysisSectionPanel.add(Box.createHorizontalGlue()); manaAnalysisColorPanel.add(manaAnalysisSectionPanel); CardLayout chooserLayout = new CardLayout(); JPanel sectionChooserPanel = new JPanel(chooserLayout); for (String section : sections) sectionChooserPanel.add(sectionChoosers.get(section), section); sectionsBox.addItemListener((e) -> chooserLayout.show(sectionChooserPanel, sectionsBox.getItemAt(sectionsBox.getSelectedIndex()))); manaAnalysisColorPanel.add(sectionChooserPanel); manaAnalysisPanel.add(manaAnalysisColorPanel); // Land analysis line color JPanel landAnalysisLinePanel = new JPanel(new BorderLayout()); landAnalysisLinePanel.setBorder(BorderFactory.createTitledBorder("Land Analysis Line")); JColorChooser landLineChooser = new JColorChooser(); landAnalysisLinePanel.add(landLineChooser, BorderLayout.CENTER); manaAnalysisPanel.add(landAnalysisLinePanel); Box legalityDefaultsBox = Box.createHorizontalBox(); legalityDefaultsBox.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); cmdrCheck = new JCheckBox(""); legalityDefaultsBox.add(cmdrCheck); ButtonGroup cmdrGroup = new ButtonGroup(); cmdrMainDeck = new JRadioButton("Main Deck"); cmdrGroup.add(cmdrMainDeck); legalityDefaultsBox.add(cmdrMainDeck); cmdrAllLists = new JRadioButton("All Lists"); cmdrGroup.add(cmdrAllLists); legalityDefaultsBox.add(cmdrAllLists); cmdrList = new JRadioButton(); cmdrGroup.add(cmdrList); legalityDefaultsBox.add(cmdrList); cmdrListName = new JTextField(); legalityDefaultsBox.add(cmdrListName); legalityDefaultsBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, legalityDefaultsBox.getPreferredSize().height)); legalityDefaultsBox.setAlignmentX(LEFT_ALIGNMENT); formatsPanel.add(legalityDefaultsBox); Box sideboardBox = Box.createHorizontalBox(); sideboardBox.setBorder(BorderFactory.createEmptyBorder(0, 2, 2, 2)); sideCheck = new JCheckBox(""); sideboardBox.add(sideCheck); sideField = new JTextField(); sideboardBox.add(sideField); sideboardBox.setAlignmentX(LEFT_ALIGNMENT); formatsPanel.add(sideboardBox); formatsPanel.add(Box.createVerticalGlue()); cmdrCheck.addActionListener((e) -> { cmdrCheck.setText(cmdrCheck.isSelected() ? "Search for commander in:" : "Search for commander"); cmdrMainDeck.setVisible(cmdrCheck.isSelected()); cmdrAllLists.setVisible(cmdrCheck.isSelected()); cmdrList.setVisible(cmdrCheck.isSelected()); cmdrListName.setVisible(cmdrCheck.isSelected()); }); ActionListener cmdrListener = (e) -> cmdrListName.setEnabled(cmdrList.isSelected()); cmdrMainDeck.addActionListener(cmdrListener); cmdrAllLists.addActionListener(cmdrListener); cmdrList.addActionListener(cmdrListener); sideCheck.addActionListener((e) -> { sideCheck.setText(sideCheck.isSelected() ? "Default sideboard name:" : "Include sideboard"); sideField.setVisible(sideCheck.isSelected()); }); // Tree panel JPanel treePanel = new JPanel(new BorderLayout()); JTree tree = new JTree(root); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); ((DefaultTreeCellRenderer)tree.getCellRenderer()).setLeafIcon(null); tree.addTreeSelectionListener((e) -> ((CardLayout)settingsPanel.getLayout()).show(settingsPanel, e.getPath().toString())); treePanel.add(tree, BorderLayout.CENTER); treePanel.add(new JSeparator(SwingConstants.VERTICAL), BorderLayout.EAST); treePanel.setPreferredSize(new Dimension(130, 0)); add(treePanel, BorderLayout.WEST); // Button panel JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton applyButton = new JButton("Apply"); applyButton.addActionListener((e) -> confirmSettings()); buttonPanel.add(applyButton); JButton okButton = new JButton("OK"); okButton.addActionListener((e) -> { confirmSettings(); setVisible(false); }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener((e) -> { rejectSettings(); setVisible(false); }); buttonPanel.add(cancelButton); JPanel bottomPanel = new JPanel(new BorderLayout()); bottomPanel.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.NORTH); bottomPanel.add(buttonPanel, BorderLayout.CENTER); add(bottomPanel, BorderLayout.SOUTH); pack(); setLocationRelativeTo(owner); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { inventorySiteField.setText(settings.inventory().source()); inventoryFileField.setText(settings.inventory().file()); currentVersionLabel.setText("(Current version: " + settings.inventory().version() + ")"); inventoryDirField.setText(settings.inventory().location()); inventoryChooser.setCurrentDirectory(new File(inventoryDirField.getText()).getAbsoluteFile()); scansDirField.setText(settings.inventory().scans()); scansChooser.setCurrentDirectory(new File(scansDirField.getText()).getAbsoluteFile()); imgSourceBox.setSelectedIndex(Math.max(IMAGE_SOURCES.indexOf(settings.inventory().imageSource()), 0)); limitImageBox.setSelected(settings.inventory().imageLimitEnable()); limitImageSpinner.setEnabled(settings.inventory().imageLimitEnable()); limitImageSpinner.setValue(settings.inventory().imageLimit()); updateBox.setSelectedIndex(settings.inventory().update().ordinal()); suppressCheckBox.setSelected(settings.inventory().warn()); viewWarningsButton.setEnabled(!inventoryWarnings.isEmpty()); for (var n : inventoryColumnCheckBoxes.entrySet()) n.getValue().setSelected(settings.inventory().columns().contains(n.getKey())); inventoryStripeColor.setColor(settings.inventory().stripe()); scanBGChooser.setColor(settings.inventory().background()); recentSpinner.getModel().setValue(settings.editor().recents().count()); explicitsSpinner.getModel().setValue(Integer.valueOf(settings.editor().categories().explicits())); manaValueBox.setSelectedIndex(Math.max(MANA_VALUE_OPTIONS.indexOf(settings.editor().manaValue()), 0)); for (Category preset : settings.editor().categories().presets()) categoriesList.addCategory(new Category(preset)); rowsSpinner.getModel().setValue(settings.editor().categories().rows()); for (var n : editorColumnCheckBoxes.entrySet()) n.getValue().setSelected(settings.editor().columns().contains(n.getKey())); editorStripeColor.setColor(settings.editor().stripe()); startingSizeSpinner.getModel().setValue(settings.editor().hand().size()); for (JRadioButton mode : modeButtons) mode.setSelected(mode.getText().equals(settings.editor().hand().rounding())); handBGColor.setColor(settings.editor().hand().background()); cmdrCheck.setSelected(settings.editor().legality().searchForCommander()); sideCheck.setSelected(!settings.editor().legality().sideboard().isEmpty()); sideCheck.setText(sideCheck.isSelected() ? "Default sideboard name:" : "Include sideboard"); sideField.setText(settings.editor().legality().sideboard()); sideField.setVisible(sideCheck.isSelected()); if (settings.editor().legality().searchForCommander()) { cmdrCheck.setText("Search for commander in:"); if (settings.editor().legality().main() || (!settings.editor().legality().all() && settings.editor().legality().list().isEmpty())) cmdrMainDeck.setSelected(true); else if (settings.editor().legality().all()) cmdrAllLists.setSelected(true); else cmdrList.setSelected(true); cmdrListName.setEnabled(cmdrList.isSelected()); cmdrListName.setText(settings.editor().legality().list()); } else { cmdrCheck.setText("Search for commander"); cmdrMainDeck.setVisible(false); cmdrAllLists.setVisible(false); cmdrList.setVisible(false); cmdrListName.setVisible(false); } for (String section : sections) sectionChoosers.get(section).setColor(settings().editor().manaAnalysis().get(section)); } }); } /** * Confirm the settings applied by the components of the dialog and send them to the parent * MainFrame. */ public void confirmSettings() { try { recentSpinner.commitEdit(); explicitsSpinner.commitEdit(); rowsSpinner.commitEdit(); startingSizeSpinner.commitEdit(); var presets = new ArrayList<Category>(categoriesList.getCount()); for (int i = 0; i < categoriesList.getCount(); i++) presets.add(categoriesList.getCategoryAt(i)); settings = new SettingsBuilder(settings) .inventorySource(inventorySiteField.getText()) .inventoryFile(inventoryFileField.getText()) .inventoryLocation(inventoryDirField.getText()) .inventoryScans(scansDirField.getText()) .imageSource(imgSourceBox.getItemAt(imgSourceBox.getSelectedIndex())) .imageLimitEnable(limitImageBox.isSelected()) .imageLimit((Integer)limitImageSpinner.getValue()) .inventoryUpdate(updateBox.getItemAt(updateBox.getSelectedIndex())) .inventoryWarn(suppressCheckBox.isSelected()) .inventoryColumns(inventoryColumnCheckBoxes.entrySet().stream().filter((e) -> e.getValue().isSelected()).map(Map.Entry::getKey).sorted().collect(Collectors.toList())) .inventoryStripe(inventoryStripeColor.getColor()) .recentsCount((Integer)recentSpinner.getValue()) .explicits((Integer)explicitsSpinner.getValue()) .manaValue(manaValueBox.getItemAt(manaValueBox.getSelectedIndex())) .backFaceLands(landsCheckBoxes.stream().filter(JCheckBox::isSelected).map((b) -> Arrays.stream(editor.database.card.CardLayout.values()).filter((l) -> l.toString().equals(b.getText())).findAny().get()).collect(Collectors.toSet())) .categoryRows((Integer)rowsSpinner.getValue()) .editorColumns(editorColumnCheckBoxes.entrySet().stream().filter((e) -> e.getValue().isSelected()).map(Map.Entry::getKey).sorted().collect(Collectors.toList())) .editorStripe(editorStripeColor.getColor()) .presetCategories(presets) .handSize((Integer)startingSizeSpinner.getValue()) .handRounding(modeButtons.stream().filter(JRadioButton::isSelected).map(JRadioButton::getText).findAny().orElse("No rounding")) .inventoryBackground(scanBGChooser.getColor()) .searchForCommander(cmdrCheck.isSelected()) .commanderInMain(cmdrMainDeck.isSelected() || (cmdrCheck.isSelected() && cmdrList.isSelected() && cmdrListName.getText().isEmpty())) .commanderInAll(cmdrAllLists.isSelected()) .commanderInList(cmdrListName.getText()) .sideboardName(sideCheck.isSelected() ? sideField.getText() : "") .sections(sectionChoosers.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (e) -> e.getValue().getColor()))) .build(); } catch (ParseException e) { e.printStackTrace(); } if (settings.inventory().columns().isEmpty()) settings = new SettingsBuilder(settings).inventoryColumns(new SettingsBuilder().defaults().build().inventory().columns()).build(); if (settings.editor().columns().isEmpty()) settings = new SettingsBuilder(settings).editorColumns(new SettingsBuilder().defaults().build().editor().columns()).build(); parent.applySettings(); } /** * Reject any changes that were made as a result of using the settings dialog. */ public void rejectSettings() { parent.setImageBackground(settings.inventory().background()); parent.setHandBackground(settings.editor().hand().background()); } }
package de.rwth.dbis.layers.lapps.resource; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import de.rwth.dbis.layers.lapps.authenticate.OIDCAuthentication; import de.rwth.dbis.layers.lapps.domain.UserFacade; import de.rwth.dbis.layers.lapps.entity.UserEntity; import de.rwth.dbis.layers.lapps.exception.OIDCException; /** * Users resource (exposed at "users" path). */ @Path("/users") @Api(value = "/users", description = "User resource") public class UsersResource { private static final Logger LOGGER = Logger.getLogger(UsersResource.class.getName()); private static UserFacade userFacade = new UserFacade(); /** * * Get all users. * * @param accessToken * @param search query parameter * @param page number * @param pageLength number of users by page * @param sortBy field * @param order asc or desc * * @return Response with all users as JSON array. */ @GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get all users", response = UserEntity.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpStatusCode.OK, message = "Default return message"), @ApiResponse(code = HttpStatusCode.UNAUTHORIZED, message = "Invalid authentication"), @ApiResponse(code = HttpStatusCode.INTERNAL_SERVER_ERROR, message = "Internal server problems")}) public Response getAllUsers( @HeaderParam("accessToken") String accessToken, @ApiParam(value = "Search query parameter", required = false) @QueryParam("search") String search, @ApiParam(value = "Page number", required = false) @DefaultValue("1") @QueryParam("page") int page, @ApiParam(value = "Number of users by page", required = false) @DefaultValue("-1") @HeaderParam("pageLength") int pageLength, @ApiParam(value = "Sort by field", required = false, allowableValues = "email") @DefaultValue("email") @QueryParam("sortBy") String sortBy, @ApiParam(value = "Order asc or desc", required = false, allowableValues = "asc,desc") @DefaultValue("asc") @QueryParam("order") String order) { try { OIDCAuthentication.authenticate(accessToken); // TODO: Check for admin rights (not part of the open id authentication process) } catch (OIDCException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.UNAUTHORIZED).build(); } List<UserEntity> entities; if (search == null) { entities = (List<UserEntity>) userFacade.findAll(); } else { entities = (List<UserEntity>) userFacade.findByEmail(search); } Collections.sort(entities); if (order.equalsIgnoreCase("desc")) { Collections.reverse(entities); } int numberOfPages = 1; if (pageLength > 0 && pageLength < entities.size()) { int fromIndex = page == 1 ? 0 : (page * pageLength) - pageLength; int toIndex = page == 1 ? pageLength : page * pageLength; numberOfPages = (int) Math.ceil((double) entities.size() / pageLength); if (entities.size() < fromIndex + 1) { entities.clear(); } else { if (entities.size() < toIndex + 1) { toIndex = entities.size(); } entities = entities.subList(fromIndex, toIndex); } } try { ObjectMapper mapper = new ObjectMapper(); return Response.status(HttpStatusCode.OK).header("numberOfPages", numberOfPages) .entity(mapper.writeValueAsBytes(entities)).build(); } catch (JsonProcessingException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.INTERNAL_SERVER_ERROR).build(); } } /** * * Gets the user for a given oidcId. * * @param oidcId * * @return Response with user as a JSON object. * */ @GET @Path("/{oidcId}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get user by oidcId", response = UserEntity.class) @ApiResponses(value = { @ApiResponse(code = HttpStatusCode.OK, message = "Default return message"), @ApiResponse(code = HttpStatusCode.NOT_FOUND, message = "User not found"), @ApiResponse(code = HttpStatusCode.INTERNAL_SERVER_ERROR, message = "Internal server problems")}) public Response getUser(@PathParam("oidcId") long oidcId) { // search for existing user List<UserEntity> entities = userFacade.findByOidcId(oidcId); UserEntity user = null; if (entities.isEmpty()) { return Response.status(HttpStatusCode.NOT_FOUND).build(); } else { user = entities.get(0); } try { ObjectMapper mapper = new ObjectMapper(); return Response.status(HttpStatusCode.OK).entity(mapper.writeValueAsBytes(user)).build(); } catch (JsonProcessingException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.INTERNAL_SERVER_ERROR).build(); } } /** * * Delete the user with the given oidcId. * * @param oidcId * * @return Response * */ @DELETE @Path("/{oidcId}") @ApiOperation(value = "Delete user by oidcId") @ApiResponses(value = { @ApiResponse(code = HttpStatusCode.OK, message = "Default return message"), @ApiResponse(code = HttpStatusCode.UNAUTHORIZED, message = "Invalid authentication"), @ApiResponse(code = HttpStatusCode.NOT_FOUND, message = "User not found"), @ApiResponse(code = HttpStatusCode.NOT_IMPLEMENTED, message = "Currently, this method is not implemented")}) public Response deleteUser(@HeaderParam("accessToken") String accessToken, @PathParam("oidcId") long oidcId) { try { // TODO: Check for admin or user himself rights (not part of the open id authentication // process) OIDCAuthentication.authenticate(accessToken); } catch (OIDCException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.UNAUTHORIZED).build(); } // search for existing user List<UserEntity> entities = userFacade.findByOidcId(oidcId); if (entities.isEmpty()) { return Response.status(HttpStatusCode.NOT_FOUND).build(); } else { // UserEntity user = entities.get(0); } // TODO: delete user with help of userFacade return Response.status(HttpStatusCode.NOT_IMPLEMENTED).build(); } /** * * Update the user with the given oidcId. * * @param oidcId * @param updatedUser as JSON * * @return Response with updated User */ @PUT @Path("/{oidcId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update user by oidcId", response = UserEntity.class) @ApiResponses(value = { @ApiResponse(code = HttpStatusCode.OK, message = "Default return message"), @ApiResponse(code = HttpStatusCode.UNAUTHORIZED, message = "Invalid authentication"), @ApiResponse(code = HttpStatusCode.NOT_FOUND, message = "User not found"), @ApiResponse(code = HttpStatusCode.INTERNAL_SERVER_ERROR, message = "Internal server problems"), @ApiResponse(code = HttpStatusCode.NOT_IMPLEMENTED, message = "Currently, this method is not implemented")}) public Response updateUser(@HeaderParam("accessToken") String accessToken, @PathParam("oidcId") long oidcId, @ApiParam(value = "User entity as JSON", required = true) UserEntity updatedUser) { try { // TODO: Check for admin or user himself rights (not part of the open id authentication // process) OIDCAuthentication.authenticate(accessToken); } catch (OIDCException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.UNAUTHORIZED).build(); } // search for existing user List<UserEntity> entities = userFacade.findByOidcId(oidcId); if (entities.isEmpty()) { return Response.status(HttpStatusCode.NOT_FOUND).build(); } else { // UserEntity user = entities.get(0); } // TODO: update user with help of userFacade try { ObjectMapper mapper = new ObjectMapper(); return Response.status(HttpStatusCode.NOT_IMPLEMENTED) .entity(mapper.writeValueAsBytes(updatedUser)).build(); } catch (JsonProcessingException e) { LOGGER.warning(e.getMessage()); return Response.status(HttpStatusCode.INTERNAL_SERVER_ERROR).build(); } } }
package info.jayharris.klondike; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.googlecode.blacken.colors.ColorNames; import com.googlecode.blacken.colors.ColorPalette; import com.googlecode.blacken.swing.SwingTerminal; import com.googlecode.blacken.terminal.BlackenKeys; import com.googlecode.blacken.terminal.CursesLikeAPI; import com.googlecode.blacken.terminal.TerminalInterface; import info.jayharris.cardgames.Deck; import org.apache.commons.collections4.iterators.LoopingListIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class TerminalUI implements KlondikeUI { private Klondike klondike; private boolean quit; private ColorPalette palette; private CursesLikeAPI term = null; private TerminalUIComponent<?> pointingTo, movingFrom = null; private List<TerminalUIComponent<?>> components; private LoopingListIterator<TerminalUIComponent<?>> componentOrder; private boolean lastDirectionRight = true; // direction of last move -- // if componentOrder.next() => X, then an immediate call to // componentOrder.previous() will also => X. public final int START_ROW = 0, LEFT_COL = 5, SPACE_BETWEEN = 5, TABLEAU_ROW = 2, WASTE_CARDS_SHOWN = 6, WASTE_START_COL = LEFT_COL + "[24 cards]".length() + SPACE_BETWEEN, WASTE_MAX_WIDTH = "... XX XX XX XX XX XX".length(), FOUNDATION_START_COL = WASTE_START_COL + WASTE_MAX_WIDTH + SPACE_BETWEEN; final Logger logger = LoggerFactory.getLogger(TerminalUI.class); public TerminalUI(Klondike klondike) { this.klondike = klondike; } protected boolean loop() { int key = BlackenKeys.NO_KEY; if (palette.containsKey("White")) { term.setCurBackground("White"); } if (palette.containsKey("Black")) { term.setCurForeground("Black"); } term.clear(); while (!this.quit) { for (TerminalUIComponent<?> component : components) { component.writeToTerminal(); } pointingTo.drawPointer(false); key = term.getch(); // getch automatically does a refresh onKeyPress(key); } term.refresh(); return this.quit; } public void init(TerminalInterface term, ColorPalette palette) { if (term == null) { this.term = new CursesLikeAPI(new SwingTerminal()); this.term.init("Klondike", 25, 80); } else { this.term = new CursesLikeAPI(term); } if (palette == null) { palette = new ColorPalette(); palette.addAll(ColorNames.XTERM_256_COLORS, false); palette.putMapping(ColorNames.SVG_COLORS); } this.palette = palette; this.term.setPalette(palette); // set up all of the deck, waste, foundation, tableau visual components components = new ArrayList<TerminalUIComponent<?>>() {{ int col; this.add(new TerminalUIComponent<Deck>(klondike.getDeck(), START_ROW, LEFT_COL) { @Override public void writeToTerminal() { super.writeToTerminal("[" + Strings.padStart(Integer.toString(klondike.getDeck().size()), 2, ' ') + " cards]"); } @Override public void doAction() { klondike.deal(); } }); this.add(new TerminalUIComponent<Klondike.Waste>(klondike.getWaste(), START_ROW, WASTE_START_COL) { @Override public void doAction() { // pick up the next card in the waste if (movingFrom == null && !payload.isEmpty()) { movingFrom = this; } // return the card to whence it came else { movingFrom = null; } } @Override public void writeToTerminal() { int sz = payload.size(); int index = Math.max(0, sz - WASTE_CARDS_SHOWN), strlen = 0; if (sz > WASTE_CARDS_SHOWN) { writeToTerminal("... "); strlen += "... ".length(); } while (index < sz) { if (index == sz - 1) { if (movingFrom == this) { setCurBackground("Yellow"); } writeToTerminal(0, strlen, payload.get(index).toString()); strlen += 2; } else { writeToTerminal(0, strlen, payload.get(index).toString() + " "); strlen += 3; } setCurBackground("White"); ++index; } while (strlen < WASTE_MAX_WIDTH) { writeToTerminal(0, strlen, " "); ++strlen; } } }); col = LEFT_COL; for (int i = 0; i < 7; ++i) { this.add(new TableauUIComponent(klondike.getTableau(i), col)); col += "XX".length() + SPACE_BETWEEN; } col = FOUNDATION_START_COL; this.add(new TerminalUIComponent<Collection<Klondike.Foundation>>( klondike.getFoundations(), START_ROW, col) { Joiner joiner = Joiner.on(Strings.repeat(" ", SPACE_BETWEEN)); @Override public void writeToTerminal() { writeToTerminal(joiner.join(payload)); } @Override public void doAction() { boolean legal = false; if (movingFrom != null) { if (movingFrom.getClass() == TableauUIComponent.class) { legal = klondike.moveFromTableauToFoundation((Klondike.Tableau) movingFrom.payload); } else { legal = klondike.moveFromWasteToFoundation(); } } if (legal) { movingFrom.writeToTerminal(); this.writeToTerminal(); movingFrom = null; } } }); }}; componentOrder = new LoopingListIterator(components); pointingTo = componentOrder.next(); start(); } private void onKeyPress(int codepoint) { switch (codepoint) { case ' ': pointingTo.doAction(); break; case 'a': case 'A': movePointerAndRedraw(true); break; case 'd': case 'D': movePointerAndRedraw(false); break; default: break; } pointingTo.receiveKeyPress(codepoint); } public void update(Observable observable, Object object) { } private void setCurBackground(String c) { term.setCurBackground(c); } private void movePointerAndRedraw(boolean left) { pointingTo.drawPointer(true); if (left) { movePointerLeft(); } else { movePointerRight(); } pointingTo.receiveFocus(); pointingTo.drawPointer(false); } private void movePointerRight() { pointingTo = componentOrder.next(); if (!lastDirectionRight) { pointingTo = componentOrder.next(); lastDirectionRight = true; } } private void movePointerLeft() { pointingTo = componentOrder.previous(); if (lastDirectionRight) { pointingTo = componentOrder.previous(); lastDirectionRight = false; } } private void start() { klondike.init(); } public void quit() { this.quit = true; term.quit(); } public abstract class TerminalUIComponent<T> { T payload; int startRow, startColumn; public TerminalUIComponent(T payload, int startRow, int startColumn) { this.payload = payload; this.startRow = startRow; this.startColumn = startColumn; } public abstract void doAction(); public void receiveFocus() {} public void receiveKeyPress(int codepoint) {} public void writeToTerminal() { this.writeToTerminal(payload.toString()); } public void writeToTerminal(String str) { term.mvputs(startRow, startColumn, str); } public void writeToTerminal(int rowOffset, int columnOffset, String str) { term.mvputs(startRow + rowOffset, startColumn + columnOffset, str); } /** * Draw or undraw the pointer indicating the current element. * * @param remove if {@code true} then remove the pointer, otherwise draw it */ public void drawPointer(boolean remove) { term.mvputs(startRow, startColumn - 3, remove ? " " : "-> "); } } public class TableauUIComponent extends TerminalUIComponent<Klondike.Tableau> { int pointerIndex; int lengthToClean; static final String blank = " "; public TableauUIComponent(Klondike.Tableau payload, int column) { super(payload, TABLEAU_ROW, column); pointerIndex = payload.size() - 1; lengthToClean = payload.size(); } public void writeToTerminal() { for (int i = 0; i < Math.max(payload.size(), lengthToClean); ++i) { if (movingFrom == this && pointerIndex == i) { setCurBackground("Yellow"); } if (i == payload.size()) { setCurBackground("White"); } term.mvputs(startRow + i, startColumn, i < payload.size() ? payload.get(i).toString() : " "); } setCurBackground("White"); lengthToClean = payload.size(); } public void doAction() { boolean legal = false; if (movingFrom == null && !payload.isEmpty()) { movingFrom = this; } else if (movingFrom.getClass() == TableauUIComponent.class) { TableauUIComponent _movingFrom = (TableauUIComponent) movingFrom; int numCards = _movingFrom.payload.size() - _movingFrom.pointerIndex; legal = klondike.moveFromTableauToTableau(_movingFrom.payload, this.payload, numCards); } else { legal = klondike.moveFromWasteToTableau(this.payload); } if (legal) { movingFrom.writeToTerminal(); writeToTerminal(); drawPointer(true); this.pointerIndex = payload.size() - 1; drawPointer(false); movingFrom = null; } } public void receiveFocus() { if (movingFrom != this) { pointerIndex = payload.size() - 1; } } public void receiveKeyPress(int codepoint) { switch (codepoint) { case 'w': case 'W': movePointerUp(); break; case 's': case 'S': movePointerDown(); break; default: break; } } public void movePointerUp() { if (pointerIndex > payload.size() - payload.countFaceup()) { drawPointer(true); --pointerIndex; drawPointer(false); } } public void movePointerDown() { if (pointerIndex < payload.size() - 1) { drawPointer(true); ++pointerIndex; drawPointer(false); } } public void drawPointer(boolean remove) { term.mvputs(startRow + pointerIndex, startColumn - 3, remove ? " " : "-> "); } } public static void main(String[] args) { TerminalUI ui = new TerminalUI(new Klondike()); ui.init(null, null); ui.loop(); ui.quit(); } }
package io.luna.game.model; import com.google.common.collect.ImmutableList; public final class EntityConstants { /** * The amount of players that can login per tick. */ public static final int LOGIN_THRESHOLD = 50; /** * The amount of players that can logout per tick. */ public static final int LOGOUT_THRESHOLD = 50; /** * The maximum amount of tiles a player can view. */ public static final int VIEWING_DISTANCE = 15; /** * The wilderness areas. */ public static final ImmutableList<Area> WILDERNESS = ImmutableList .of(Area.create(2941, 3518, 3392, 3966, 0), Area.create(2941, 3518, 3392, 3966, 1), Area.create(2941, 3518, 3392, 3966, 2), Area.create(2941, 3518, 3392, 3966, 3)); /** * A private constructor. */ private EntityConstants() { } }
package it.near.sdk.Recipes; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import it.near.sdk.Communication.Constants; import it.near.sdk.Communication.CustomJsonRequest; import it.near.sdk.Communication.Filter; import it.near.sdk.GlobalConfig; import it.near.sdk.GlobalState; import it.near.sdk.MorpheusNear.Morpheus; import it.near.sdk.Reactions.Reaction; import it.near.sdk.Recipes.Models.OperationAction; import it.near.sdk.Recipes.Models.PulseAction; import it.near.sdk.Recipes.Models.PulseBundle; import it.near.sdk.Recipes.Models.ReactionAction; import it.near.sdk.Recipes.Models.ReactionBundle; import it.near.sdk.Recipes.Models.Recipe; import it.near.sdk.Utils.NearUtils; import it.near.sdk.Utils.ULog; /** * Menage recipes download, caching and direct calling. * * @author cattaneostefano */ public class RecipesManager { private static final String TAG = "RecipesManager"; public static final String PREFS_SUFFIX = "NearRecipes"; private static final String EVALUATE_PATH = "evaluate"; public final String PREFS_NAME; private final SharedPreferences sp; private Context mContext; private Morpheus morpheus; private List<Recipe> recipes = new ArrayList<>(); private HashMap<String, Reaction> reactions = new HashMap<>(); SharedPreferences.Editor editor; public RecipesManager(Context context) { this.mContext = context; String PACK_NAME = mContext.getApplicationContext().getPackageName(); PREFS_NAME = PACK_NAME + PREFS_SUFFIX; sp = mContext.getSharedPreferences(PREFS_NAME, 0); editor = sp.edit(); try { loadChachedList(); } catch (JSONException e) { e.printStackTrace(); } setUpMorpheusParser(); refreshConfig(); } private void setUpMorpheusParser() { morpheus = new Morpheus(); // register your resources morpheus.getFactory().getDeserializer().registerResourceClass("recipes", Recipe.class); morpheus.getFactory().getDeserializer().registerResourceClass("pulse_actions", PulseAction.class); morpheus.getFactory().getDeserializer().registerResourceClass("operation_actions", OperationAction.class); morpheus.getFactory().getDeserializer().registerResourceClass("reaction_actions", ReactionAction.class); morpheus.getFactory().getDeserializer().registerResourceClass("pulse_bundles", PulseBundle.class); morpheus.getFactory().getDeserializer().registerResourceClass("reaction_bundles", ReactionBundle.class); } public void addReaction(String plugin, Reaction reaction){ reactions.put(plugin, reaction); } /** * return the list of recipes * @return the list of recipes */ public List<Recipe> getRecipes() { return recipes; } /** * Tries to refresh the recipes list. If some network problem occurs, a cached version will be used. */ public void refreshConfig(){ final Uri uri = Uri.parse(Constants.API.RECIPES_PATH).buildUpon() .appendQueryParameter("filter[active]", "true") .build(); GlobalState.getInstance(mContext).getRequestQueue().add( new CustomJsonRequest(mContext, uri.toString(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { ULog.d(TAG, uri.toString()); ULog.d(TAG, response.toString()); recipes = NearUtils.parseList(morpheus, response, Recipe.class); persistList(recipes); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { ULog.d(TAG , "Error " + error.toString()); try { recipes = loadChachedList(); } catch (JSONException e) { e.printStackTrace(); } } })); */ Uri url = Uri.parse(Constants.API.RECIPES_PATH).buildUpon() .appendPath(EVALUATE_PATH).build(); HashMap<String, Object> map = new HashMap<>(); map.put("app_id", GlobalConfig.getInstance(mContext).getAppId()); map.put("installation_id", GlobalConfig.getInstance(mContext).getInstallationId()); JSONObject congregoObj = new JSONObject(); try { congregoObj.put("profile_id", GlobalConfig.getInstance(mContext).getProfileId()); } catch (JSONException e) { e.printStackTrace(); ULog.d(TAG, "profileId not present"); return; } map.put("congrego", congregoObj); String requestBody = null; try { requestBody = NearUtils.toJsonAPI("evaluates", map); } catch (JSONException e) { e.printStackTrace(); ULog.d(TAG, "Can't build request body"); } GlobalState.getInstance(mContext).getRequestQueue().add( new CustomJsonRequest(mContext, Request.Method.POST, url.toString(), requestBody, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { ULog.d(TAG, "Got recipes: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { ULog.d(TAG, "Error in downloading recipes: " + error.toString()); } }) ); } private void persistList(List<Recipe> recipes) { Gson gson = new Gson(); String listStringified = gson.toJson(recipes); ULog.d(TAG , "Persist: " + listStringified); editor.putString(TAG , listStringified); editor.apply(); } private List<Recipe> loadChachedList() throws JSONException { Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Recipe>>(){}.getType(); ArrayList<Recipe> recipes = gson.fromJson(sp.getString(TAG, ""), collectionType); return recipes; } /** * Tries to trigger a recipe, stating the plugin, action and bundle of the pulse. * If nothing matches, nothing happens. * * @param pulse_plugin the plugin of the pulse. * @param pulse_action the action of the pulse. * @param pulse_bundle the bundle of the pulse. */ public void gotPulse(String pulse_plugin, String pulse_action, String pulse_bundle){ List<Recipe> matchingRecipes = new ArrayList<>(); if (recipes == null) return; for (Recipe recipe : recipes){ if ( recipe.getPulse_plugin_id().equals(pulse_plugin) && recipe.getPulse_action().getId().equals(pulse_action) && recipe.getPulse_bundle().getId().equals(pulse_bundle) ) { matchingRecipes.add(recipe); } } if (matchingRecipes.isEmpty()){return;} Recipe winnerRecipe = matchingRecipes.get(0); gotRecipe(winnerRecipe); } /** * Tries to trigger a recipe. If no reaction plugin can handle the recipe, nothing happens. * * @param recipe the recipe to trigger. */ public void gotRecipe(Recipe recipe){ String stringRecipe = recipe.getName(); ULog.d(TAG , stringRecipe); Reaction reaction = reactions.get(recipe.getReaction_plugin_id()); reaction.handleReaction(recipe); } /** * Process a recipe from it's id. Typically called for processing a push recipe. * @param id push id. * @return true if the recipe was found, false otherwise. */ public boolean processRecipe(final String id) { // TODO use new evaluation endpoint for single recipes Uri uri = Uri.parse(Constants.API.RECIPES_PATH).buildUpon() .appendEncodedPath(id) .build(); GlobalState.getInstance(mContext).getRequestQueue().add(new CustomJsonRequest( mContext, uri.toString(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { ULog.d(TAG, response.toString()); Recipe recipe = NearUtils.parseElement(morpheus, response, Recipe.class); ULog.d(TAG, recipe.toString()); String reactionPluginName = recipe.getReaction_plugin_id(); Reaction reaction = reactions.get(reactionPluginName); reaction.handlePushReaction(recipe, id, recipe.getReaction_bundle().getId()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } )); // inside receiver, parse the response to know what reaction plugin to use // than fire the reaction // if we got a network error, return false return true; } }
package au.edu.unimelb.boldapp; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Scanner; import java.util.UUID; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import android.os.Environment; import android.util.Log; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Abstract class that offers various File IO related methods. * * @author Oliver Adams <oliver.adams@gmail.com> * @author Florian Hanke <florian.hanke@gmail.com> */ public abstract class FileIO { /** * The images directory path */ static final String imagesPath = "images/"; /** * The application's top level path in the external storage. */ static final String appRootPath = "bold/"; /** * The users directory path */ static final String usersPath = "users/"; /** * The recordings directory path */ static final String recordingsPath = "recordings/"; /** * Returns the absolute path to the application's data. * * @return A string representation of the absolute path to the * application's data */ public static String getAppRootPath(){ File external = Environment.getExternalStorageDirectory(); String path = external.getAbsolutePath() + "/" + appRootPath; return path; } /** * Returns the relative path to the application's users directory and * ensures the directory exists. * * @return A string representation of the relative path to the * application's users directory */ public static String getUsersPath(){ File file = new File(getAppRootPath() + usersPath); file.mkdirs(); return usersPath; } /** * Returns the relative path to the application's images directory and * ensures the directory exists. * * @return A string representation of the relative path to the * application's images directory */ public static String getImagesPath(){ File file = new File(getAppRootPath() + imagesPath); file.mkdirs(); return imagesPath; } /** * Returns the relative path to the application's recordings directory, and * ensures the directory exists. * * @return A string representation of the relative path to the * application's recordings directory */ public static String getRecordingsPath(){ File file = new File(getAppRootPath() + recordingsPath); file.mkdirs(); return recordingsPath; } /** * Takes a file path and some data and writes the data into the file in the * bold directory in external storage. * * @param filePath The filename, including parent paths within the bold * dir. * @param data The data that is to be written to the file. */ public static void write(String filePath, String data) { try { String absPath = getAppRootPath() + filePath; File file = new File(absPath); file.getParentFile().mkdirs(); BufferedWriter bos = new BufferedWriter(new FileWriter(absPath)); bos.write(data); bos.flush(); bos.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Takes a file path relative to the bold directory in external storage and * returns a string containing the file's contents. * * @param filePath The filename, including parent paths within the * bold dir. * @return A string containing the file's contents. */ public static String read(String filePath) { String path = getAppRootPath() + filePath; StringBuilder text = new StringBuilder(); String newLine = System.getProperty("line.separator"); try { Scanner scanner = new Scanner(new FileInputStream(path)); while (scanner.hasNextLine()){ text.append(scanner.nextLine() + newLine); } scanner.close(); } catch (Exception e) { e.printStackTrace(); } return text.toString(); } /** * Method to load all the users from the users directory into an array of * User objects in GlobalState. */ public static void loadUsers() { // Get an array of all the UUIDs from the "users" directory File dir = new File(getAppRootPath() + getUsersPath()); List<String> userUuids = Arrays.asList(dir.list()); // Get the user data from the metadata.json files List<User> users = new ArrayList<User>(); JSONParser parser = new JSONParser(); for (String userUuid : userUuids) { String jsonStr = read(getUsersPath() + userUuid + "/metadata.json"); try { Object obj = parser.parse(jsonStr); JSONObject jsonObj = (JSONObject) obj; users.add( new User( UUID.fromString(jsonObj.get("uuid").toString()), jsonObj.get("name").toString())); } catch (Exception e) { e.printStackTrace(); } } User[] usersArray = new User[users.size()]; GlobalState.setUsers(users.toArray(usersArray)); } /** * Method to load all the recordings from the recordings directory into an * array of Recording objects. * * @return An array of all the recordings as Recording objects. */ public static void loadRecordings() { //Get an array of all the UUIDs from the "recordings" directory File dir = new File(getAppRootPath() + getRecordingsPath()); JSONFilenameFilter fnf = new JSONFilenameFilter(); String[] recordingUuids = dir.list(fnf); /* for (int i = 0; i < recordingUuids.length; i++) { recordingUuids[i] = recordingUuids[i].replace(".json", ""); } */ Recording[] recordings = new Recording[recordingUuids.length]; JSONParser parser = new JSONParser(); for (int i=0; i < recordingUuids.length; i++) { String jsonStr = read(getRecordingsPath() + recordingUuids[i]); try { Object obj = parser.parse(jsonStr); JSONObject jsonObj = (JSONObject) obj; UUID originalUUID = null; if (jsonObj.containsKey("originalUUID")) { originalUUID = UUID.fromString( jsonObj.get("originalUUID").toString()); } recordings[i] = new Recording( UUID.fromString(jsonObj.get("uuid").toString()), GlobalState.getUserMap().get(UUID.fromString( jsonObj.get("creatorUUID").toString())), jsonObj.get("recording_name").toString(), new StandardDateFormat().parse( jsonObj.get("date_string").toString()), originalUUID); } catch (Exception e) { e.printStackTrace(); } } GlobalState.setRecordings(recordings); } /** * Delete the filename supplied as an argument * * @param fileName Name of the file to be deleted. */ public static boolean delete(String fileName) { File file = new File(getAppRootPath() + fileName); return file.delete(); } }
package com.wxd.download; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.wxd.bean.Position; /** * @author Administrator * <ul> * <li>comment:</li> * <li>param type: street, satellite</li> * <ul> */ public class MapDownloader { private static int downloadImgNum = 0; private static int failedImgNum = 0; private List<Position> cityList = new ArrayList<Position>(); public static void main(String[] args) { MapDownloader mk = new MapDownloader(); mk.start("", 3, 19, "D:/map/baidu", "street"); } private void start(String cityName, int startLevel, int endLevel, String fileURL, String type) { prepareList(); List<Position> cpList = new ArrayList<Position>(); for (Position p : cityList) { if (p.getNaem().equals(cityName)) { cpList.add(p); } } System.out.println("" + cpList.size()); for (Position p : cpList) { getImgToDownload(p, startLevel, endLevel, fileURL, type); } } private void getImgToDownload(Position p, int startLevel, int endLevel, String fileURL, String type) { checkFolder(fileURL); for (int i = startLevel; i < endLevel; i++) { int startBlockX = getBlockNum(p.getSwlng(), i); int startBlockY = getBlockNum(p.getSwlat(), i); int endBlockX = getBlockNum(p.getNelng(), i); int endBlockY = getBlockNum(p.getNelat(), i); if (startBlockX == endBlockX && startBlockY == endBlockY) { makeImg(startBlockX, endBlockX, i, fileURL, type); } else if (startBlockX == endBlockX && startBlockY < endBlockY) { for (int j = startBlockY; j < endBlockY; j++) { makeImg(startBlockX, j, i, fileURL, type); } } else if (startBlockX < endBlockX && startBlockY == endBlockY) { for (int j = startBlockX; j < endBlockX; j++) { makeImg(j, startBlockY, i, fileURL, type); } } else if (startBlockX < endBlockX && startBlockY < endBlockY) { for (int j = startBlockY; j < endBlockY; j++) { for (int k = startBlockX; k < endBlockX; k++) { makeImg(k, j, i, fileURL, type); } } } } System.out.println(" " + downloadImgNum + " " + failedImgNum + " "); } private void checkFolder(String fileURL) { Path path = Paths.get(fileURL); if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { System.out.println(""); } else { System.out.println(""); try { Files.createDirectories(path); } catch (IOException e) { e.printStackTrace(); } } } private int getBlockNum(double num, int level) { int mercator = (int) ((num / Math.pow(2, Math.abs(level - 18))) / 256); return (int) Math.ceil(mercator); } private void makeImg(int x, int y, int level, String fileURL, String type) { try { testFileURL(fileURL); fileURL = fileURL + "/" + type; testFileURL(fileURL); fileURL = fileURL + "/" + level; testFileURL(fileURL); fileURL = fileURL + "/" + x; testFileURL(fileURL); fileURL = fileURL + "/" + y + ".png"; if (new File(fileURL).exists()) { System.out.println(""); return; } else { int server = new Random().nextInt(3) + 1; String url = null; if (type == "street" || type.equals("street")) { // ";v=014;type=web&fm=44"; url = "http://or" + server + ".map.bdimg.com:8080/tile/?qt=tile&x=" + x + "&y=" + y + "&z=" + level + "&styles=pl&udt=20130822"; } else if (type == "satellite" || type.equals("satellite")) { url = "http://q" + server + ".baidu.com/it/u=x=" + x + ";y=" + y + ";z=" + level + ";v=009;type=sate&fm=46"; } System.out.println(url); download(url, fileURL); if (new File(fileURL).exists()) { System.out.println(""); downloadImgNum++; } else { System.out.println(""); failedImgNum++; } } } catch (Exception e) { e.printStackTrace(); } } public void testFileURL(String url) { if (!(new File(url).isDirectory())) { new File(url).mkdir(); } } public void download(String url, String fileURL) { try { URL website = new URL(url); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(fileURL); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); } } private void prepareList() { cityList.add(new Position("", 12849780.03, 4758298.57, 13081648.69, 4993877.7)); cityList.add(new Position("", 13454484.1, 3568800.28, 13581796.02, 3723920.55)); cityList.add(new Position("", 12992707.8, 4632155.37, 13144152.71, 4875788.48)); cityList.add(new Position("", 11721675.29, 3249611.73, 12268313.26, 3767557.48)); cityList.add(new Position("", 12789537.39, 3405435.24, 13320133.59, 4092816.99)); cityList.add(new Position("", 12990475.48, 3676579.19, 13123586.88, 3811319.65)); cityList.add(new Position("", 12887481.9, 3454898.21, 13107862.27, 3646083.88)); cityList.add(new Position("", 12995822.55, 3834584.01, 13144929.84, 3939289.58)); cityList.add(new Position("", 12863348.24, 3854078.13, 13006628.34, 4014765.32)); cityList.add(new Position("", 13028829.69, 3603211.52, 13192759, 3748793.1)); cityList.add(new Position("", 12986120.06, 3426931.13, 13151204.87, 3591348.77)); cityList.add(new Position("", 13053067.1, 3535823.22, 13061768.15, 3545996.32)); cityList.add(new Position("", 13043184.39, 3721827.62, 13273474.97, 3901278.64)); cityList.add(new Position("", 12789537.38, 3794153.77, 12984610.55, 3950009.09)); cityList.add(new Position("", 12957826.12, 3909503.2, 13026290.91, 4019732.4)); cityList.add(new Position("", 13020083.78, 4021565.76, 13031750.41, 4038753.9)); cityList.add(new Position("", 12954547.28, 3791875.17, 13049194.48, 3873101.6)); cityList.add(new Position("", 12843917.55, 3612450.62, 13053613.58, 3827971.98)); cityList.add(new Position("", 12931647.28, 3908884.14, 13157442.73, 4092816.99)); cityList.add(new Position("", 13103319.94, 3578779.17, 13154980.09, 3627862.46)); cityList.add(new Position("", 13053028.36, 3535885.51, 13061746.78, 3545874.59)); cityList.add(new Position("", 13133024.87, 3564652.97, 13218213.7, 3679856.86)); cityList.add(new Position("", 13133269.55, 3475589.48, 13320133.59, 3650783.12)); cityList.add(new Position("", 12897454.35, 2683181.03, 13407473.04, 3267816.61)); cityList.add(new Position("", 13179389.05, 2883610.35, 13418530.19, 3059849.59)); cityList.add(new Position("", 12897615.32, 2781549.12, 13109090.81, 2985037.64)); cityList.add(new Position("", 13025619.21, 3012367.26, 13278487.07, 3268738.49)); cityList.add(new Position("", 13197601.45, 3016950.32, 13442670.19, 3188800.6)); cityList.add(new Position("", 13186983.57, 2850832.02, 13328047.05, 2950379.38)); cityList.add(new Position("", 13089640.52, 2773176.15, 13255318.23, 2972531.17)); cityList.add(new Position("", 12956588.01, 2916694.44, 13211358.35, 3120762.57)); cityList.add(new Position("", 13123882.32, 2783184.25, 13187098.46, 2846886.47)); cityList.add(new Position("", 13014083.93, 2682034.37, 13163863.93, 2882029.41)); cityList.add(new Position("", 10278113.51, 3819147.66, 12102965.62, 5252506.82)); cityList.add(new Position("", 11788465.15, 4195802.26, 11807156.12, 4206259.08)); cityList.add(new Position("", 11422342.5, 4217541.74, 11642252.76, 4418836.3)); cityList.add(new Position("", 11501528.14, 4396344.48, 11533947.96, 4416771.5)); cityList.add(new Position("", 11528560.04, 4195845.91, 11747728.12, 4502894.7)); cityList.add(new Position("", 11518748.23, 4022153.92, 11761521.87, 4282042.76)); cityList.add(new Position("", 11217907.82, 3886255.46, 11662869.69, 4220654.41)); cityList.add(new Position("", 11290711.56, 4557009.66, 11437171.08, 4695275.95)); cityList.add(new Position("", 10278113.51, 4568365.95, 11155247.73, 5252506.82)); cityList.add(new Position("", 11431805.09, 4132017.83, 11562370.36, 4304956.62)); cityList.add(new Position("", 11580714.01, 3819147.66, 11865719.16, 4076954.54)); cityList.add(new Position("", 11727845.47, 4124154.82, 12008123.16, 4241838.57)); cityList.add(new Position("", 11788465.15, 4195802.26, 11807156.12, 4206259.08)); cityList.add(new Position("", 11841053.16, 4172671.15, 12103001.35, 4436112.37)); cityList.add(new Position("", 11642375.88, 4015763.83, 11880236.27, 4164018.38)); cityList.add(new Position("", 11336774.84, 4380067.5, 11601054.41, 4761251.56)); cityList.add(new Position("", 10842020.78, 4498627.15, 11379407.22, 4822272.6)); cityList.add(new Position("", 12204811.93, 2266035.52, 13065234.46, 2921500.05)); cityList.add(new Position("", 12639267.13, 2508287.37, 12647878.56, 2521703.55)); cityList.add(new Position("", 12954958.72, 2303357.52, 13056457.16, 2380870)); cityList.add(new Position("", 12575735.07, 2557788.85, 12697886.49, 2728067.86)); cityList.add(new Position("", 12954894.83, 2667280.35, 13048076.49, 2764816.4)); cityList.add(new Position("", 12638089.8, 2574520.97, 12720118.91, 2633102.76)); cityList.add(new Position("", 12512172.62, 2573265.14, 12623566.9, 2684829.08)); cityList.add(new Position("", 12718215.32, 2635737.98, 12868594.57, 2831558.65)); cityList.add(new Position("", 12670519.19, 2540804.77, 12849216.97, 2731644.27)); cityList.add(new Position("", 12469151.17, 2429749.14, 12609270.87, 2598244.64)); cityList.add(new Position("", 12870889.44, 2597546.79, 12984731.22, 2709125.25)); cityList.add(new Position("", 12282216, 2417360.91, 12433414.56, 2580478.42)); cityList.add(new Position("", 12837695.5, 2660848.7, 13018737.14, 2850589.3)); cityList.add(new Position("", 12460642.6, 2670650.76, 12681969.64, 2882964.54)); cityList.add(new Position("", 12941785.81, 2620828.27, 13065234.46, 2693730.75)); cityList.add(new Position("", 12793512.76, 2569238.56, 12939239.8, 2672747.62)); cityList.add(new Position("", 12563536.99, 2723059.75, 12774252.39, 2921545.56)); cityList.add(new Position("", 12655329.26, 2524065.96, 12763882.42, 2598086.93)); cityList.add(new Position("", 12388729.2, 2432521.57, 12509767.64, 2577300.64)); cityList.add(new Position("", 12363611.58, 2541024.52, 12526651.32, 2654892.41)); cityList.add(new Position("", 12204811.93, 2266035.52, 12366346.39, 2486371.49)); cityList.add(new Position("", 12397611.15, 2588200.85, 12566766.07, 2785085.04)); cityList.add(new Position("", 12597605.13, 2517097.58, 12657143.12, 2589122.78)); cityList.add(new Position("", 12586773.18, 2469841.91, 12737069.71, 2550399.13)); cityList.add(new Position("", 12639267.13, 2508287.37, 12647878.56, 2521703.55)); cityList.add(new Position("", 11628199.97, 2361555.36, 12475525.4, 3028485.6)); cityList.add(new Position("", 11948723.55, 2520266.1, 12203721.99, 2740475.24)); cityList.add(new Position("", 11628281.68, 2598432.13, 12010475.04, 2870371.72)); cityList.add(new Position("", 11863081.97, 2447799.58, 12035866.62, 2658625.86)); cityList.add(new Position("", 11966009.99, 2434092.83, 12090967.59, 2540756.29)); cityList.add(new Position("", 12203513.59, 2767363.85, 12412145.62, 3028460.26)); cityList.add(new Position("", 12157883.91, 2574247.99, 12319764.58, 2741746.95)); cityList.add(new Position("", 11864284.79, 2682529.8, 12152497.77, 2933018.53)); cityList.add(new Position("", 12309542.89, 2694512.71, 12475525.4, 2876770.74)); cityList.add(new Position("", 12069942.89, 2648285.66, 12297046.92, 2793323.49)); cityList.add(new Position("", 12088774.01, 2725212.58, 12265781.27, 2987215.34)); cityList.add(new Position("", 12043831.73, 2436918.66, 12231590.35, 2577726.62)); cityList.add(new Position("", 12282248.95, 2568690.63, 12431555.05, 2785670.59)); cityList.add(new Position("", 12194910.29, 2452521.12, 12346063.76, 2630903.18)); cityList.add(new Position("", 11533824.17, 2811720.2, 12196978.62, 3383484.41)); cityList.add(new Position("", 12194978.86, 3069800.37, 12200958.78, 3075203.89)); cityList.add(new Position("", 11814609.16, 3003588.79, 11943156.07, 3148864.35)); cityList.add(new Position("", 11717065.62, 2901507.82, 11864290.81, 3057891.29)); cityList.add(new Position("", 11533784.43, 3025022.84, 11881631.57, 3201435.83)); cityList.add(new Position("", 11644468.6, 3071056.9, 11656455.83, 3086864.52)); cityList.add(new Position("", 11612424.93, 2897648.89, 11769719.19, 3094721.5)); cityList.add(new Position("", 11644468.6, 3071056.9, 11656455.83, 3086864.52)); cityList.add(new Position("", 11995889.13, 3119682.92, 12187511.24, 3366386.06)); cityList.add(new Position("", 11757167.01, 3121156.11, 12047262.41, 3383484.41)); cityList.add(new Position("", 12015598.57, 3122722.29, 12018716.22, 3125413.85)); cityList.add(new Position("", 11637014.34, 2811713.26, 11859899.87, 3002420.55)); cityList.add(new Position("", 11945318.81, 2895734.08, 12196978.62, 3170377.47)); cityList.add(new Position("", 12015502.84, 3122698.53, 12018716.22, 3125331.83)); cityList.add(new Position("", 12194978.86, 3069800.37, 12200958.78, 3075203.89)); cityList.add(new Position("", 11824220.14, 2865341.08, 12057171.4, 3164964.42)); cityList.add(new Position("", 12409700.35, 906066.21, 12992596.92, 1317151.37)); cityList.add(new Position("", 13068767.78, 1671999.42, 13143805.06, 1712911.09)); cityList.add(new Position("", 12087085.28, 2038411.14, 12392639.68, 2288276.92)); cityList.add(new Position("", 12641328.9, 1704958.81, 12815778.01, 1837117.15)); cityList.add(new Position("", 12333087, 1743353.48, 12592970.63, 1947438.9)); cityList.add(new Position("", 12449748.09, 397609.14, 12531830.18, 463341.68)); cityList.add(new Position("", 12253739.05, 2202961.89, 12324943.33, 2280172.7)); cityList.add(new Position("", 12122660.37, 2162581.61, 12219905.46, 2253222.1)); cityList.add(new Position("", 12215429.36, 2185324.39, 12275148.24, 2269522.45)); cityList.add(new Position("", 12087085.28, 2108210.16, 12148675.24, 2184688.31)); cityList.add(new Position("", 12259795.67, 2166388.23, 12307463.86, 2227020.45)); cityList.add(new Position("", 12259376.55, 2138803.45, 12326339.18, 2196983.39)); cityList.add(new Position("", 12189689.57, 2208796.43, 12234541.01, 2263628.19)); cityList.add(new Position("", 12127107.74, 2038411.14, 12224936.37, 2097570.2)); cityList.add(new Position("", 12226179.05, 2156934.88, 12274133.78, 2211123.69)); cityList.add(new Position("", 12247415.14, 2091636.82, 12314403.93, 2153852.07)); cityList.add(new Position("", 12297525.49, 2178586.52, 12392639.68, 2288276.92)); cityList.add(new Position("", 12631437.27, 4282909.93, 13343965.35, 5225650.87)); cityList.add(new Position("", 12998148.26, 4784262.48, 13054191.55, 4853107.22)); cityList.add(new Position("", 12638208.02, 4475092.94, 12856434.67, 4661831.99)); cityList.add(new Position("", 12665350.79, 4587220.42, 12951186.4, 4832225.52)); cityList.add(new Position("", 12880793.64, 4479580.82, 13131370.2, 4687632.8)); cityList.add(new Position("", 12903726.26, 4867013.14, 13276059.06, 5225650.87)); cityList.add(new Position("", 12631434.94, 4282892.66, 12856439.79, 4417106.37)); cityList.add(new Position("", 12823909.32, 4422243.11, 12976825.23, 4605899.62)); cityList.add(new Position("", 12926947.09, 4620516.76, 13017224.96, 4784803.31)); cityList.add(new Position("", 12998148.26, 4784262.48, 13054191.55, 4853107.22)); cityList.add(new Position("", 13199886.31, 4756823.91, 13343965.35, 4928255.69)); cityList.add(new Position("", 13082245.15, 4681171.61, 13297827.38, 4906608.95)); cityList.add(new Position("", 12664646.24, 4379902.73, 12897564.22, 4526506.53)); cityList.add(new Position("", 12671878.53, 4775095.47, 12965762.95, 5155301.95)); cityList.add(new Position("", 12286071.03, 3660864.94, 12986309.64, 4326464.96)); cityList.add(new Position("", 12856585.84, 4261694.17, 12859146.11, 4264857.81)); cityList.add(new Position("", 12548946.52, 4040531.51, 12716120.05, 4138411.12)); cityList.add(new Position("", 12650465.99, 4167705.33, 12801376.56, 4326464.96)); cityList.add(new Position("", 12690831.99, 4200001.14, 12775652.69, 4282718.42)); cityList.add(new Position("", 12531944.95, 4114483.34, 12651968.71, 4207089.96)); cityList.add(new Position("", 12677610.65, 4031891.71, 12832121, 4142988.38)); cityList.add(new Position("", 12372854.09, 3947204.6, 12578234.88, 4149589.96)); cityList.add(new Position("", 12631364.58, 3926163.84, 12724151.05, 4003454.4)); cityList.add(new Position("", 12355412.58, 3776444.18, 12670661.23, 3979040.78)); cityList.add(new Position("", 12496474.73, 3889600.05, 12656614.68, 4051815.54)); cityList.add(new Position("", 12788646.71, 4184766.32, 12926227.74, 4304932.16)); cityList.add(new Position("", 12856585.84, 4261694.17, 12859146.11, 4264857.81)); cityList.add(new Position("", 12286071.03, 3945519.42, 12472112.08, 4151313.03)); cityList.add(new Position("", 12783323.68, 3966379.07, 12986309.64, 4121107.78)); cityList.add(new Position("", 12622490.21, 4123393.18, 12804700.93, 4254081.03)); cityList.add(new Position("", 12659024.55, 3660864.94, 12907666.35, 3827787.61)); cityList.add(new Position("", 12587257.09, 3964004.12, 12727459.95, 4059964.81)); cityList.add(new Position("", 12701552.95, 3879639.11, 12875316.22, 4050620.69)); cityList.add(new Position("", 12590848.41, 3777478.93, 12827034.2, 3942889.5)); cityList.add(new Position("", 13490905.67, 5348409.52, 15039836.95, 7054232.57)); cityList.add(new Position("", 13992514.64, 5445872.94, 14499195.16, 5858675.06)); cityList.add(new Position("", 13777265.82, 5652172.63, 14003866.46, 5989382.85)); cityList.add(new Position("", 13490853.8, 6571823.47, 14141757.63, 7054232.57)); cityList.add(new Position("", 14436077.55, 5921386.98, 14753490.16, 6134632.14)); cityList.add(new Position("", 13887889.21, 6007483.38, 14420950.4, 6589484.39)); cityList.add(new Position("", 14516958.27, 5569834.63, 14912075.52, 5848536.94)); cityList.add(new Position("", 14417610.78, 5741589.43, 15039836.95, 6153248.05)); cityList.add(new Position("", 14275523.93, 5348409.52, 14619689.58, 5748261.41)); cityList.add(new Position("", 14484081.26, 5684727.64, 14687887.09, 5804083)); cityList.add(new Position("", 13626428.72, 5786139.27, 14102308.03, 6232466.29)); cityList.add(new Position("", 13901920.74, 5671485.76, 14311629.24, 6091903.49)); cityList.add(new Position("", 14208755.89, 5827777.76, 14558968.25, 6318269.04)); cityList.add(new Position("", 12064304.05, 3359266.14, 12929154.47, 3908479.94)); cityList.add(new Position("", 12657945.07, 3478449.47, 12811591.57, 3658063.61)); cityList.add(new Position("", 12747618.35, 3484832.76, 12812749.87, 3561573.36)); cityList.add(new Position("", 12064304.05, 3369959.41, 12317540.06, 3662709.24)); cityList.add(new Position("", 12736044.23, 3447125.6, 12929154.47, 3689644.64)); cityList.add(new Position("", 12750480.29, 3419830.74, 12859489.09, 3524955.96)); cityList.add(new Position("", 12453082.36, 3532771.45, 12634540.12, 3690476.09)); cityList.add(new Position("", 12384453.26, 3409727.23, 12701228.9, 3567254.97)); cityList.add(new Position("", 12524632.52, 3492647.35, 12583690.15, 3565691.31)); cityList.add(new Position("", 12239344.5, 3649696.82, 12355288.91, 3723091.34)); cityList.add(new Position("", 12183159.83, 3676978.08, 12422480.63, 3908479.94)); cityList.add(new Position("", 12367133.32, 3741056.42, 12373714.6, 3747368.35)); cityList.add(new Position("", 12549669.99, 3653567.47, 12706259.03, 3797789.86)); cityList.add(new Position("", 12534612.31, 3531153.72, 12631998, 3598956.38)); cityList.add(new Position("", 12573389.21, 3491702.39, 12671806.84, 3551001.39)); cityList.add(new Position("", 12639828.07, 3359266.14, 12799671.24, 3520884.76)); cityList.add(new Position("", 12331054.95, 3641093.03, 12593184.7, 3823455.32)); cityList.add(new Position("", 12367316.11, 3741070.66, 12373714.6, 3747368.35)); cityList.add(new Position("", 12615222.41, 3531572.81, 12757176.34, 3722128.5)); cityList.add(new Position("", 12274457.17, 3475774.83, 12478018.53, 3685686.18)); cityList.add(new Position("", 12111403.17, 2813884.72, 12720365.37, 3498932.17)); cityList.add(new Position("", 12194953.92, 3069800.37, 12200958.78, 3075203.89)); cityList.add(new Position("", 12457143.79, 3210426.01, 12720365.37, 3312691.71)); cityList.add(new Position("", 12300724.95, 3280400.71, 12502694.66, 3498932.17)); cityList.add(new Position("", 12494256.33, 2845105.02, 12717684.33, 3084766.55)); cityList.add(new Position("", 12417843.8, 2995041.87, 12611538.14, 3162763.26)); cityList.add(new Position("", 12111403.17, 2964391.48, 12369899.08, 3358151.3)); cityList.add(new Position("", 12194953.92, 3069800.37, 12200958.78, 3075203.89)); cityList.add(new Position("", 12331934.94, 3130279.23, 12526991.85, 3258868.42)); cityList.add(new Position("", 12226234.04, 2976269.45, 12478773.73, 3187238.32)); cityList.add(new Position("", 12468613.61, 3146766.51, 12590127.72, 3238741.09)); cityList.add(new Position("", 12155458.56, 3194433.71, 12289473.66, 3435962.1)); cityList.add(new Position("", 12326280.74, 3226294.29, 12574413.25, 3422112.88)); cityList.add(new Position("", 12351927.25, 2813884.72, 12519530.02, 3088178.95)); cityList.add(new Position("", 12503731.28, 3282522.94, 12708729.24, 3463189.32)); cityList.add(new Position("", 12211924.65, 3338800.11, 12394889.47, 3456041.42)); cityList.add(new Position("", 12576262.28, 2986577.47, 12703067.36, 3233085.72)); cityList.add(new Position("", 12954229.79, 3580106.02, 13581761.74, 4156572.87)); cityList.add(new Position("", 13176967.94, 3640988.49, 13274663.76, 3821558.1)); cityList.add(new Position("", 13263571.77, 3631026.63, 13381681.92, 3748957.02)); cityList.add(new Position("", 13161063.21, 3835201.33, 13319697, 4017866.03)); cityList.add(new Position("", 13182036.81, 4002740.8, 13342598.45, 4156579.51)); cityList.add(new Position("", 13381735.13, 3690921.36, 13581761.74, 3834536.61)); cityList.add(new Position("", 13350152.45, 3580106.02, 13513616.32, 3745748.53)); cityList.add(new Position("", 13129948.41, 3890776.84, 13267507.85, 4062067.28)); cityList.add(new Position("", 13320019.83, 3731702.32, 13421453.25, 3901551.07)); cityList.add(new Position("", 13305727.03, 3626875, 13426468.91, 3739356.22)); cityList.add(new Position("", 12954229.79, 3966916.13, 13211616.5, 4131844.11)); cityList.add(new Position("", 13299029.64, 3816627.93, 13469968.81, 4078509.68)); cityList.add(new Position("", 13249831.34, 3769769.55, 13349388.79, 3927706.65)); cityList.add(new Position("", 13244692.56, 3692354.72, 13357140.83, 3782655.36)); cityList.add(new Position("", 12644109.24, 2795594.61, 13190753.56, 3492343.75)); cityList.add(new Position("", 12851431.58, 3249211.17, 12976882.33, 3377512.18)); cityList.add(new Position("", 12868493.37, 3042033.62, 13059017.09, 3291486.29)); cityList.add(new Position("", 12681670.07, 2795594.61, 12985640.71, 3122470.32)); cityList.add(new Position("", 12672878.63, 2977517.45, 12906722.57, 3224668.71)); cityList.add(new Position("", 13021139.66, 3319860.68, 13104348.55, 3473993.97)); cityList.add(new Position("", 12684843.6, 3315729.07, 13014559.83, 3492315.08)); cityList.add(new Position("", 12644109.24, 3099508.61, 12721927.98, 3230152.95)); cityList.add(new Position("", 12940169.55, 3204487.01, 13190753.56, 3444248.34)); cityList.add(new Position("", 12745423.33, 3170682.15, 12847858.86, 3243010.24)); cityList.add(new Position("", 12679007.17, 3172639.93, 12930604.09, 3368121.15)); cityList.add(new Position("", 12991006.37, 3210245.04, 13077868.25, 3308488.31)); cityList.add(new Position("", 13988293.58, 5217424.68, 14251713.32, 5536780.59)); cityList.add(new Position("", 13865002.46, 5323590.1, 14148960.42, 5631617.95)); cityList.add(new Position("", 13542049.63, 5471532.33, 13845684.75, 5799148.39)); cityList.add(new Position("", 14040572.68, 5038501, 14285212.28, 5256385.39)); cityList.add(new Position("", 13988293.58, 5217424.68, 14251713.32, 5536780.59)); cityList.add(new Position("", 13898007.04, 5177774.69, 14009745.42, 5318881.11)); cityList.add(new Position("", 13727238.63, 5256509.4, 14003110.59, 5460508.1)); cityList.add(new Position("", 13705386.94, 5435075.22, 14048737.16, 5677439.9)); cityList.add(new Position("", 13945197.78, 4964607.5, 14111100.13, 5286862.28)); cityList.add(new Position("", 14190662.04, 5132787.01, 14619263.22, 5516016.73)); cityList.add(new Position("", 13230751.64, 4649616.17, 14003844.2, 5358417.45)); cityList.add(new Position("", 13629240.68, 5014350.49, 13783739.01, 5290030.79)); cityList.add(new Position("", 13602737.12, 4839186.88, 13778710.77, 5068827.09)); cityList.add(new Position("", 13758769.44, 4958008.42, 14003897.3, 5068945.98)); cityList.add(new Position("", 13230762.11, 4926403.23, 13503991.65, 5190367.65)); cityList.add(new Position("", 13461674.64, 4649616.17, 13752706.03, 4868678.34)); cityList.add(new Position("", 13735472.36, 4793832.22, 13995107.19, 5008148.16)); cityList.add(new Position("", 13767731.54, 5020112.9, 13970313.73, 5204489.64)); cityList.add(new Position("", 13472755.95, 5087291.92, 13690558.91, 5259786.15)); cityList.add(new Position("", 13272022.46, 4832466.51, 13481796.08, 5015274.26)); cityList.add(new Position("", 13439072.08, 4945280.94, 13648679.73, 5152410.72)); cityList.add(new Position("", 13647649.45, 4942125.61, 13769836.06, 5075223.29)); cityList.add(new Position("", 13523527.43, 4932035.47, 13628658.48, 5051560.31)); cityList.add(new Position("", 13743698.96, 5131040.1, 13928017.54, 5358417.45)); cityList.add(new Position("", 13566201.77, 4827542.52, 13693972.67, 4976093.77)); cityList.add(new Position("", 10818075.47, 4470447.78, 14035610.67, 7011774.18)); cityList.add(new Position("", 12303730.61, 4779716.47, 12503025.73, 5041774.5)); cityList.add(new Position("", 10818075.47, 4470447.78, 11897603.97, 5252506.82)); cityList.add(new Position("", 12163058.54, 4874987.92, 12406921.79, 5243579.34)); cityList.add(new Position("", 11711601.44, 4863791.7, 12235396.29, 5202571.45)); cityList.add(new Position("", 12954916.87, 5026938.58, 13469044.85, 5630202.23)); cityList.add(new Position("", 11853705.76, 4500035.24, 12408879.03, 4967758.89)); cityList.add(new Position("", 12861487.29, 5927337.76, 14035610.67, 7011774.18)); cityList.add(new Position("", 13274418.97, 5169712.46, 13773350.23, 5700327.86)); cityList.add(new Position("", 11866502.75, 4700672.48, 11932190.2, 4825259.97)); cityList.add(new Position("", 12283628.32, 4862833.96, 12781569.27, 5341253.52)); cityList.add(new Position("", 12374482.82, 5069933.32, 13372922.1, 5875332.68)); cityList.add(new Position("", 13301627.53, 5476186.93, 13764825.85, 6019170.77)); cityList.add(new Position("", 11610753.23, 4172214.01, 11985178.85, 4751391.87)); cityList.add(new Position("", 11788465.15, 4195802.26, 11807246.18, 4206340.75)); cityList.add(new Position("", 11782747.28, 4482018.56, 11897627.01, 4676676.53)); cityList.add(new Position("", 11725584.99, 4172214.01, 11907388.28, 4363021.99)); cityList.add(new Position("", 11788465.15, 4195802.26, 11807246.18, 4206340.75)); cityList.add(new Position("", 11799171.31, 4640913, 11910724.23, 4751391.87)); cityList.add(new Position("", 11755581.24, 4354781.37, 11985178.85, 4590714.83)); cityList.add(new Position("", 11610753.23, 4292753.59, 11819203.69, 4519083.94)); cityList.add(new Position("", 9953867.03, 3689099.52, 11474926.83, 4727046.71)); cityList.add(new Position("", 11233421.36, 4307806.06, 11345918.61, 4470356.51)); cityList.add(new Position("", 10796510.09, 3808461.06, 11330738.92, 4218993.78)); cityList.add(new Position("", 11318357.5, 4200793.44, 11474926.83, 4434559.82)); cityList.add(new Position("", 10920558.31, 4377248.76, 11426912.66, 4708314.46)); cityList.add(new Position("", 11013940.57, 4091466.6, 11333079.66, 4447004.57)); cityList.add(new Position("", 10039145.37, 4140832.85, 11108882.99, 4727046.71)); cityList.add(new Position("", 9979513.54, 3835795.38, 10343970.95, 4132361.76)); cityList.add(new Position("", 11209243.28, 4014246.3, 11406266.12, 4299398.15)); cityList.add(new Position("", 9953867.03, 3689099.52, 10885226.68, 4314088.37)); cityList.add(new Position("", 12782933.17, 4056085.99, 13662686.76, 4618802.14)); cityList.add(new Position("", 12856585.84, 4261694.17, 12859146.11, 4264857.81)); cityList.add(new Position("", 12938853.51, 4280134.29, 13108451.71, 4489105.12)); cityList.add(new Position("", 13054690.05, 4370783.44, 13178864.17, 4597271.11)); cityList.add(new Position("", 13148336.36, 4405399.59, 13283347, 4576679.93)); cityList.add(new Position("", 12887067.45, 4332222.43, 13092839.99, 4555071.15)); cityList.add(new Position("", 12782933.17, 4079359.18, 12960004.89, 4257385.35)); cityList.add(new Position("", 12899189.05, 4065886.5, 13091751.72, 4273574.83)); cityList.add(new Position("", 13062131.73, 4274781.58, 13133741.44, 4352121.98)); cityList.add(new Position("", 12833962.58, 4245857.82, 12974662.26, 4417147.88)); cityList.add(new Position("", 12856585.84, 4261694.17, 12859146.11, 4264857.81)); cityList.add(new Position("", 13071928.5, 4056085.99, 13270518.63, 4304452.48)); cityList.add(new Position("", 13304995.87, 4211575.51, 13515784.63, 4434367.2)); cityList.add(new Position("", 13203486.64, 4134294.82, 13353875.46, 4281767.1)); cityList.add(new Position("", 12919305.6, 4225626.11, 13136851.18, 4341583.6)); cityList.add(new Position("", 13490221.5, 4368831.31, 13662686.76, 4498957.54)); cityList.add(new Position("", 13156294.57, 4236695.19, 13360454.73, 4460300.4)); cityList.add(new Position("", 13309659.43, 4353072.03, 13573707.79, 4618802.14)); cityList.add(new Position("", 13004263.44, 4067481.89, 13117857.53, 4183285.71)); cityList.add(new Position("", 13086032.84, 4265566.89, 13194547.7, 4454232.75)); cityList.add(new Position("", 12270624.5, 4083896.51, 12753907.97, 4947334.76)); cityList.add(new Position("", 12414761.55, 4477543.17, 12597354.77, 4613071.62)); cityList.add(new Position("", 12466586.57, 4251962.38, 12662207.43, 4431272.44)); cityList.add(new Position("", 12533146.99, 4702342.43, 12753907.97, 4947334.76)); cityList.add(new Position("", 12461903.64, 4167494.97, 12649517.76, 4284844.26)); cityList.add(new Position("", 12402800.14, 4364687.35, 12706735.93, 4566716.17)); cityList.add(new Position("", 12287732.27, 4192354.69, 12532521.93, 4404887.45)); cityList.add(new Position("", 12287844.15, 4376854.72, 12505293.22, 4657101.81)); cityList.add(new Position("", 12457309.32, 4708157.61, 12643693.68, 4882446.81)); cityList.add(new Position("", 12351264.33, 4572394.82, 12687599.9, 4790431.02)); cityList.add(new Position("", 12571029.99, 4506299.25, 12696252.86, 4627705.5)); cityList.add(new Position("", 12270624.5, 4083898.8, 12477750.14, 4251682.71)); cityList.add(new Position("", 11744111.76, 3702746.74, 12384710.75, 4779514.03)); cityList.add(new Position("", 11981884.99, 3964654.15, 12226230.59, 4105288.31)); cityList.add(new Position("", 12026235.15, 3702746.74, 12269009.46, 3984319.77)); cityList.add(new Position("", 11835274.51, 3949399.28, 12029720.49, 4154241.13)); cityList.add(new Position("", 11744283.86, 3760380.97, 12054988.07, 3989283.7)); cityList.add(new Position("", 12087463.21, 3885095.93, 12361433.92, 4063447.96)); cityList.add(new Position("", 12088312.92, 4113604.41, 12189868.68, 4218877.81)); cityList.add(new Position("", 12130716.64, 4033630.18, 12313489.1, 4256079.36)); cityList.add(new Position("", 11984609.78, 4031675.07, 12154517.12, 4213826.27)); cityList.add(new Position("", 11985526.06, 4186651.87, 12307509.95, 4483691.41)); cityList.add(new Position("", 11941399.2, 4388945.75, 12384710.75, 4779303.54)); cityList.add(new Position("", 10838113.75, 2986533.97, 12084207.75, 4047359.43)); cityList.add(new Position("", 11469367.59, 3494751.29, 11677450.47, 3667639.18)); cityList.add(new Position("", 11191486.63, 3558944.25, 11626760.7, 4047359.43)); cityList.add(new Position("", 11841716.3, 3643858.17, 11996838.81, 3838156.85)); cityList.add(new Position("", 11874900.11, 3524432.9, 12084207.75, 3785513.7)); cityList.add(new Position("", 11555332.89, 3549960.81, 11708848.03, 3701927.98)); cityList.add(new Position("", 10838113.75, 3224547.1, 11410483.84, 4031723.71)); cityList.add(new Position("", 11794888.69, 3485015.43, 11946996.41, 3592275.81)); cityList.add(new Position("", 11646675.31, 3679400.3, 11886077.49, 3863720.27)); cityList.add(new Position("", 11456866.72, 3282255.36, 11606142.44, 3473629.59)); cityList.add(new Position("", 11139614.74, 2986533.97, 11564329.49, 3393883.6)); cityList.add(new Position("", 11705550.71, 3186846.74, 11843096.57, 3396900.43)); cityList.add(new Position("", 11738900.72, 3541461.13, 11908529.65, 3721444.31)); cityList.add(new Position("", 11450337.21, 3406322.68, 11634170.76, 3529139.28)); cityList.add(new Position("", 11550122.97, 3573305.2, 11770233.27, 3878122.45)); cityList.add(new Position("", 11608072.18, 3378899.78, 11739053.9, 3487837.25)); cityList.add(new Position("", 11259548.44, 2990979.4, 11382968.25, 3147334.32)); cityList.add(new Position("", 11696014.54, 3505172.11, 11800842.79, 3632125.5)); cityList.add(new Position("", 11348373.45, 3336428, 11510760.08, 3603260.72)); cityList.add(new Position("", 11534873.7, 3209500.13, 11728994.3, 3389231.15)); cityList.add(new Position("", 11599464.2, 3441209.59, 11773322.2, 3565314.97)); cityList.add(new Position("", 11583992.85, 3345872.23, 11719370.62, 3436407.2)); cityList.add(new Position("", 8727843.05, 3086017.6, 11033798.96, 4342740.32)); cityList.add(new Position("", 9992141.99, 3385663.74, 10311363.56, 3618513.4)); cityList.add(new Position("", 8727843.05, 3441390.6, 9610897.86, 4257019.66)); cityList.add(new Position("", 10419735.04, 3284156.87, 11033798.96, 3818960.92)); cityList.add(new Position("", 10260423.88, 3174330.56, 10994041.11, 3568908.2)); cityList.add(new Position("", 9468850.53, 3474655.39, 10578770.58, 4342740.32)); cityList.add(new Position("", 9144835.04, 3130768.42, 10058481, 3716081.04)); cityList.add(new Position("", 10027095.13, 3086017.6, 10504892.15, 3460286.95)); cityList.add(new Position("", 8181798.98, 4050003.25, 10730822.64, 6273729.91)); cityList.add(new Position("", 9662128.42, 5270859.24, 9906000.47, 5592219.04)); cityList.add(new Position("", 8972185.87, 4891851.52, 9123961.52, 4977007.41)); cityList.add(new Position("", 8686910.21, 4762157.81, 9361652.92, 5230038.82)); cityList.add(new Position("", 8972185.87, 4891851.52, 9123961.52, 4977007.41)); cityList.add(new Position("", 9521770.94, 5592219.04, 10139318.53, 6273729.91)); cityList.add(new Position("", 9181386.86, 4226843.45, 10450142.85, 5368965.84)); cityList.add(new Position("", 8893601.58, 5437124.81, 9329944.22, 5653078.83)); cityList.add(new Position("", 9773086.33, 5345744.78, 10196222.22, 5668843.11)); cityList.add(new Position("", 9527666.26, 5298895.9, 9750123.99, 5644356.17)); cityList.add(new Position("", 10150705.08, 4948635.66, 10730822.64, 5606117.42)); cityList.add(new Position("", 8617397.77, 4050003.25, 9454075.26, 4786182.37)); cityList.add(new Position("", 8289730.85, 4201158.73, 8891448.19, 4876496.1)); cityList.add(new Position("", 8756518.04, 4783639.2, 8862513.05, 4857851.76)); cityList.add(new Position("", 9413099.9, 5541495.71, 9578289.8, 5784360.46)); cityList.add(new Position("", 9431903.08, 5453177.45, 9475566.84, 5496855.11)); cityList.add(new Position("", 8181798.98, 4504704.65, 8781619.08, 5043837.4)); cityList.add(new Position("", 9563250.15, 5455441.32, 9593248.41, 5508042.09)); cityList.add(new Position("", 9156886.06, 5356708.34, 9723062.26, 5949778.86)); cityList.add(new Position("", 9413137.41, 5453077.32, 9578314.18, 5784360.46)); cityList.add(new Position("", 8756518.04, 4783639.2, 8862340.94, 4857851.76)); cityList.add(new Position("", 9714556.8, 5012740.03, 10232736.75, 5380227)); cityList.add(new Position("", 9726569.75, 5437137.77, 9765472.66, 5528937.44)); cityList.add(new Position("", 8924626.32, 5171696.76, 9456988.42, 5567388.32)); cityList.add(new Position("", 9438627.96, 5489585.39, 9490921.97, 5564219.65)); cityList.add(new Position("", 10857721.56, 2393774.36, 11822981.47, 3386968.96)); cityList.add(new Position("", 11374215.89, 2783319.89, 11541734.51, 3047940.43)); cityList.add(new Position("", 10920144.87, 2751373.9, 11137987.9, 2963199.62)); cityList.add(new Position("", 11213131.16, 2763346.98, 11409116.6, 3042427.04)); cityList.add(new Position("", 11006373.44, 2816846.8, 11249273.2, 3066933.44)); cityList.add(new Position("", 10857885.87, 2717112.8, 10991086.43, 2899331.83)); cityList.add(new Position("", 10976289.68, 3088082.75, 11167166.62, 3387037.37)); cityList.add(new Position("", 11333385.68, 2548820.52, 11609514.34, 2829457.53)); cityList.add(new Position("", 11063995.37, 2979088.98, 11301319.42, 3220020.52)); cityList.add(new Position("", 10924864.31, 2925486.15, 11093103.62, 3279081.08)); cityList.add(new Position("", 11472606.58, 2778803.18, 11670343.2, 3111043.37)); cityList.add(new Position("", 11452492.49, 3046917.77, 11724598.46, 3313477.27)); cityList.add(new Position("", 11530657.54, 2578150.93, 11822981.47, 2792390.19)); cityList.add(new Position("", 11126674.27, 2393805.45, 11338093.77, 2566720.27)); cityList.add(new Position("", 11274923.61, 2653633.78, 11483803.55, 2852475.44)); cityList.add(new Position("", 13139130.14, 3124220.58, 13597165.96, 3633652.49)); cityList.add(new Position("", 13617818.74, 3460251.46, 13629588.12, 3475911.6)); cityList.add(new Position("", 13612463.87, 3534593.33, 13630004.12, 3542768.3)); cityList.add(new Position("", 13563307.1, 3477623.32, 13573530.57, 3492890.68)); cityList.add(new Position("", 13590726.61, 3511620.64, 13608413.47, 3525120.35)); cityList.add(new Position("", 13567657.52, 3361593.28, 13579552.91, 3377746.21)); cityList.add(new Position("", 13586593.39, 3437493.7, 13604177.05, 3455095.63)); cityList.add(new Position("", 13574435.5, 3474037.55, 13619386.13, 3505312.02)); cityList.add(new Position("", 13174965.5, 3379425.23, 13439566.79, 3555379.53)); cityList.add(new Position("", 13274316.78, 3530637.21, 13413803.29, 3634464.94)); cityList.add(new Position("", 13392163.88, 3514264.36, 13530798.9, 3615258.63)); cityList.add(new Position("", 13273358.08, 3295182.09, 13446447.08, 3442148.74)); cityList.add(new Position("", 13214392.18, 3156523.05, 13408063.48, 3349194.76)); cityList.add(new Position("", 13456881.95, 3335309.93, 13616290.3, 3540487.02)); cityList.add(new Position("", 13139724.48, 3259521.17, 13286427.8, 3418618.76)); cityList.add(new Position("", 13346849.9, 3383986.06, 13496304.62, 3519472.14)); cityList.add(new Position("", 13391487.61, 3229487.33, 13579594.55, 3398618.42)); cityList.add(new Position("", 13317494.85, 3106318.51, 13512020.1, 3306358.35)); cityList.add(new Position("", 13528611.11, 3424814.02, 13692301.19, 3598734.46)); cityList.add(new Position("", 12671487.79, 2512035.14, 12747437.34, 2563724.73)); cityList.add(new Position("", 12639267.13, 2508287.37, 12647856.41, 2521696.25)); } }
package persistlayer; import java.sql.Connection; import java.sql.ResultSet; public class SearchPersistImpl{ //global variables DbAccessImpl db = new DbAccessImpl(); Connection con = db.connect(); public ResultSet getSuggestions(String searchbarContent){ ResultSet rs; String query = "SELECT DISTINCT make FROM cars WHERE make LIKE \'%%" + searchbarContent + "%%\'"; rs = db.retrieve(con, query); return rs; }//getSuggestions }//SearchImpl
package backend; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import terminal.Card; /* TODO: Change exp to short * Certificate with expdate is a byte array that looks like: * cert[0] = type (0 = smartcard, 1 = rentalterm, 2 = vehicleterm) * cert[1..163] = rsapublickey (length 162bytes) * cert[164..172] = expiration date of type long (8bytes) * cert[173...301] = Signature (128bytes) */ /*ALGO: * 1. get cardCert from smartcard and do mutual authentication between Rental Terminal - Smartcard * 2. get card data from database * 3. do the change (register, top up or refund) * 4. update database + update card certificate (if needed) */ public class BackendRentalTerminal { Database db = new Database(); Backend be = new Backend(); Serialization serial = new Serialization(); ByteUtils byteUtil = new ByteUtils(); ConstantValues CV = new ConstantValues(); public BackendRentalTerminal(){ } private byte[] ReadCertFromSmartCard(){ byte[] cert = null; return cert; } private byte[] MutualAuthenticationRT_S(){ byte[] cert = ReadCertFromSmartCard(); //TODO: //Check Mutual Authentication between Rental Terminal and SmartCards //Need to do a revocation check as well return cert; } /** * REGISTER NEW CUSTOMER * 1. Read cert from card * 2. renew the certificate to expand the expiration date * 3. Add customer and card data to database. NOTE: pubkey database is string */ public void RegisterNewCustomer(String name){ //1. read from the card and do mutual authentication byte[] cert = MutualAuthenticationRT_S(); //2a. renew the certificate byte[] newCert = null; try { newCert = be.renewCertificate(cert); } catch (RevokedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //2b. extract the expiration date and pubkey from card certificate byte[] exp = getExpFromCert(newCert); byte[] pubKey = getPublicKeyFromCert(newCert); String strPubKey = serial.SerializeByteKey(pubKey); long expLong = byteUtil.bytesToLong(exp); //3. add to database customer Integer customerId = db.insertCustomer(name); db.addSmartcard(customerId, expLong, strPubKey); } /** * * @param cardKm: the kilometers amount that stored in the card * NOTE: for the database, the kilometers saved is the total kilometers that ever added to the card * without the ticking */ public Card TopUpCard(short cardKm){ //1. read from the card and do mutual authentication byte[] cert = MutualAuthenticationRT_S(); short km = 0; //read this from card byte[] newCert = null; /* Get card from database */ Card card = getCardDB(cert); try { /* renew the certificate */ newCert = be.renewCertificate(cert); //extract expiration date from the new certificate and convert it to Long long expNew = byteUtil.bytesToLong(getExpFromCert(newCert)); //convert the long date to string String expString = convertLongDateToString(expNew); card.setExpiration(expNew); card.setStringExpiration(expString); /* update to database */ db.updateKilometersExpiration(card.getKilometers()+ cardKm, expNew, card.getID()); //TODO update to the smartcard card.setKilometers(km + cardKm); } catch (RevokedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return card; } //Refund the kilometers public Card refundKilometers(){ //1. read from the card and do mutual authentication byte[] cert = MutualAuthenticationRT_S(); //2. get card data from database Card card = getCardDB(cert); //3. do the refund card.setKilometers(0); /*4. update to database */ db.updateKilometersExpiration(0, card.getExpDate(), card.getID()); //TODO update to Card return card; } /** * Get card data from database * @param cardPublicKey * @return */ public Card getCardDB(byte[] cardPublicKey){ Card card = new Card(); String strPubKey = serial.SerializeByteKey(cardPublicKey); ResultSet rs = db.selectCard(strPubKey); try { if(rs.next()){ card = new Card(rs.getInt("id"), rs.getInt("custID"), rs.getString("custName"), rs.getInt("km"), rs.getLong("exp") , rs.getInt("revoke"), rs.getString("cardPK")); }else{ System.out.println("That card has not been issued"); card = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return card; } //get the expiration date from the certificate private byte[] getExpFromCert(byte[] cert){ byte[] exp = new byte[CV.EXP_LENGTH]; System.arraycopy(cert, 164, exp, 0, CV.EXP_LENGTH); return exp; } //get public key from certificate private byte[] getPublicKeyFromCert(byte[] cert){ byte[] pubKey = new byte[CV.RSAPUBLICKEYLENGTH]; System.arraycopy(cert, 1, pubKey, 0, CV.RSAPUBLICKEYLENGTH); return pubKey; } //convert long date to string date private String convertLongDateToString(long expDate){ Date date=new Date(expDate); SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy"); String dateText = df2.format(date); System.out.println(dateText); return dateText; } }
package org.innovateuk.ifs.project.security; import org.innovateuk.ifs.BaseServiceSecurityTest; import org.innovateuk.ifs.address.resource.AddressResource; import org.innovateuk.ifs.address.resource.OrganisationAddressType; import org.innovateuk.ifs.application.resource.FundingDecision; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.file.service.FileAndContents; import org.innovateuk.ifs.invite.resource.InviteProjectResource; import org.innovateuk.ifs.project.domain.ProjectUser; import org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectTeamStatusResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.innovateuk.ifs.project.transactional.ProjectService; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.RoleResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.resource.UserRoleType; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.method.P; import java.io.InputStream; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.*; import java.util.function.Supplier; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.EnumSet.complementOf; import static java.util.EnumSet.of; import static java.util.stream.Collectors.toList; import static junit.framework.TestCase.fail; import static org.innovateuk.ifs.address.builder.AddressResourceBuilder.newAddressResource; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.project.builder.ProjectResourceBuilder.newProjectResource; import static org.innovateuk.ifs.project.builder.ProjectUserResourceBuilder.newProjectUserResource; import static org.innovateuk.ifs.user.builder.RoleResourceBuilder.newRoleResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.UserRoleType.*; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; /** * Testing how the secured methods in ProjectService interact with Spring Security */ public class ProjectServiceSecurityTest extends BaseServiceSecurityTest<ProjectService> { private ProjectPermissionRules projectPermissionRules; private ProjectLookupStrategy projectLookupStrategy; @Before public void lookupPermissionRules() { projectPermissionRules = getMockPermissionRulesBean(ProjectPermissionRules.class); projectLookupStrategy = getMockPermissionEntityLookupStrategiesBean(ProjectLookupStrategy.class); } @Test public void testGetProjectById() { final Long projectId = 1L; when(projectLookupStrategy.getProjectResource(projectId)).thenReturn(newProjectResource().build()); assertAccessDenied( () -> classUnderTest.getProjectById(projectId), () -> { verify(projectPermissionRules, times(1)).partnersOnProjectCanView(isA(ProjectResource.class), isA(UserResource.class)); verify(projectPermissionRules, times(1)).internalUsersCanViewProjects(isA(ProjectResource.class), isA(UserResource.class)); } ); } @Test public void testCreateProjectFromApplicationAllowedIfCompAdminRole() { setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(COMP_ADMIN).build())).build()); classUnderTest.createProjectFromApplication(123L); } @Test public void testCreateProjectFromApplicationDeniedForApplicant() { setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(APPLICANT).build())).build()); try { classUnderTest.createProjectFromApplication(123L); fail("Should not have been able to create project from application as applicant"); } catch (AccessDeniedException ade) { //expected behaviour } } @Test public void testCreateProjectFromFundingDecisionsAllowedIfGlobalCompAdminRole() { RoleResource compAdminRole = newRoleResource().withType(COMP_ADMIN).build(); setLoggedInUser(newUserResource().withRolesGlobal(singletonList(compAdminRole)).build()); classUnderTest.createProjectsFromFundingDecisions(new HashMap<>()); } @Test public void testCreateProjectFromFundingDecisionsAllowedIfNoGlobalRolesAtAll() { try { classUnderTest.createProjectsFromFundingDecisions(new HashMap<>()); Assert.fail("Should not have been able to create project from application without the global Comp Admin role"); } catch (AccessDeniedException e) { // expected behaviour } } @Test public void testCreateProjectFromFundingDecisionsDeniedIfNotCorrectGlobalRoles() { List<UserRoleType> nonCompAdminRoles = asList(UserRoleType.values()).stream().filter(type -> type != COMP_ADMIN && type != PROJECT_FINANCE) .collect(toList()); nonCompAdminRoles.forEach(role -> { setLoggedInUser( newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(role).build())).build()); try { classUnderTest.createProjectsFromFundingDecisions(new HashMap<>()); Assert.fail("Should not have been able to create project from application without the global Comp Admin role"); } catch (AccessDeniedException e) { // expected behaviour } }); } @Test public void testUpdateProjectStartDate() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.updateProjectStartDate(123L, LocalDate.now()), () -> { verify(projectPermissionRules).leadPartnersCanUpdateTheBasicProjectDetails(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testUpdateProjectAddress() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(456L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.updateProjectAddress(123L, 456L, OrganisationAddressType.ADD_NEW, newAddressResource().build()), () -> { verify(projectPermissionRules).leadPartnersCanUpdateTheBasicProjectDetails(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testUpdateFinanceContact() { ProjectResource project = newProjectResource().build(); ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(123L, 456L); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.updateFinanceContact(composite, 789L), () -> { verify(projectPermissionRules).partnersCanUpdateTheirOwnOrganisationsFinanceContacts(composite, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testSetProjectManager() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.setProjectManager(123L, 456L), () -> { verify(projectPermissionRules).leadPartnersCanUpdateTheBasicProjectDetails(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetProjectUsers() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getProjectUsers(123L), () -> { verify(projectPermissionRules).partnersOnProjectCanView(project, getLoggedInUser()); verify(projectPermissionRules).internalUsersCanViewProjects(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testCreateCollaborationAgreementFileEntry() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.createCollaborationAgreementFileEntry(123L, null, null), () -> { verify(projectPermissionRules).leadPartnersCanUploadOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetCollaborationAgreementFileEntryDetails() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getCollaborationAgreementFileEntryDetails(123L), () -> { verify(projectPermissionRules).partnersCanViewOtherDocumentsDetails(project, getLoggedInUser()); verify(projectPermissionRules).internalUserCanViewOtherDocumentsDetails(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetCollaborationAgreementFileEntryContents() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getCollaborationAgreementFileContents(123L), () -> { verify(projectPermissionRules).internalUserCanDownloadOtherDocuments(project, getLoggedInUser()); verify(projectPermissionRules).partnersCanDownloadOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testDeleteCollaborationAgreementFileEntry() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.deleteCollaborationAgreementFile(123L), () -> { verify(projectPermissionRules).leadPartnersCanDeleteOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testCreateExploitationPlanFileEntry() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.createExploitationPlanFileEntry(123L, null, null), () -> { verify(projectPermissionRules).leadPartnersCanUploadOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetExploitationPlanFileEntryDetails() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getExploitationPlanFileEntryDetails(123L), () -> { verify(projectPermissionRules).internalUserCanViewOtherDocumentsDetails(project, getLoggedInUser()); verify(projectPermissionRules).partnersCanViewOtherDocumentsDetails(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetExploitationPlanFileEntryContents() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getExploitationPlanFileContents(123L), () -> { verify(projectPermissionRules).internalUserCanDownloadOtherDocuments(project, getLoggedInUser()); verify(projectPermissionRules).partnersCanDownloadOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testDeleteExploitationPlanFileEntry() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.deleteExploitationPlanFile(123L), () -> { verify(projectPermissionRules).leadPartnersCanDeleteOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testAcceptOrRejectOtherDocuments() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.acceptOrRejectOtherDocuments(123L, true), () -> { verify(projectPermissionRules).internalUserCanAcceptOrRejectOtherDocuments(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testAddPartnerDeniedIfNotSystemRegistrar() { EnumSet<UserRoleType> nonSystemRegistrationRoles = complementOf(of(SYSTEM_REGISTRATION_USER)); nonSystemRegistrationRoles.forEach(role -> { setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(role).build())).build()); try { classUnderTest.addPartner(1L, 2L, 3L); Assert.fail("Should not have been able to add a partner without the system registrar role"); } catch (AccessDeniedException e) { // expected behaviour } }); } @Test public void testAddPartnerAllowedIfSystemRegistrar() { setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(SYSTEM_REGISTRATION_USER).build())).build()); classUnderTest.addPartner(1L, 2L, 3L); // There should be no exception thrown } @Test public void test_createApplicationByAppNameForUserIdAndCompetitionId_deniedIfNotCorrectGlobalRolesOrASystemRegistrar() { EnumSet<UserRoleType> nonSystemRegistrationRoles = complementOf(of(SYSTEM_REGISTRATION_USER)); nonSystemRegistrationRoles.forEach(role -> { setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(role).build())).build()); try { classUnderTest.addPartner(1L, 2L, 3L); Assert.fail("Should not have been able to add a partner without the system registrar role"); } catch (AccessDeniedException e) { // expected behaviour } }); } @Test public void testGetProjectTeamStatus() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied(() -> classUnderTest.getProjectTeamStatus(123L, Optional.empty()), () -> { verify(projectPermissionRules).partnersCanViewTeamStatus(project, getLoggedInUser()); verify(projectPermissionRules).internalUsersCanViewTeamStatus(project, getLoggedInUser()); verifyNoMoreInteractions(projectPermissionRules); }); } @Test public void testGetProjectManager() { ProjectResource project = newProjectResource().build(); when(projectLookupStrategy.getProjectResource(123L)).thenReturn(project); assertAccessDenied( () -> classUnderTest.getProjectById(123L), () -> { verify(projectPermissionRules, times(1)).partnersOnProjectCanView(isA(ProjectResource.class), isA(UserResource.class)); verify(projectPermissionRules, times(1)).internalUsersCanViewProjects(isA(ProjectResource.class), isA(UserResource.class)); verifyNoMoreInteractions(projectPermissionRules); } ); } @Override protected Class<TestProjectService> getClassUnderTest() { return TestProjectService.class; } public static class TestProjectService implements ProjectService { static final int ARRAY_SIZE_FOR_POST_FILTER_TESTS = 2; @Override public ServiceResult<ProjectResource> getProjectById(@P("projectId") Long projectId) { return serviceSuccess(newProjectResource().withId(1L).build()); } @Override public ServiceResult<ProjectResource> getByApplicationId(@P("applicationId") Long applicationId) { return null; } @Override public ServiceResult<List<ProjectResource>> findAll() { return null; } @Override public ServiceResult<ProjectResource> createProjectFromApplication(Long applicationId) { return null; } @Override public ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions) { return null; } @Override public ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerId) { return null; } @Override public ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate) { return null; } @Override public ServiceResult<Void> updateProjectAddress(Long leadOrganisationId, Long projectId, OrganisationAddressType addressType, AddressResource projectAddress) { return null; } @Override public ServiceResult<List<ProjectResource>> findByUserId(Long userId) { return null; } @Override public ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId) { return null; } @Override public ServiceResult<List<ProjectUserResource>> getProjectUsers(Long projectId) { return serviceSuccess(newProjectUserResource().build(2)); } @Override public ServiceResult<Void> submitProjectDetails(Long id, ZonedDateTime date) { return null; } @Override public ServiceResult<Boolean> isSubmitAllowed(Long projectId) { return null; } @Override public ServiceResult<Void> saveDocumentsSubmitDateTime(Long projectId, ZonedDateTime date) { return null; } @Override public ServiceResult<Boolean> isOtherDocumentsSubmitAllowed(Long projectId, Long userId) { return null; } @Override public ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(Long projectId, Long userId) { return null; } @Override public ServiceResult<Void> inviteFinanceContact(Long projectId, InviteProjectResource inviteResource) { return null; } @Override public ServiceResult<Void> inviteProjectManager(Long projectId, InviteProjectResource inviteResource) { return null; } @Override public ServiceResult<FileEntryResource> createCollaborationAgreementFileEntry(Long projectId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { return null; } @Override public ServiceResult<FileAndContents> getCollaborationAgreementFileContents(Long projectId) { return null; } @Override public ServiceResult<FileEntryResource> getCollaborationAgreementFileEntryDetails(Long projectId) { return null; } @Override public ServiceResult<Void> updateCollaborationAgreementFileEntry(Long projectId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { return null; } @Override public ServiceResult<Void> deleteCollaborationAgreementFile(Long projectId) { return null; } @Override public ServiceResult<FileEntryResource> createExploitationPlanFileEntry(Long projectId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { return null; } @Override public ServiceResult<FileAndContents> getExploitationPlanFileContents(Long projectId) { return null; } @Override public ServiceResult<FileEntryResource> getExploitationPlanFileEntryDetails(Long projectId) { return null; } @Override public ServiceResult<Void> updateExploitationPlanFileEntry(Long projectId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { return null; } @Override public ServiceResult<Void> deleteExploitationPlanFile(Long projectId) { return null; } @Override public ServiceResult<Void> acceptOrRejectOtherDocuments(Long projectId, Boolean approved) { return null; } @Override public ServiceResult<ProjectUser> addPartner(Long projectId, Long userId, Long organisationId) { return null; } @Override public ServiceResult<ProjectTeamStatusResource> getProjectTeamStatus(Long projectId, Optional<Long> filterByUserId) { return null; } @Override public ServiceResult<ProjectUserResource> getProjectManager(Long projectId) { return serviceSuccess(newProjectUserResource().withProject(projectId).withRoleName("project-manager").build()); } } }
package mil.nga.geopackage.user; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.db.GeoPackageDataType; /** * Metadata about a single column from a user table * * @author osbornb */ public abstract class UserColumn implements Comparable<UserColumn> { /** * User Column index value * * @since 3.2.1 */ public static final int NO_INDEX = -1; /** * Column index */ private int index; /** * Column name */ private String name; /** * Max size */ private final Long max; /** * True if a not null column */ private final boolean notNull; /** * Default column value */ private final Object defaultValue; /** * True if a primary key column */ private final boolean primaryKey; /** * Data type */ private final GeoPackageDataType dataType; /** * Constructor * * @param index * column index * @param name * column name * @param dataType * data type * @param max * max value * @param notNull * not null flag * @param defaultValue * default value * @param primaryKey * primary key flag */ protected UserColumn(int index, String name, GeoPackageDataType dataType, Long max, boolean notNull, Object defaultValue, boolean primaryKey) { this.index = index; this.name = name; this.max = max; this.notNull = notNull; this.defaultValue = defaultValue; this.primaryKey = primaryKey; this.dataType = dataType; validateMax(); } /** * Copy Constructor * * @param userColumn * user column * @since 3.2.1 */ protected UserColumn(UserColumn userColumn) { this.index = userColumn.index; this.name = userColumn.name; this.max = userColumn.max; this.notNull = userColumn.notNull; this.defaultValue = userColumn.defaultValue; this.primaryKey = userColumn.primaryKey; this.dataType = userColumn.dataType; } /** * Copy the column * * @return copied column * @since 3.2.1 */ public abstract UserColumn copy(); /** * Check if the column has a valid index * * @return true if has a valid index * @since 3.2.1 */ public boolean hasIndex() { return this.index > NO_INDEX; } /** * Set the column index. Only allowed when {@link #hasIndex()} is false ( * {@link #getIndex()} is {@link #NO_INDEX}). Setting a valid index to an * existing valid index does nothing. * * @param index * column index * @since 3.2.1 */ public void setIndex(int index) { if (hasIndex()) { if (index != this.index) { throw new GeoPackageException( "User Column with a valid index may not be changed. Column Name: " + name + ", Index: " + this.index + ", Attempted Index: " + index); } } else { this.index = index; } } /** * Reset the column index * * @since 3.2.1 */ protected void resetIndex() { this.index = NO_INDEX; } /** * Get the index * * @return index */ public int getIndex() { return index; } /** * Set the name * * @param name * column name * @since 3.2.1 */ protected void setName(String name) { this.name = name; } /** * Get the name * * @return name */ public String getName() { return name; } /** * Determine if this column is named the provided name * * @param name * column name * @return true if named the provided name * @since 3.0.1 */ public boolean isNamed(String name) { return this.name.equals(name); } /** * Determine if the column has a max value * * @return true if has max value * @since 3.2.1 */ public boolean hasMax() { return max != null; } /** * Get the max * * @return max */ public Long getMax() { return max; } /** * Get the is not null flag * * @return not null flag */ public boolean isNotNull() { return notNull; } /** * Determine if the column has a default value * * @return true if has default value * @since 3.2.1 */ public boolean hasDefaultValue() { return defaultValue != null; } /** * Get the default value * * @return default value */ public Object getDefaultValue() { return defaultValue; } /** * Get the primary key flag * * @return primary key flag */ public boolean isPrimaryKey() { return primaryKey; } /** * When not a geometry column, gets the data type * * @return data type */ public GeoPackageDataType getDataType() { return dataType; } /** * Get the database type name * * @return type name */ public String getTypeName() { String type = null; if (dataType != null) { type = dataType.name(); } return type; } /** * {@inheritDoc} * * Sort by index */ @Override public int compareTo(UserColumn another) { return index - another.index; } /** * Validate that if max is set, the data type is text or blob */ private void validateMax() { if (max != null) { if (dataType == null) { throw new GeoPackageException( "Column max is only supported for data typed columns. column: " + name + ", max: " + max); } else if (dataType != GeoPackageDataType.TEXT && dataType != GeoPackageDataType.BLOB) { throw new GeoPackageException( "Column max is only supported for " + GeoPackageDataType.TEXT.name() + " and " + GeoPackageDataType.BLOB.name() + " columns. column: " + name + ", max: " + max + ", type: " + dataType.name()); } } } }
package net.creeperhost.chtweaks; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntityMob; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.event.entity.living.LivingDeathEvent; import java.util.Random; public class ModEvents { private static final int SPAWN_RATIO = 8; @SubscribeEvent public void onLivingDeathEvent(LivingDeathEvent event) { if (isServer(event.entity.worldObj) && event.entity != null && isHostile(event.entity)) { Random randomGenerator = new Random(); if(randomGenerator.nextInt(100) > 40) { spawnStackAtEntity(event, new ItemStack(Items.gold_nugget, (int) event.entityLiving.getMaxHealth() / SPAWN_RATIO)); } } } private boolean isServer(World world) { return !world.isRemote; } private boolean isHostile(Entity entity) { return entity instanceof EntityMob; } private void spawnStackAtEntity(LivingDeathEvent event, ItemStack stack) { World world = event.entity.worldObj; EntityItem item = new EntityItem(world, event.entity.posX, event.entity.posY, event.entity.posZ, stack); world.spawnEntityInWorld(item); } }
package com.twelvemonkeys.imageio.util; import com.twelvemonkeys.image.ImageUtil; import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi; import org.junit.Ignore; import org.junit.Test; import org.mockito.InOrder; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import javax.imageio.*; import javax.imageio.event.IIOReadProgressListener; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.IIORegistry; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public abstract class ImageReaderAbstractTestCase<T extends ImageReader> { // TODO: Should we really test if the provider is installed? // - Pro: Tests the META-INF/services config // - Con: Not all providers should be installed at runtime... static { IIORegistry.getDefaultInstance().registerServiceProvider(new URLImageInputStreamSpi()); } protected abstract List<TestData> getTestData(); protected abstract ImageReaderSpi createProvider(); protected abstract Class<T> getReaderClass(); protected T createReader() { try { return getReaderClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } protected abstract List<String> getFormatNames(); protected abstract List<String> getSuffixes(); protected abstract List<String> getMIMETypes(); protected boolean allowsNullRawImageType() { return false; } private static void failBecause(String message, Throwable exception) { AssertionError error = new AssertionError(message); error.initCause(exception); throw error; } protected void assertProviderInstalledForName(final String pFormat, final Class<? extends ImageReader> pReaderClass) { assertProviderInstalled0(pFormat.toUpperCase(), pReaderClass, ImageIO.getImageReadersByFormatName(pFormat.toUpperCase())); assertProviderInstalled0(pFormat.toLowerCase(), pReaderClass, ImageIO.getImageReadersByFormatName(pFormat.toLowerCase())); } protected void assertProviderInstalledForMIMEType(final String pType, final Class<? extends ImageReader> pReaderClass) { assertProviderInstalled0(pType, pReaderClass, ImageIO.getImageReadersByMIMEType(pType)); } protected void assertProviderInstalledForSuffix(final String pType, final Class<? extends ImageReader> pReaderClass) { assertProviderInstalled0(pType, pReaderClass, ImageIO.getImageReadersBySuffix(pType)); } private void assertProviderInstalled0(final String pFormat, final Class<? extends ImageReader> pReaderClass, final Iterator<ImageReader> pReaders) { boolean found = false; while (pReaders.hasNext()) { ImageReader reader = pReaders.next(); if (reader.getClass() == pReaderClass) { found = true; } } assertTrue(String.format("%s not installed for %s", pReaderClass.getSimpleName(), pFormat), found); } @Test public void testProviderInstalledForNames() { Class<? extends ImageReader> readerClass = getReaderClass(); for (String name : getFormatNames()) { assertProviderInstalledForName(name, readerClass); } } @Test public void testProviderInstalledForSuffixes() { Class<? extends ImageReader> readerClass = getReaderClass(); for (String suffix : getSuffixes()) { assertProviderInstalledForSuffix(suffix, readerClass); } } @Test public void testProviderInstalledForMIMETypes() { Class<? extends ImageReader> readerClass = getReaderClass(); for (String type : getMIMETypes()) { assertProviderInstalledForMIMEType(type, readerClass); } } @Test public void testProviderCanRead() throws IOException { List<TestData> testData = getTestData(); ImageReaderSpi provider = createProvider(); for (TestData data : testData) { ImageInputStream stream = data.getInputStream(); assertNotNull(stream); assertTrue("Provider is expected to be able to decode data: " + data, provider.canDecodeInput(stream)); } } @Test public void testProviderCanReadNull() { boolean canRead = false; try { canRead = createProvider().canDecodeInput(null); } catch (IllegalArgumentException ignore) { } catch (RuntimeException e) { failBecause("RuntimeException other than IllegalArgumentException thrown", e); } catch (IOException e) { failBecause("Could not test data for read", e); } assertFalse("ImageReader can read null input", canRead); } @Test public void testSetInput() { // Should just pass with no exceptions ImageReader reader = createReader(); assertNotNull(reader); for (TestData data : getTestData()) { reader.setInput(data.getInputStream()); } } @Test public void testSetInputNull() { // Should just pass with no exceptions ImageReader reader = createReader(); assertNotNull(reader); reader.setInput(null); } @Test public void testRead() { ImageReader reader = createReader(); for (TestData data : getTestData()) { reader.setInput(data.getInputStream()); for (int i = 0; i < data.getImageCount(); i++) { BufferedImage image = null; try { image = reader.read(i); } catch (Exception e) { failBecause(String.format("Image %s index %s could not be read: %s", data.getInput(), i, e), e); } assertNotNull(String.format("Image %s index %s was null!", data.getInput(), i), image); assertEquals( String.format("Image %s index %s has wrong width: %s", data.getInput(), i, image.getWidth()), data.getDimension(i).width, image.getWidth() ); assertEquals( String.format("Image %s index %s has wrong height: %s", data.getInput(), i, image.getHeight()), data.getDimension(i).height, image.getHeight() ); } } } @Test public void testReadIndexNegative() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(-1); fail("Read image with illegal index"); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadIndexOutOfBounds() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(Integer.MAX_VALUE); // TODO: This might actually not throw exception... fail("Read image with index out of bounds"); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadNoInput() { ImageReader reader = createReader(); // Do not set input BufferedImage image = null; try { image = reader.read(0); fail("Read image with no input"); } catch (IllegalStateException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReRead() throws IOException { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream(), false); // Explicitly allow repositioning, even though it's the default BufferedImage first = reader.read(0); assertNotNull(first); BufferedImage second = reader.read(0); assertNotNull(second); // TODO: These images should be exactly the same, but there's no equals for images assertEquals(first.getType(), second.getType()); assertEquals(first.getWidth(), second.getWidth()); assertEquals(first.getHeight(), second.getHeight()); } @Test public void testReadIndexNegativeWithParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(-1, reader.getDefaultReadParam()); fail("Read image with illegal index"); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadIndexOutOfBoundsWithParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(99, reader.getDefaultReadParam()); fail("Read image with index out of bounds"); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadNoInputWithParam() { ImageReader reader = createReader(); // Do not set input BufferedImage image = null; try { image = reader.read(0, reader.getDefaultReadParam()); fail("Read image with no input"); } catch (IllegalStateException ignore) { } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadWithNewParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(0, new ImageReadParam()); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); } @Test public void testReadWithDefaultParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(0, reader.getDefaultReadParam()); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); } @Test public void testReadWithNullParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage image = null; try { image = reader.read(0, null); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); } @Test public void testReadWithSizeParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); if (param.canSetSourceRenderSize()) { param.setSourceRenderSize(new Dimension(10, 10)); BufferedImage image = null; try { image = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); } } @Test public void testReadWithSubsampleParamDimensions() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(5, 5, 0, 0); BufferedImage image = null; try { image = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: ", (data.getDimension(0).width + 4) / 5, image.getWidth()); assertEquals("Read image has wrong height: ", (data.getDimension(0).height + 4) / 5, image.getHeight()); } @Ignore @Test public void testReadWithSubsampleParamPixels() throws IOException { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(new Rectangle(Math.min(100, reader.getWidth(0)), Math.min(100, reader.getHeight(0)))); BufferedImage image = null; BufferedImage subsampled = null; try { image = reader.read(0, param); param.setSourceSubsampling(2, 2, 1, 1); // Hmm.. Seems to be the offset the fake version (ReplicateScaleFilter) uses subsampled = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } BufferedImage expected = ImageUtil.toBuffered(IIOUtil.fakeSubsampling(image, param)); // JPanel panel = new JPanel(); // panel.add(new JLabel("Expected", new BufferedImageIcon(expected, 300, 300), JLabel.CENTER)); // panel.add(new JLabel("Actual", new BufferedImageIcon(subsampled, 300, 300), JLabel.CENTER)); // JOptionPane.showConfirmDialog(null, panel); assertImageDataEquals("Subsampled image data does not match expected", expected, subsampled); } protected final void assertImageDataEquals(String message, BufferedImage expected, BufferedImage actual) { assertNotNull("Expected image was null", expected); assertNotNull("Actual image was null!", actual); if (expected == actual) { return; } for (int y = 0; y < expected.getHeight(); y++) { for (int x = 0; x < expected.getWidth(); x++) { int expectedRGB = expected.getRGB(x, y); int actualRGB = actual.getRGB(x, y); assertEquals(String.format("%s alpha at (%d, %d)", message, x, y), (expectedRGB >> 24) & 0xff, (actualRGB >> 24) & 0xff, 5); assertEquals(String.format("%s red at (%d, %d)", message, x, y), (expectedRGB >> 16) & 0xff, (actualRGB >> 16) & 0xff, 5); assertEquals(String.format("%s green at (%d, %d)", message, x, y), (expectedRGB >> 8) & 0xff, (actualRGB >> 8) & 0xff, 5); assertEquals(String.format("%s blue at (%d, %d)", message, x, y), expectedRGB & 0xff, actualRGB & 0xff, 5); } } } @Test public void testReadWithSourceRegionParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(new Rectangle(0, 0, 10, 10)); BufferedImage image = null; try { image = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); } @Test public void testReadWithSourceRegionParamEqualImage() throws IOException { // Default invocation assertReadWithSourceRegionParamEqualImage(new Rectangle(3, 3, 9, 9), getTestData().get(0), 0); } protected void assertReadWithSourceRegionParamEqualImage(final Rectangle r, final TestData data, final int imageIndex) throws IOException { ImageReader reader = createReader(); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); // Read full image and get sub image for comparison final BufferedImage roi = reader.read(imageIndex, param).getSubimage(r.x, r.y, r.width, r.height); param.setSourceRegion(r); final BufferedImage image = reader.read(imageIndex, param); // try { // SwingUtilities.invokeAndWait(new Runnable() { // public void run() { // JPanel panel = new JPanel(new FlowLayout()); // panel.add(new JLabel(new BufferedImageIcon(roi, r.width * 10, r.height * 10, true))); // panel.add(new JLabel(new BufferedImageIcon(image, r.width * 10, r.height * 10, true))); // JOptionPane.showConfirmDialog(null, panel); // catch (Exception e) { // throw new RuntimeException(e); assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), r.width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), r.height, image.getHeight()); assertImageDataEquals("Images differ", roi, image); } @Test public void testReadWithSizeAndSourceRegionParam() { // TODO: Is this test correct??? ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); if (param.canSetSourceRenderSize()) { Dimension size = data.getDimension(0); size = new Dimension(size.width * 2, size.height * 2); param.setSourceRenderSize(size); param.setSourceRegion(new Rectangle(0, 0, 10, 10)); BufferedImage image = null; try { image = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); } } @Test public void testReadWithSubsampleAndSourceRegionParam() { // NOTE: The "standard" (com.sun.imageio.plugin.*) ImageReaders pass // this test, so the test should be correct... ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(2, 2, 0, 0); param.setSourceRegion(new Rectangle(0, 0, 10, 10)); BufferedImage image = null; try { image = reader.read(0, param); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), 5, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), 5, image.getHeight()); } @Test public void testReadAsRenderedImageIndexNegative() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); RenderedImage image = null; try { image = reader.readAsRenderedImage(-1, reader.getDefaultReadParam()); fail("Read image with illegal index"); } catch (IndexOutOfBoundsException expected) { // Ignore } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadAsRenderedImageIndexOutOfBounds() throws IIOException { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); RenderedImage image = null; try { image = reader.readAsRenderedImage(reader.getNumImages(true), reader.getDefaultReadParam()); fail("Read image with index out of bounds"); } catch (IndexOutOfBoundsException expected) { // Ignore } catch (IIOException e) { // Allow this to bubble up, due to a bug in the Sun JPEGImageReader throw e; } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadAsRenderedImageNoInput() { ImageReader reader = createReader(); // Do not set input BufferedImage image = null; try { image = reader.read(0, reader.getDefaultReadParam()); fail("Read image with no input"); } catch (IllegalStateException expected) { // Ignore } catch (IOException e) { failBecause("Image could not be read", e); } assertNull(image); } @Test public void testReadAsRenderedImage() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); RenderedImage image = null; try { image = reader.readAsRenderedImage(0, null); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); } @Test public void testReadAsRenderedImageWithDefaultParam() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); RenderedImage image = null; try { image = reader.readAsRenderedImage(0, reader.getDefaultReadParam()); } catch (IOException e) { failBecause("Image could not be read", e); } assertNotNull("Image was null!", image); assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); } @Test public void testGetDefaultReadParam() { ImageReader reader = createReader(); ImageReadParam param = reader.getDefaultReadParam(); assertNotNull(param); } @Test public void testGetFormatName() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); String name = null; try { name = reader.getFormatName(); } catch (IOException e) { fail(e.getMessage()); } assertNotNull(name); } @Test public void testGetMinIndex() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); int num = 0; try { num = reader.getMinIndex(); } catch (IllegalStateException ignore) { } assertEquals(0, num); } @Test public void testGetMinIndexNoInput() { ImageReader reader = createReader(); int num = 0; try { num = reader.getMinIndex(); } catch (IllegalStateException ignore) { } assertEquals(0, num); } @Test public void testGetNumImages() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); int num = -1; try { num = reader.getNumImages(false); } catch (IOException e) { fail(e.getMessage()); } assertTrue(num == -1 || num > 0); try { num = reader.getNumImages(true); } catch (IOException e) { fail(e.getMessage()); } assertTrue(num > 0); assertTrue(data.getImageCount() <= num); if (data.getImageCount() != num) { System.err.println("WARNING: Image count not equal to test data count"); } } @Test public void testGetNumImagesNoInput() { ImageReader reader = createReader(); int num = -1; try { num = reader.getNumImages(false); } catch (IllegalStateException ignore) { } catch (IOException e) { fail(e.getMessage()); } assertEquals(-1, num); try { num = reader.getNumImages(true); fail("Should throw IllegalStateException"); } catch (IllegalStateException ignore) { } catch (IOException e) { fail(e.getMessage()); } assertEquals(-1, num); } @Test public void testGetWidth() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); int width = 0; try { width = reader.getWidth(0); } catch (IOException e) { fail("Could not read image width: " + e); } assertEquals("Wrong width reported", data.getDimension(0).width, width); } @Test public void testGetWidthIndexOutOfBounds() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); //int width = 0; try { /*width = */reader.getWidth(-1); // NOTE: Some readers (like the com.sun.imageio stuff) ignores // index in getWidth/getHeight for formats with only one image... //assertEquals("Wrong width reported", data.getDimension().width, width); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { fail("Could not read image aspect ratio: " + e); } } @Test public void testGetWidthNoInput() { ImageReader reader = createReader(); int width = 0; try { width = reader.getWidth(0); fail("Width read without imput"); } catch (IllegalStateException ignore) { } catch (IOException e) { fail("Could not read image width: " + e); } assertEquals("Wrong width reported", 0, width); } @Test public void testGetHeight() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); int height = 0; try { height = reader.getHeight(0); } catch (IOException e) { fail("Could not read image height: " + e); } assertEquals("Wrong height reported", data.getDimension(0).height, height); } @Test public void testGetHeightNoInput() { ImageReader reader = createReader(); int height = 0; try { height = reader.getHeight(0); fail("height read without imput"); } catch (IllegalStateException ignore) { } catch (IOException e) { fail("Could not read image height: " + e); } assertEquals("Wrong height reported", 0, height); } @Test public void testGetHeightIndexOutOfBounds() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); //int height = 0; try { /*height =*/ reader.getHeight(-1); // NOTE: Some readers (like the com.sun.imageio stuff) ignores // index in getWidth/getHeight for formats with only one image... //assertEquals("Wrong height reported", data.getDimension().height, height); } catch (IndexOutOfBoundsException ignore) { } catch (IOException e) { fail("Could not read image height: " + e); } } @Test public void testGetAspectRatio() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); float aspectRatio = 0f; try { aspectRatio = reader.getAspectRatio(0); } catch (IOException e) { fail("Could not read image aspect ratio" + e); } Dimension d = data.getDimension(0); assertEquals("Wrong aspect aspect ratio", d.getWidth() / d.getHeight(), aspectRatio, 0.001); } @Test public void testGetAspectRatioNoInput() { ImageReader reader = createReader(); float aspectRatio = 0f; try { aspectRatio = reader.getAspectRatio(0); fail("aspect read without input"); } catch (IllegalStateException ignore) { } catch (IOException e) { fail("Could not read image aspect ratio" + e); } assertEquals("Wrong aspect aspect ratio", 0f, aspectRatio, 0f); } @Test public void testGetAspectRatioIndexOutOfBounds() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); //float aspectRatio = 0f; try { // NOTE: Some readers (like the com.sun.imageio stuff) ignores // index in getWidth/getHeight for formats with only one image... /*aspectRatio =*/ reader.getAspectRatio(-1); //assertEquals("Wrong aspect ratio", data.getDimension().width / (float) data.getDimension().height, aspectRatio, 0f); } catch (IndexOutOfBoundsException expected) { } catch (IOException e) { fail("Could not read image aspect ratio" + e); } } @Test public void testDisposeBeforeRead() { ImageReader reader = createReader(); reader.dispose(); // Just pass with no exceptions } @Test public void testDisposeAfterRead() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); reader.dispose(); // Just pass with no exceptions } @Test public void testAddIIOReadProgressListener() { ImageReader reader = createReader(); reader.addIIOReadProgressListener(mock(IIOReadProgressListener.class)); } @Test public void testAddIIOReadProgressListenerNull() { ImageReader reader = createReader(); reader.addIIOReadProgressListener(null); } @Test public void testAddIIOReadProgressListenerCallbacks() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listener); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // At least imageStarted and imageComplete, plus any number of imageProgress InOrder ordered = inOrder(listener); ordered.verify(listener).imageStarted(reader, 0); ordered.verify(listener, atLeastOnce()).imageProgress(eq(reader), anyInt()); ordered.verify(listener).imageComplete(reader); } @Test public void testMultipleAddIIOReadProgressListenerCallbacks() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class); IIOReadProgressListener listenerToo = mock(IIOReadProgressListener.class); IIOReadProgressListener listenerThree = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listener); reader.addIIOReadProgressListener(listenerToo); reader.addIIOReadProgressListener(listenerThree); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // At least imageStarted and imageComplete, plus any number of imageProgress InOrder ordered = inOrder(listener, listenerToo, listenerThree); ordered.verify(listener).imageStarted(reader, 0); ordered.verify(listenerToo).imageStarted(reader, 0); ordered.verify(listenerThree).imageStarted(reader, 0); ordered.verify(listener, atLeastOnce()).imageProgress(eq(reader), anyInt()); ordered.verify(listenerToo, atLeastOnce()).imageProgress(eq(reader), anyInt()); ordered.verify(listenerThree, atLeastOnce()).imageProgress(eq(reader), anyInt()); ordered.verify(listener).imageComplete(reader); ordered.verify(listenerToo).imageComplete(reader); ordered.verify(listenerThree).imageComplete(reader); } @Test public void testRemoveIIOReadProgressListenerNull() { ImageReader reader = createReader(); reader.removeIIOReadProgressListener(null); } @Test public void testRemoveIIOReadProgressListenerNone() { ImageReader reader = createReader(); reader.removeIIOReadProgressListener(mock(IIOReadProgressListener.class)); } @Test public void testRemoveIIOReadProgressListener() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listener); reader.removeIIOReadProgressListener(listener); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // Should not have called any methods... verifyZeroInteractions(listener); } @Test public void testRemoveIIOReadProgressListenerMultiple() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class, "Listener1"); reader.addIIOReadProgressListener(listener); IIOReadProgressListener listenerToo = mock(IIOReadProgressListener.class, "Listener2"); reader.addIIOReadProgressListener(listenerToo); reader.removeIIOReadProgressListener(listener); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // Should not have called any methods on listener1... verifyZeroInteractions(listener); InOrder ordered = inOrder(listenerToo); ordered.verify(listenerToo).imageStarted(reader, 0); ordered.verify(listenerToo, atLeastOnce()).imageProgress(eq(reader), anyInt()); ordered.verify(listenerToo).imageComplete(reader); } @Test public void testRemoveAllIIOReadProgressListeners() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listener); reader.removeAllIIOReadProgressListeners(); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // Should not have called any methods... verifyZeroInteractions(listener); } @Test public void testRemoveAllIIOReadProgressListenersMultiple() { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listener); IIOReadProgressListener listenerToo = mock(IIOReadProgressListener.class); reader.addIIOReadProgressListener(listenerToo); reader.removeAllIIOReadProgressListeners(); try { reader.read(0); } catch (IOException e) { fail("Could not read image"); } // Should not have called any methods... verifyZeroInteractions(listener); verifyZeroInteractions(listenerToo); } @Test public void testAbort() { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); IIOReadProgressListener listener = mock(IIOReadProgressListener.class, "Progress1"); reader.addIIOReadProgressListener(listener); IIOReadProgressListener listenerToo = mock(IIOReadProgressListener.class, "Progress2"); reader.addIIOReadProgressListener(listenerToo); // Create a listener that just makes the reader abort immediately... IIOReadProgressListener abortingListener = mock(IIOReadProgressListener.class, "Aborter"); Answer<Void> abort = new Answer<Void>() { public Void answer(InvocationOnMock invocation) throws Throwable { reader.abort(); return null; } }; doAnswer(abort).when(abortingListener).imageStarted(any(ImageReader.class), anyInt()); doAnswer(abort).when(abortingListener).imageProgress(any(ImageReader.class), anyInt()); reader.addIIOReadProgressListener(abortingListener); try { reader.read(0); } catch (IOException e) { failBecause("Image could not be read", e); } verify(listener).readAborted(reader); verify(listenerToo).readAborted(reader); } @Test public void testGetTypeSpecifiers() throws IOException { final ImageReader reader = createReader(); for (TestData data : getTestData()) { reader.setInput(data.getInputStream()); ImageTypeSpecifier rawType = reader.getRawImageType(0); if (rawType == null && allowsNullRawImageType()) { continue; } assertNotNull(rawType); Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0); assertNotNull(types); assertTrue(types.hasNext()); // TODO: This might fail even though the specifiers are obviously equal, if the // color spaces they use are not the SAME instance, as ColorSpace uses identity equals // and Interleaved ImageTypeSpecifiers are only equal if color spaces are equal... boolean rawFound = false; while (types.hasNext()) { ImageTypeSpecifier type = types.next(); if (type.equals(rawType)) { rawFound = true; break; } } assertTrue("ImageTypeSepcifier from getRawImageType should be in the iterator from getImageTypes", rawFound); } } @Test public void testSetDestination() throws IOException { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0); while (types.hasNext()) { ImageTypeSpecifier type = types.next(); BufferedImage destination = type.createBufferedImage(50, 50); param.setDestination(destination); BufferedImage result = null; try { result = reader.read(0, param); } catch (Exception e) { failBecause("Could not read " + data.getInput() + " with explicit destination " + destination, e); } assertSame(destination, result); } } @Test public void testSetDestinationRaw() throws IOException { ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); ImageTypeSpecifier type = reader.getRawImageType(0); if (type != null) { BufferedImage destination = type.createBufferedImage(reader.getWidth(0), reader.getHeight(0)); param.setDestination(destination); BufferedImage result = null; try { result = reader.read(0, param); } catch (Exception e) { failBecause("Image could not be read", e); } assertSame(destination, result); } else { System.err.println("WARNING: Test skipped due to reader.getRawImageType(0) returning null"); } } @Test public void testSetDestinationIllegal() throws IOException { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); List<ImageTypeSpecifier> illegalTypes = createIllegalTypes(reader.getImageTypes(0)); ImageReadParam param = reader.getDefaultReadParam(); for (ImageTypeSpecifier illegalType : illegalTypes) { BufferedImage destination = illegalType.createBufferedImage(50, 50); param.setDestination(destination); try { BufferedImage result = reader.read(0, param); // NOTE: We allow the reader to read, as it's inconvenient to test all possible cases. // However, it may NOT fail with any other exception in that case. // TODO: Special case for BufferedImage type 2/3 and 6/7 System.err.println("WARNING: Reader does not throw exception with non-declared destination: " + destination); // Test that the destination is really taken into account assertSame(destination, result); } catch (IIOException expected) { // TODO: This is thrown by ImageReader.getDestination. But are we happy with that? String message = expected.getMessage().toLowerCase(); if (!(message.contains("destination") || message.contains("band size") || // For JDK classes ((destination.getType() == BufferedImage.TYPE_BYTE_BINARY || destination.getType() == BufferedImage.TYPE_BYTE_INDEXED) && message.contains("indexcolormodel")))) { failBecause( "Wrong message: " + message + " for type " + destination.getType(), expected ); } } catch (IllegalArgumentException expected) { String message = expected.getMessage().toLowerCase(); assertTrue("Wrong message: " + message, message.contains("dest")); } } } @Test public void testSetDestinationTypeIllegal() throws IOException { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); List<ImageTypeSpecifier> illegalTypes = createIllegalTypes(reader.getImageTypes(0)); ImageReadParam param = reader.getDefaultReadParam(); for (ImageTypeSpecifier illegalType : illegalTypes) { param.setDestinationType(illegalType); try { reader.read(0, param); fail("Expected to throw exception with illegal type specifier"); } catch (IIOException expected) { // TODO: This is thrown by ImageReader.getDestination. But are we happy with that? String message = expected.getMessage().toLowerCase(); if (!(message.contains("destination") && message.contains("type"))) { // Allow this to bubble up, du to a bug in the Sun PNGImageReader throw expected; } } catch (IllegalArgumentException expected) { String message = expected.getMessage().toLowerCase(); if (!(message.contains("destination") && message.contains("type"))) { // Allow this to bubble up, du to a bug in the Sun PNGImageReader throw expected; } } } } private List<ImageTypeSpecifier> createIllegalTypes(Iterator<ImageTypeSpecifier> pValidTypes) { List<ImageTypeSpecifier> allTypes = new ArrayList<ImageTypeSpecifier>(); for (int i = BufferedImage.TYPE_INT_RGB; i < BufferedImage.TYPE_BYTE_INDEXED; i++) { allTypes.add(ImageTypeSpecifier.createFromBufferedImageType(i)); } List<ImageTypeSpecifier> illegalTypes = new ArrayList<ImageTypeSpecifier>(allTypes); while (pValidTypes.hasNext()) { ImageTypeSpecifier valid = pValidTypes.next(); boolean removed = illegalTypes.remove(valid); // TODO: 4BYTE_ABGR (6) and 4BYTE_ABGR_PRE (7) is essentially the same type... // #$@*%$! ImageTypeSpecifier.equals is not well-defined if (!removed) { for (Iterator<ImageTypeSpecifier> iterator = illegalTypes.iterator(); iterator.hasNext();) { ImageTypeSpecifier illegalType = iterator.next(); if (illegalType.getBufferedImageType() == valid.getBufferedImageType()) { iterator.remove(); } } } } return illegalTypes; } // TODO: Test dest offset + destination set? // TODO: Test that destination offset is used for image data, not just image dimensions... @Test public void testSetDestinationOffset() throws IOException { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); Point point = new Point(37, 42); param.setDestinationOffset(point); BufferedImage image = reader.read(0, param); assertNotNull(image); assertEquals(reader.getWidth(0) + point.x, image.getWidth()); assertEquals(reader.getHeight(0) + point.y, image.getHeight()); } @Test public void testSetDestinationOffsetNull() throws IOException { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); try { param.setDestinationOffset(null); fail("Null offset not allowed"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().toLowerCase().contains("offset")); } } @Test public void testSetDestinationType() throws IOException { final ImageReader reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); ImageReadParam param = reader.getDefaultReadParam(); Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0); while (types.hasNext()) { ImageTypeSpecifier type = types.next(); param.setDestinationType(type); BufferedImage result = null; try { result = reader.read(0, param); } catch (Exception e) { failBecause("Could not read " + data.getInput() + " with explicit destination type " + type, e); } assertNotNull(result); assertEquals(type.getColorModel(), result.getColorModel()); // The following logically tests // assertEquals(type.getSampleModel(), result.getSampleModel()); // but SampleModel does not have a proper equals method. SampleModel expectedModel = type.getSampleModel(); SampleModel resultModel = result.getSampleModel(); assertEquals(expectedModel.getDataType(), resultModel.getDataType()); assertEquals(expectedModel.getNumBands(), resultModel.getNumBands()); assertEquals(expectedModel.getNumDataElements(), resultModel.getNumDataElements()); assertTrue(Arrays.equals(expectedModel.getSampleSize(), resultModel.getSampleSize())); assertEquals(expectedModel.getTransferType(), resultModel.getTransferType()); for (int i = 0; i < expectedModel.getNumBands(); i++) { assertEquals(expectedModel.getSampleSize(i), resultModel.getSampleSize(i)); } } } @Test public void testNotBadCaching() throws IOException { T reader = createReader(); TestData data = getTestData().get(0); reader.setInput(data.getInputStream()); BufferedImage one = reader.read(0); BufferedImage two = reader.read(0); assertNotSame("Multiple reads return same (mutable) image", one, two); Graphics2D g = one.createGraphics(); try { g.setColor(Color.WHITE); g.setXORMode(Color.BLACK); g.fillRect(0, 0, one.getWidth(), one.getHeight()); } finally { g.dispose(); } assertTrue(one.getRGB(0, 0) != two.getRGB(0, 0)); } @Test public void testNotBadCachingThumbnails() throws IOException { T reader = createReader(); if (reader.readerSupportsThumbnails()) { for (TestData data : getTestData()) { reader.setInput(data.getInputStream()); int images = reader.getNumImages(true); for (int i = 0; i < images; i++) { int thumbnails = reader.getNumThumbnails(0); for (int j = 0; j < thumbnails; j++) { BufferedImage one = reader.readThumbnail(i, j); BufferedImage two = reader.readThumbnail(i, j); assertNotSame("Multiple reads return same (mutable) image", one, two); Graphics2D g = one.createGraphics(); try { g.setColor(Color.WHITE); g.setXORMode(Color.BLACK); g.fillRect(0, 0, one.getWidth(), one.getHeight()); } finally { g.dispose(); } assertTrue(one.getRGB(0, 0) != two.getRGB(0, 0)); } if (thumbnails > 0) { // We've tested thumbnails, let's get out of here return; } } } fail("No thumbnails tested for reader that supports thumbnails."); } } @Ignore("TODO: Implement") @Test public void testSetDestinationBands() throws IOException { throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement } @Ignore("TODO: Implement") @Test public void testSetSourceBands() throws IOException { throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement } @Test public void testProviderAndMetadataFormatNamesMatch() throws IOException { ImageReaderSpi provider = createProvider(); ImageReader reader = createReader(); reader.setInput(getTestData().get(0).getInputStream()); IIOMetadata imageMetadata = reader.getImageMetadata(0); if (imageMetadata != null) { assertEquals(provider.getNativeImageMetadataFormatName(), imageMetadata.getNativeMetadataFormatName()); } IIOMetadata streamMetadata = reader.getStreamMetadata(); if (streamMetadata != null) { assertEquals(provider.getNativeStreamMetadataFormatName(), streamMetadata.getNativeMetadataFormatName()); } } protected URL getClassLoaderResource(final String pName) { return getClass().getResource(pName); } static final protected class TestData { private final Object input; private final List<Dimension> sizes; private final List<BufferedImage> images; public TestData(final Object pInput, final Dimension... pSizes) { this(pInput, Arrays.asList(pSizes), null); } public TestData(final Object pInput, final BufferedImage... pImages) { this(pInput, null, Arrays.asList(pImages)); } public TestData(final Object pInput, final List<Dimension> pSizes, final List<BufferedImage> pImages) { if (pInput == null) { throw new IllegalArgumentException("input == null"); } sizes = new ArrayList<Dimension>(); images = new ArrayList<BufferedImage>(); List<Dimension> sizes = pSizes; if (sizes == null) { sizes = new ArrayList<Dimension>(); if (pImages != null) { for (BufferedImage image : pImages) { sizes.add(new Dimension(image.getWidth(), image.getHeight())); } } else { throw new IllegalArgumentException("Need either size or image"); } } else if (pImages != null) { if (pImages.size() != pSizes.size()) { throw new IllegalArgumentException("Size parameter and image size differs"); } for (int i = 0; i < sizes.size(); i++) { if (!new Dimension(pImages.get(i).getWidth(), pImages.get(i).getHeight()).equals(sizes.get(i))) { throw new IllegalArgumentException("Size parameter and image size differs"); } } } this.sizes.addAll(sizes); if (pImages != null) { images.addAll(pImages); } input = pInput; } public Object getInput() { return input; } public ImageInputStream getInputStream() { try { ImageInputStream stream = ImageIO.createImageInputStream(input); assertNotNull("Could not create ImageInputStream for input: " + input, stream); return stream; } catch (IOException e) { failBecause("Could not create ImageInputStream for input: " + input, e); } return null; } public int getImageCount() { return sizes.size(); } public Dimension getDimension(final int pIndex) { return sizes.get(pIndex); } public BufferedImage getImage(final int pIndex) { return images.get(pIndex); } @Override public String toString() { return getClass().getSimpleName() + ": " + String.valueOf(input); } } }
package net.galaxygaming.util; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; /** * @author t7seven7t */ public class LocationUtil { public LocationUtil() { throw new AssertionError("Cannot instantiate utility class."); } public static String serializeLocation(Location location) { StringBuilder builder = new StringBuilder(); builder.append(location.getWorld().getName()); builder.append(','); builder.append(location.getBlockX()); builder.append(','); builder.append(location.getBlockY()); builder.append(','); builder.append(location.getBlockZ()); return builder.toString(); } public static Location deserializeLocation(String string) { if (string == null) { return null; } String[] args = string.split(","); if (args.length < 4) throw new RuntimeException("Location string was invalid: " + string); int x, y, z; try { x = Integer.valueOf(args[1]); y = Integer.valueOf(args[2]); z = Integer.valueOf(args[3]); } catch (NumberFormatException e) { throw new RuntimeException("Location string was invalid: " + string); } World world = Bukkit.getWorld(args[0]); if (world == null) throw new RuntimeException("Location string was invalid: " + string); return new Location(world, x, y, z); } }
package net.glowstone.command; import net.glowstone.GlowWorld; import net.glowstone.ServerProvider; import net.glowstone.block.state.BlockStateData; import net.glowstone.block.state.InvalidBlockStateException; import net.glowstone.block.state.StateSerialization; import org.apache.commons.lang.math.NumberUtils; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Entity; public class CommandUtils { private CommandUtils() { } private static double getDouble(String d, boolean shift) { boolean literal = d.split("\\.").length != 1; if (shift && !literal) { d += ".5"; } return Double.valueOf(d); } /** * Parses a block state from a string. * * @param sender the target who should receive an error message if {@code state} is * invalid * @param type the block type * @param state a string specifying a block state * @return the block state for {@code type} and {@code state}, or null if none match */ public static BlockStateData readState(CommandSender sender, Material type, String state) { if (NumberUtils.isNumber(state)) { return new BlockStateData(Byte.parseByte(state)); } try { return StateSerialization.parse(type, state); } catch (InvalidBlockStateException e) { sender.sendMessage(ChatColor.RED + e.getMessage()); return null; } } /** * Converts an array of entities to a readable string. * * @param entities one or more entities * @return a list of the entities' names, formatted like "Alice, Bob and Creeper" * @deprecated Use one of the {@code joinList} overloads in * {@link net.glowstone.command.minecraft.GlowVanillaCommand}'s inner class CommandMessages. */ @Deprecated public static String prettyPrint(Entity[] entities) { String[] names = new String[entities.length]; for (int i = 0; i < entities.length; i++) { names[i] = entities[i].getName(); } return prettyPrint(names); } /** * Converts an array of strings describing list items to a single string listing them. * * @param strings one or more strings * @return a list of the strings, formatted like "a, b and c" * @deprecated Use one of the {@code joinList} overloads in * {@link net.glowstone.command.minecraft.GlowVanillaCommand}'s inner class CommandMessages. */ @Deprecated public static String prettyPrint(String[] strings) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < strings.length; i++) { String string = strings[i]; if (i == strings.length - 1 && strings.length > 1) { builder.append(" and "); } else if (i > 0) { builder.append(", "); } builder.append(string); } return builder.toString(); } // TODO: Move this into the Server class within Glowkit, and implement it with GlowServer. private static GlowWorld getDefaultWorld() { return (GlowWorld) ServerProvider.getServer().getWorlds().get(0); } /** * Returns the world that the given command sender is referring to when not specifying one. * * @param sender a command sender * @return the command sender's world if the sender is a block or entity, or the default world * otherwise */ public static GlowWorld getWorld(CommandSender sender) { if (sender instanceof ConsoleCommandSender) { return getDefaultWorld(); } else if (sender instanceof Entity) { return (GlowWorld) ((Entity) sender).getWorld(); } else if (sender instanceof BlockCommandSender) { return (GlowWorld) ((BlockCommandSender) sender).getBlock().getWorld(); } return getDefaultWorld(); } /** * Gets the location that is "~ ~ ~" for a command sender. * * @param sender a command sender * @return the sender's location if the sender is a block or entity, or the default world's * coordinate origin otherwise. */ public static Location getLocation(CommandSender sender) { if (sender instanceof Entity) { return ((Entity) sender).getLocation(); } else if (sender instanceof BlockCommandSender) { return ((BlockCommandSender) sender).getBlock().getLocation(); } return new Location(getDefaultWorld(), 0, 0, 0); } /** * Parses coordinates that may be absolute or relative. * * @param sender the command sender * @param x the x coordinate specifier * @param y the y coordinate specifier * @param z the z coordinate specifier * @return the coordinates */ public static Location getLocation(CommandSender sender, String x, String y, String z) { Location currentLocation; if (x.startsWith("~") || y.startsWith("~") || z .startsWith("~")) { // The coordinates are relative currentLocation = getLocation(sender); } else { // Otherwise, the current location can be set to 0/0/0 (since it's absolute) currentLocation = new Location(getWorld(sender), 0, 0, 0); } return getLocation(currentLocation, x, y, z); } /** * <p>Gets the relative location based on the given axis values (x/y/z) based on tilde * notation.</p> * * <p>For instance, using axis values of ~10 ~ ~15 will return the location with the offset of * the given rotation values. * * @param location the initial location * @param relativeX the relative x-axis (if there is no tilde [~], then the literal * value is used) * @param relativeY the relative y-axis (if there is no tilde [~], then the literal * value is used) * @param relativeZ the relative z-axis (if there is no tilde [~], then the literal * value is used) * @return the relative location */ public static Location getLocation(Location location, String relativeX, String relativeY, String relativeZ) { double x; double y; double z; if (relativeX.startsWith("~")) { double diff = 0; if (relativeX.length() > 1) { diff = getDouble(relativeX.substring(1), true); } x = location.getX() + diff; } else { x = getDouble(relativeX, true); } if (relativeY.startsWith("~")) { double diff = 0; if (relativeY.length() > 1) { diff = getDouble(relativeY.substring(1), false); } y = location.getY() + diff; } else { y = getDouble(relativeY, false); } if (relativeZ.startsWith("~")) { double diff = 0; if (relativeZ.length() > 1) { diff = getDouble(relativeZ.substring(1), true); } z = location.getZ() + diff; } else { z = getDouble(relativeZ, true); } return new Location(location.getWorld(), x, y, z); } /** * <p>Gets the relative location based on the given rotation values (yaw/relative) based on * tilde notation.</p> * * <p>For instance, using rotations of ~10 ~15 will return the location with the offset of the * given rotation values.</p> * * @param location the initial location * @param yawRelative the relative yaw (if there is no tilde [~], then the literal value * is used) * @param pitchRelative the relative pitch (if there is no tilde [~], then the literal * value is used) * @return the relative location */ public static Location getRotation(Location location, String yawRelative, String pitchRelative) { float yaw; if (yawRelative.startsWith("~")) { float diff = 0; if (yawRelative.length() > 1) { diff = Float.valueOf(yawRelative.substring(1)); } yaw = location.getYaw() + diff; } else { yaw = Float.valueOf(yawRelative); } float pitch; if (pitchRelative.startsWith("~")) { float diff = 0; if (pitchRelative.length() > 1) { diff = Float.valueOf(pitchRelative.substring(1)); } pitch = location.getPitch() + diff; } else { pitch = Float.valueOf(pitchRelative); } return new Location(location.getWorld(), location.getX(), location.getY(), location.getZ(), yaw, pitch); } /** * Gets the name of a command sender. * * @param sender the sender * @return the sender's name */ public static String getName(CommandSender sender) { if (sender instanceof Entity) { return getName((Entity) sender); } return sender.getName(); } /** * Gets the name of an entity. * * @param entity an entity * @return the first of the following that exists and is non-empty: {@code * entity.getCustomName()}, {@code entity.getName()}, {@code * entity.getType().getName()} */ public static String getName(Entity entity) { String customName = entity.getCustomName(); if (customName != null && !customName.isEmpty()) { return customName; } String name = entity.getName(); if (name == null || name.isEmpty()) { name = entity.getType().getName(); } return name; } public static boolean isPhysical(CommandSender sender) { return sender instanceof Entity || sender instanceof BlockCommandSender; } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package com.milkenknights; import com.milkenknights.InsightLT.DecimalData; import com.milkenknights.InsightLT.InsightLT; import com.milkenknights.InsightLT.StringData; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SafePWM; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Knight extends IterativeRobot { private static final double JITTER_RANGE = 0.008; JStick xbox; // XBox controller JStick atk; // Logitech ATK3 controller private boolean usingCheesy; private DriverStationLCD lcd; private Compressor compressor; // Pair state "true" means high gear, // Pair state "false" means low gear private SolenoidPair driveGear; private SolenoidPair ingestSolenoids; //public final static PrefsHelper prefs = new PrefsHelper(); public static PrefsHelper prefs; private Drive drive; private SpeedController shooter; private SpeedController intake; private SpeedController actuator; private SpeedController kicker; private Counter shooterEnc; private Encoder lWheels; private Encoder rWheels; // stuff for the InsightLT display private InsightLT display; private DecimalData disp_batteryVoltage; private StringData disp_message; public Knight() { prefs = new PrefsHelper(); // get robot preferences, stored on the cRIO drive = new Drive(new Talon(prefs.getInt("leftmotor",4)), new Talon(prefs.getInt("rightmotor",9))); shooter = new Talon(prefs.getInt("shooter", 6)); intake = new Talon(prefs.getInt("intake", 8)); actuator = new Talon(prefs.getInt("actuator", 1)); kicker = new Talon(prefs.getInt("kicker",5)); xbox = new JStick(1); atk = new JStick(2); lcd = DriverStationLCD.getInstance(); usingCheesy = true; integral_err = 0; prev_err = 0; // pressure sensor is 3 compressor = new Compressor(5,1); driveGear = new SolenoidXORPair(2,1); ingestSolenoids = new SolenoidXANDPair(3,4); shooterEnc = new Counter(1); lWheels = new Encoder(3,4); rWheels = new Encoder(6,7); // configure the display to have two lines of text display = new InsightLT(InsightLT.TWO_ONE_LINE_ZONES); display.startDisplay(); // add battery display disp_batteryVoltage = new DecimalData("Bat:"); display.registerData(disp_batteryVoltage,1); // this shows what mode the robot is in // i.e. teleop, autonomous, disabled disp_message = new StringData(); display.registerData(disp_message,2); } /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { compressor.start(); driveGear.set(true); drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true); drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft,true); shooterEnc.start(); } //This function is called at the start of autonomous Timer timer; public void autonomousInit() { /* kicker.set(-1.0); timer.start(); */ } /** * This function is called periodically during autonomous */ double integral_err; double prev_err; double last_timer; public void autonomousPeriodic() { SmartDashboard.putNumber("time",Timer.getFPGATimestamp()); /* //drive.tankDrive(0.4, 0.4); disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("autonomous"); if (timer.get() > 1000) { shooter.set(-1); } if (timer.get() > 6000) { actuator.set(0.4); } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); */ } /** * This function is called periodically during operator control */ public void teleopPeriodic() { xbox.update(); atk.update(); // Press A to toggle cheesy drive if (xbox.isReleased(JStick.XBOX_A)) { usingCheesy = !usingCheesy; } // use LB to toggle high and low gear if (xbox.isReleased(JStick.XBOX_LB)) { driveGear.toggle(); } // show the solenoids status lcd.println(DriverStationLCD.Line.kUser3,1,driveGear.get()?"High Gear":"Low Gear "); // show if the compressor is running if (compressor.getPressureSwitchValue()) { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is off "); } else { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is running"); } /* // Old control system // joystick button 1 should spin the shooter and kicker // but the actuator shouldn't run unless the // shooter is at full speed if (atk.isPressed(1)) { shooter.set(-1); kicker.set(-1); // replace the 0.001 with the actual speed if (shooterEnc.getPeriod() < 0.001) { actuator.set(1); } else { actuator.set(0); } } else { shooter.set(0); kicker.set(0); actuator.set(0); } */ // New control system // joystick button 1 spins the actuator // joystick button 2 spins the shooter and kicker // this control system does not use the optical encoders actuator.set(atk.isPressed(1) ? 1 : 0); shooter.set(atk.isPressed(2) ? -1 : 0); kicker.set(atk.isPressed(2) ? -1 : 0); // hold down atk 2 to use the ingestor //ingestSolenoids.set(atk.isPressed(2)); //intake.set(atk.isPressed(2) ? 1 : 0); if (xbox.isPressed(JStick.XBOX_A)) { ingestSolenoids.set(true); intake.set(1); } else { ingestSolenoids.set(false); intake.set(0); } double leftStickX = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSX), JITTER_RANGE); double leftStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSY), JITTER_RANGE); double rightStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_RSY), JITTER_RANGE); if (usingCheesy) { drive.cheesyDrive(rightStickY, leftStickX, xbox.isPressed(JStick.XBOX_LJ)); lcd.println(DriverStationLCD.Line.kUser4,1,"cheesy drive"); } else { if (!drive.straightDrive(xbox.getAxis(JStick.XBOX_TRIG))) { drive.tankDrive(leftStickY, rightStickY); lcd.println(DriverStationLCD.Line.kUser4,1,"tank drive "); } else { lcd.println(DriverStationLCD.Line.kUser4,1,"straightDrive"); } } // print encoder values to see if they're working lcd.println(DriverStationLCD.Line.kUser2,1,""+shooterEnc.getPeriod()); lcd.println(DriverStationLCD.Line.kUser5, 1,""+lWheels.get()+" "+rWheels.get()); SmartDashboard.putNumber("Shooter speed", shooterEnc.getPeriod()); lcd.updateLCD(); // update the display disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("teleop"); } public void disabledPeriodic() { disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("disabled"); } private boolean shootTester; private boolean pwmtest; private SafePWM[] pwms; public void testInit() { timer.start(); pwmtest = false; pwms = new SafePWM[10]; for (int i = 0; i < 10; ++i) { pwms[i] = new SafePWM(i+1); } } /** * This function is called periodically during test mode */ public void testPeriodic() { xbox.update(); atk.update(); // toggle between PWM test and austin's thing if (xbox.isPressed(JStick.XBOX_LB)) { pwmtest = false; } if (xbox.isPressed(JStick.XBOX_RB)) { pwmtest = true; } if (pwmtest) { for (int i = 0; i < 10; ++i) { if (atk.isPressed(i+1)) { pwms[i].setRaw(143); } } } else { if (xbox.isReleased(JStick.XBOX_A)) { shootTester = !shootTester; lcd.println(DriverStationLCD.Line.kUser1, 1, "Shooter Tester "); } else { lcd.println(DriverStationLCD.Line.kUser1, 1, "Normal Tester "); } //Only spins shooter shooter.set((atk.isPressed(7)) ? -1 : 0); //Only spins the kicker kicker.set((atk.isPressed(6)) ? -1 : 0); //Slow start for shooting 1 if(shootTester && atk.isPressed(1)) { if(timer.get() > 2) { shooter.set(1); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: On "); } if(timer.get() > 4) { kicker.set(1); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: On "); } if(timer.get() > 7) { //actuator.set(1); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: On "); } else { timer.reset(); shooter.set(0); kicker.set(0); actuator.set(0); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: Off "); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: Off "); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: Off "); } } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); } } }
package org.apache.couchdb.lucene; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.io.IOUtils; /** * Communication with couchdb. * * @author rnewson * */ public final class Database { static final HttpClient CLIENT = new HttpClient(); private static final String[] EMPTY_ARR = new String[0]; static { CLIENT.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } private final String url; public Database(final String url) { if (url.endsWith("/")) this.url = url.substring(0, url.length() - 1); else this.url = url; } public String[] getAllDatabases() throws HttpException, IOException { return (String[]) JSONArray.fromObject(get("_all_dbs")).toArray(EMPTY_ARR); } public JSONObject getAllDocsBySeq(final String dbname, final long from, final int limit) throws HttpException, IOException { return JSONObject.fromObject(get(String.format("%s/_all_docs_by_seq?startkey=%s&limit=%d&include_docs=true", encode(dbname), from, limit))); } public JSONObject getDoc(final String dbname, final String id, final String rev) throws HttpException, IOException { if (rev == null) return JSONObject.fromObject(get(String.format("%s/%s", encode(dbname), id))); else return JSONObject.fromObject(get(String.format("%s/%s?rev=%s", encode(dbname), id, rev))); } public JSONObject getDocs(final String dbname, final String... ids) throws HttpException, IOException { final JSONArray keys = new JSONArray(); for (final String id : ids) { keys.add(id); } final JSONObject req = new JSONObject(); req.element("keys", keys); return JSONObject.fromObject(post(String.format("%s/_all_docs?include_docs=true", encode(dbname)), req.toString())); } public JSONObject getInfo(final String dbname) throws HttpException, IOException { return JSONObject.fromObject(get(encode(dbname))); } private String get(final String path) throws HttpException, IOException { return execute(new GetMethod(url(path))); } String url(final String path) { return String.format("%s/%s", url, path); } String encode(final String path) { try { return URLEncoder.encode(path, "UTF-8"); } catch (final UnsupportedEncodingException e) { throw new Error("UTF-8 support missing!"); } } private String post(final String path, final String body) throws HttpException, IOException { final PostMethod post = new PostMethod(url(path)); post.setRequestEntity(new StringRequestEntity(body, "application/json", "UTF-8")); return execute(post); } private synchronized String execute(final HttpMethodBase method) throws HttpException, IOException { try { CLIENT.executeMethod(method); final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return writer.toString(); } finally { in.close(); } } finally { method.releaseConnection(); } } }
package org.clafer.compiler; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.chocosolver.solver.Solver; import org.chocosolver.solver.variables.BoolVar; import org.clafer.assertion.Assertion; import org.clafer.choco.constraint.Constraints; import org.clafer.collection.Either; import org.clafer.common.Check; import org.clafer.instance.InstanceModel; /** * * @author jimmy */ public class ClaferAsserter implements ClaferSearch { private final Solver solver; private final ClaferSolutionMap solutionMap; private final Map<Assertion, Either<Boolean, BoolVar>> assertions; private int count = 0; private boolean more = true; public ClaferAsserter(Solver solver, ClaferSolutionMap solutionMap, Map<Assertion, Either<Boolean, BoolVar>> assertions) { this.solver = Check.notNull(solver); this.solutionMap = Check.notNull(solutionMap); this.assertions = Check.notNull(assertions); } public ClaferAsserter() { this.solver = new Solver(); this.solutionMap = null; this.assertions = null; this.more = false; } @Override public boolean find() { if (!more) { return false; } more &= count == 0 ? solveFirst() : solveNext(); if (solver.hasReachedLimit()) { more = false; throw new ReachedLimitException(); } if (more) { count++; } return more; } private boolean solveFirst() { List<BoolVar> boolVars = new ArrayList<>(assertions.size()); for (Either<?, BoolVar> assertion : assertions.values()) { if (assertion.isLeft() && assertion.getLeft().equals(Boolean.TRUE)) { return solver.findSolution(); } else if (assertion.isRight()) { boolVars.add(assertion.getRight()); } } if (boolVars.isEmpty()) { return false; } solver.post(Constraints.or(boolVars.toArray(new BoolVar[boolVars.size()]))); return solver.findSolution(); } private boolean solveNext() { List<BoolVar> boolVars = new ArrayList<>(assertions.size()); for (Either<?, BoolVar> assertion : assertions.values()) { if (assertion.isRight()) { BoolVar boolVar = assertion.getRight(); if (boolVar.isInstantiatedTo(0)) { boolVars.add(boolVar); } } } if (boolVars.isEmpty()) { return false; } solver.post(Constraints.or(boolVars.toArray(new BoolVar[boolVars.size()]))); return solver.nextSolution(); } public Assertion[] failedAssertions() { if (count == 0 || !more) { throw new IllegalStateException("No instances. Did you forget to call find?"); } List<Assertion> failedAssertions = new ArrayList<>(assertions.size()); for (Entry<Assertion, Either<Boolean, BoolVar>> assertion : assertions.entrySet()) { Either<Boolean, BoolVar> value = assertion.getValue(); if (value.isLeft() && value.getLeft().equals(Boolean.TRUE)) { failedAssertions.add(assertion.getKey()); } else if (value.isRight() && value.getRight().getValue() == 1) { failedAssertions.add(assertion.getKey()); } } return failedAssertions.toArray(new Assertion[failedAssertions.size()]); } @Override public InstanceModel instance() { if (count == 0 || !more) { throw new IllegalStateException("No instances. Did you forget to call find?"); } return solutionMap.getInstance(); } @Override public int instanceCount() { return count; } @Override public Solver getInternalSolver() { return solver; } }
package org.codemucker.jpattern; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used in generator annotations to define a dependency of some sort */ @Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.ANNOTATION_TYPE) public @interface Dependency { String group(); String artifact() default ""; String classifier() default ""; String extension() default ""; }
package org.funcj.codec.json; import org.funcj.codec.*; import org.funcj.control.Exceptions; import org.funcj.json.Node; import java.lang.reflect.*; import java.util.*; public class JsonCodecCore extends CodecCore<Node> { protected String typeFieldName() { return "@type"; } protected String keyFieldName() { return "@key"; } protected String valueFieldName() { return "@value"; } private final Codec.NullCodec<Node> nullCodec = new Codec.NullCodec<Node>() { @Override public boolean isNull(Node in) { return in.isNull(); } @Override public Node encode(Object val, Node out) { return Node.nul(); } @Override public Object decode(Node in) { in.asNull(); return null; } }; @Override public <T> Node encode(Class<T> type, T val) { return super.encode(type, val, null); } @Override protected Codec.NullCodec<Node> nullCodec() { return nullCodec; } private final Codec.BooleanCodec<Node> booleanCodec = new Codec.BooleanCodec<Node>() { @Override public Node encodePrim(boolean val, Node out) { return Node.bool(val); } @Override public boolean decodePrim(Node in) { return in.asBool().value; } }; @Override protected Codec.BooleanCodec<Node> booleanCodec() { return booleanCodec; } private final Codec<boolean[], Node> booleanArrayCodec = new Codec<boolean[], Node>() { @Override public Node encode(boolean[] vals, Node out) { final List<Node> nodes = new ArrayList<>(vals.length); for (boolean val : vals) { nodes.add(booleanCodec().encode(val, out)); } return Node.array(nodes); } @Override public boolean[] decode(Node in) { final Node.ArrayNode arrNode = in.asArray(); final boolean[] vals = new boolean[arrNode.values.size()]; int i = 0; for (Node node : arrNode.values) { vals[i++] = booleanCodec().decode(boolean.class, node); } return vals; } }; @Override protected Codec<boolean[], Node> booleanArrayCodec() { return booleanArrayCodec; } private final Codec.IntegerCodec<Node> integerCodec = new Codec.IntegerCodec<Node>() { @Override public Node encodePrim(int val, Node out) { return Node.number(val); } @Override public int decodePrim(Node in) { return (int)in.asNumber().value; } }; @Override protected Codec.IntegerCodec<Node> integerCodec() { return integerCodec; } private final Codec<int[], Node> integerArrayCodec = new Codec<int[], Node>() { @Override public Node encode(int[] vals, Node out) { final List<Node> nodes = new ArrayList<>(vals.length); for (int val : vals) { nodes.add(integerCodec().encode(val, out)); } return Node.array(nodes); } @Override public int[] decode(Node in) { final Node.ArrayNode arrNode = in.asArray(); final int[] vals = new int[arrNode.values.size()]; int i = 0; for (Node node : arrNode.values) { vals[i++] = integerCodec().decode(int.class, node); } return vals; } }; @Override protected Codec<int[], Node> integerArrayCodec() { return integerArrayCodec; } private final Codec<String, Node> stringCodec = new Codec<String, Node>() { @Override public Node encode(String val, Node out) { return Node.string(val); } @Override public String decode(Node in) { return in.asString().value; } }; @Override protected Codec<String, Node> stringCodec() { return stringCodec; } @Override protected <EM extends Enum<EM>> Codec<EM, Node> enumCodec(Class<? super EM> enumType) { return new Codec<EM, Node>() { @Override public Node encode(EM val, Node out) { return Node.string(val.name()); } @Override public EM decode(Class<EM> dynType, Node in) { return EM.valueOf(dynType, in.asString().value); } }; } @Override protected <K, V> Codec<Map<K, V>, Node> mapCodec( Class<K> keyType, Class<V> valType) { final Codec<V, Node> valueCodec = dynamicCodec(valType); if (String.class.equals(keyType)) { return (Codec)new JsonMapCodecs.StringMapCodec<V>(this, valueCodec); } else { final Codec<K, Node> keyCodec = dynamicCodec(keyType); return new JsonMapCodecs.MapCodec<K, V>(this, keyCodec, valueCodec); } } @Override protected <T> Codec<T[], Node> objectArrayCodec(Class<T> elemType, Codec<T, Node> elemCodec) { return new Codec<T[], Node>() { @Override public Node encode(T[] vals, Node out) { final List<Node> nodes = new ArrayList<>(vals.length); for (T val : vals) { nodes.add(elemCodec.encode(val, out)); } return Node.array(nodes); } @Override public T[] decode(Class<T[]> dynType, Node in) { final Class<T> dynElemType = (Class<T>)dynType.getComponentType(); final Node.ArrayNode arrNode = in.asArray(); final T[] vals = (T[]) Array.newInstance(elemType, arrNode.values.size()); int i = 0; for (Node node : arrNode.values) { vals[i++] = elemCodec.decode(dynElemType, node); } return vals; } }; } @Override protected <T> Codec<T, Node> dynamicCodec(Class<T> stcType) { return new Codec<T, Node>() { @Override public Node encode(T val, Node out) { final Class<? extends T> dynType = (Class<? extends T>)val.getClass(); if (dynType.equals(stcType) || Modifier.isFinal(stcType.getModifiers())) { return JsonCodecCore.this.getNullUnsafeCodec(stcType).encode(val, out); } else { final LinkedHashMap<String, Node> fields = new LinkedHashMap<>(); fields.put(typeFieldName(), Node.string(classToName(dynType))); fields.put(valueFieldName(), encode2(JsonCodecCore.this.getNullUnsafeCodec(dynType), val, out)); return Node.object(fields); } } protected <S extends T> Node encode2(Codec<S, Node> codec, T val, Node out) { return codec.encode((S)val, out); } @Override public T decode(Node in) { if (in.isObject()) { final Node.ObjectNode objNode = in.asObject(); final String typeFieldName = typeFieldName(); final String valueFieldName = valueFieldName(); if (objNode.fields.size() == 2 && objNode.fields.containsKey(typeFieldName) && objNode.fields.containsKey(valueFieldName)) { final Node typeNode = objNode.fields.get(typeFieldName()); final Node valueNode = objNode.fields.get(valueFieldName()); return decode2(valueNode, nameToClass(typeNode.asString().value)); } } final Codec<T, Node> codec = JsonCodecCore.this.getNullUnsafeCodec(stcType); return codec.decode(stcType, in); } protected <S extends T> S decode2(Node in, Class<S> dynType) { final Codec<S, Node> codec = JsonCodecCore.this.getNullUnsafeCodec(dynType); return codec.decode(dynType, in); } }; } @Override protected <T> Codec<T, Node> dynamicCodec(Codec<T, Node> codec, Class<T> stcType) { return new Codec<T, Node>() { @Override public Node encode(T val, Node out) { final Class<? extends T> dynType = (Class<? extends T>)val.getClass(); if (dynType.equals(stcType)) { return codec.encode(val, out); } else { final LinkedHashMap<String, Node> fields = new LinkedHashMap<>(); fields.put(typeFieldName(), Node.string(classToName(dynType))); fields.put(valueFieldName(), codec.encode(val, out)); return Node.object(fields); } } @Override public T decode(Node in) { final Node.ObjectNode objNode = in.asObject(); final String typeFieldName = typeFieldName(); final String valueFieldName = valueFieldName(); if (objNode.fields.size() == 2 && objNode.fields.containsKey(typeFieldName) && objNode.fields.containsKey(valueFieldName)) { final Node typeNode = objNode.fields.get(typeFieldName()); final Class<?> dynType = nameToClass(typeNode.asString().value); final Node valueNode = objNode.fields.get(valueFieldName()); return codec.decode((Class<T>)dynType, valueNode); } else { return codec.decode(stcType, in); } } }; } @Override protected <T> Codec<T, Node> createObjectCodec( Class<T> type, Map<String, FieldCodec<Node>> fieldCodecs) { return new Codec<T, Node>() { @Override public Node encode(T val, Node out) { final LinkedHashMap<String, Node> fields = new LinkedHashMap<>(); fieldCodecs.forEach((name, codec) -> fields.put(name, codec.encode(val, out))); return Node.object(fields); } @Override public T decode(Class<T> dynType, Node in) { final Node.ObjectNode objNode = in.asObject(); final T val = Exceptions.wrap(() -> dynType.newInstance(), JsonCodecException::new); fieldCodecs.forEach((name, codec) -> { codec.decode(val, objNode.fields.get(name)); }); return val; } }; } }
package org.java_websocket.drafts; import org.java_websocket.WebSocket.Role; import org.java_websocket.exceptions.*; import org.java_websocket.framing.CloseFrameBuilder; import org.java_websocket.framing.FrameBuilder; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.handshake.*; import org.java_websocket.util.Base64; import org.java_websocket.util.Charsetfunctions; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class Draft_10 extends Draft { private class IncompleteException extends Throwable { /** * It's Serializable. */ private static final long serialVersionUID = 7330519489840500997L; private int preferedsize; public IncompleteException(int preferedsize) { this.preferedsize = preferedsize; } public int getPreferedSize() { return preferedsize; } } public static int readVersion(Handshakedata handshakedata) { String vers = handshakedata.getFieldValue("Sec-WebSocket-Version"); if (vers.length() > 0) { int v; try { v = new Integer(vers.trim()); return v; } catch (NumberFormatException e) { return -1; } } return -1; } private ByteBuffer incompleteframe; private Framedata fragmentedframe = null; private final Random reuseableRandom = new Random(); @Override public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHandshake response) throws InvalidHandshakeException { if (!request.hasFieldValue("Sec-WebSocket-Key") || !response.hasFieldValue("Sec-WebSocket-Accept")) return HandshakeState.NOT_MATCHED; String seckey_answere = response.getFieldValue("Sec-WebSocket-Accept"); String seckey_challenge = request.getFieldValue("Sec-WebSocket-Key"); seckey_challenge = generateFinalKey(seckey_challenge); if (seckey_challenge.equals(seckey_answere)) return HandshakeState.MATCHED; return HandshakeState.NOT_MATCHED; } @Override public HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata) throws InvalidHandshakeException { // Sec-WebSocket-Origin is only required for browser clients int v = readVersion(handshakedata); if (v == 7 || v == 8) return basicAccept(handshakedata) ? HandshakeState.MATCHED : HandshakeState.NOT_MATCHED; return HandshakeState.NOT_MATCHED; } @Override public ByteBuffer createBinaryFrame(Framedata framedata) { ByteBuffer mes = framedata.getPayloadData(); boolean mask = role == Role.CLIENT; // framedata.getTransfereMasked(); int sizebytes = mes.remaining() <= 125 ? 1 : mes.remaining() <= 65535 ? 2 : 8; ByteBuffer buf = ByteBuffer.allocate(1 + (sizebytes > 1 ? sizebytes + 1 : sizebytes) + (mask ? 4 : 0) + mes.remaining()); byte optcode = fromOpcode(framedata.getOpcode()); byte one = (byte) (framedata.isFin() ? -128 : 0); one |= optcode; buf.put(one); byte[] payloadlengthbytes = toByteArray(mes.remaining(), sizebytes); assert (payloadlengthbytes.length == sizebytes); if (sizebytes == 1) { buf.put((byte) (payloadlengthbytes[0] | (mask ? (byte) -128 : 0))); } else if (sizebytes == 2) { buf.put((byte) ((byte) 126 | (mask ? (byte) -128 : 0))); buf.put(payloadlengthbytes); } else if (sizebytes == 8) { buf.put((byte) ((byte) 127 | (mask ? (byte) -128 : 0))); buf.put(payloadlengthbytes); } else throw new RuntimeException("Size representation not supported/specified"); if (mask) { ByteBuffer maskkey = ByteBuffer.allocate(4); maskkey.putInt(reuseableRandom.nextInt()); buf.put(maskkey.array()); for (int i = 0; mes.hasRemaining(); i++) { buf.put((byte) (mes.get() ^ maskkey.get(i % 4))); } } else buf.put(mes); // translateFrame ( buf.array () , buf.array ().length ); assert (buf.remaining() == 0) : buf.remaining(); buf.flip(); return buf; } @Override public List<Framedata> createFrames(ByteBuffer binary, boolean mask) { FrameBuilder curframe = new FramedataImpl1(); try { curframe.setPayload(binary); } catch (InvalidDataException e) { throw new NotSendableException(e); } curframe.setFin(true); curframe.setOptcode(Opcode.BINARY); curframe.setTransferemasked(mask); return Collections.singletonList((Framedata) curframe); } @Override public List<Framedata> createFrames(String text, boolean mask) { FrameBuilder curframe = new FramedataImpl1(); try { curframe.setPayload(ByteBuffer.wrap(Charsetfunctions.utf8Bytes(text))); } catch (InvalidDataException e) { throw new NotSendableException(e); } curframe.setFin(true); curframe.setOptcode(Opcode.TEXT); curframe.setTransferemasked(mask); return Collections.singletonList((Framedata) curframe); } private byte fromOpcode(Opcode opcode) { if (opcode == Opcode.CONTINUOUS) return 0; else if (opcode == Opcode.TEXT) return 1; else if (opcode == Opcode.BINARY) return 2; else if (opcode == Opcode.CLOSING) return 8; else if (opcode == Opcode.PING) return 9; else if (opcode == Opcode.PONG) return 10; throw new RuntimeException("Don't know how to handle " + opcode.toString()); } private String generateFinalKey(String in) { String seckey = in.trim(); String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; MessageDigest sh1; try { sh1 = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return Base64.encodeBytes(sh1.digest(acc.getBytes())); } @Override public ClientHandshakeBuilder postProcessHandshakeRequestAsClient(ClientHandshakeBuilder request) { request.put("Upgrade", "websocket"); request.put("Connection", "Upgrade"); // to respond to a Connection keep alives request.put("Sec-WebSocket-Version", "8"); byte[] random = new byte[16]; reuseableRandom.nextBytes(random); request.put("Sec-WebSocket-Key", Base64.encodeBytes(random)); return request; } @Override public HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake request, ServerHandshakeBuilder response) throws InvalidHandshakeException { response.put("Upgrade", "websocket"); response.put("Connection", request.getFieldValue("Connection")); // to respond to a Connection keep alives response.setHttpStatusMessage("Switching Protocols"); String seckey = request.getFieldValue("Sec-WebSocket-Key"); if (seckey == null) throw new InvalidHandshakeException("missing Sec-WebSocket-Key"); response.put("Sec-WebSocket-Accept", generateFinalKey(seckey)); return response; } private byte[] toByteArray(long val, int bytecount) { byte[] buffer = new byte[bytecount]; int highest = 8 * bytecount - 8; for (int i = 0; i < bytecount; i++) { buffer[i] = (byte) (val >>> (highest - 8 * i)); } return buffer; } private Opcode toOpcode(byte opcode) throws InvalidFrameException { switch (opcode) { case 0: return Opcode.CONTINUOUS; case 1: return Opcode.TEXT; case 2: return Opcode.BINARY; // 3-7 are not yet defined case 8: return Opcode.CLOSING; case 9: return Opcode.PING; case 10: return Opcode.PONG; // 11-15 are not yet defined default: throw new InvalidFrameException("unknow optcode " + (short) opcode); } } @Override public List<Framedata> translateFrame(ByteBuffer buffer) throws LimitExedeedException, InvalidDataException { List<Framedata> frames = new LinkedList<Framedata>(); Framedata cur; if (incompleteframe != null) { // complete an incomplete frame try { buffer.mark(); int available_next_byte_count = buffer.remaining();// The number of bytes received int expected_next_byte_count = incompleteframe.remaining();// The number of bytes to complete the incomplete frame if (expected_next_byte_count > available_next_byte_count) { // did not receive enough bytes to complete the frame incompleteframe.put(buffer.array(), buffer.position(), available_next_byte_count); buffer.position(buffer.position() + available_next_byte_count); return Collections.emptyList(); } incompleteframe.put(buffer.array(), buffer.position(), expected_next_byte_count); buffer.position(buffer.position() + expected_next_byte_count); cur = translateSingleFrame((ByteBuffer) incompleteframe.duplicate().position(0)); frames.add(cur); incompleteframe = null; } catch (IncompleteException e) { // extending as much as suggested int oldsize = incompleteframe.limit(); ByteBuffer extendedframe = ByteBuffer.allocate(checkAlloc(e.getPreferedSize())); assert (extendedframe.limit() > incompleteframe.limit()); incompleteframe.rewind(); extendedframe.put(incompleteframe); incompleteframe = extendedframe; return translateFrame(buffer); } } while (buffer.hasRemaining()) {// Read as much as possible full frames buffer.mark(); try { cur = translateSingleFrame(buffer); frames.add(cur); } catch (IncompleteException e) { // remember the incomplete data buffer.reset(); int pref = e.getPreferedSize(); incompleteframe = ByteBuffer.allocate(checkAlloc(pref)); incompleteframe.put(buffer); break; } } return frames; } public Framedata translateSingleFrame(ByteBuffer buffer) throws IncompleteException, InvalidDataException { int maxpacketsize = buffer.remaining(); int realpacketsize = 2; if (maxpacketsize < realpacketsize) throw new IncompleteException(realpacketsize); byte b1 = buffer.get( ); boolean FIN = b1 >> 8 != 0; byte rsv = (byte) ((b1 & ~(byte) 128) >> 4); if (rsv != 0) throw new InvalidFrameException("bad rsv " + rsv); byte b2 = buffer.get( ); boolean MASK = (b2 & -128) != 0; int payloadlength = (byte) (b2 & ~(byte) 128); Opcode optcode = toOpcode((byte) (b1 & 15)); if (!FIN) { if (optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING) { throw new InvalidFrameException("control frames may no be fragmented"); } } if (!(payloadlength >= 0 && payloadlength <= 125)) { if (optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING) { throw new InvalidFrameException("more than 125 octets"); } if (payloadlength == 126) { realpacketsize += 2; // additional length bytes if (maxpacketsize < realpacketsize) throw new IncompleteException(realpacketsize); byte[] sizebytes = new byte[3]; sizebytes[1] = buffer.get( /*1 + 1*/); sizebytes[2] = buffer.get( /*1 + 2*/); payloadlength = new BigInteger(sizebytes).intValue(); } else { realpacketsize += 8; // additional length bytes if (maxpacketsize < realpacketsize) throw new IncompleteException(realpacketsize); byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { bytes[i] = buffer.get( /*1 + i*/); } long length = new BigInteger(bytes).longValue(); if (length > Integer.MAX_VALUE) { throw new LimitExedeedException("Payloadsize is to big..."); } else { payloadlength = (int) length; } } } // int maskskeystart = foff + realpacketsize; realpacketsize += (MASK ? 4 : 0); // int payloadstart = foff + realpacketsize; realpacketsize += payloadlength; if (maxpacketsize < realpacketsize) throw new IncompleteException(realpacketsize); ByteBuffer payload = ByteBuffer.allocate(checkAlloc(payloadlength)); if (MASK) { byte[] maskskey = new byte[4]; buffer.get(maskskey); for (int i = 0; i < payloadlength; i++) { payload.put((byte) (buffer.get( /*payloadstart + i*/) ^ maskskey[i % 4])); } } else { payload.put(buffer.array(), buffer.position(), payload.limit()); buffer.position(buffer.position() + payload.limit()); } FrameBuilder frame; if (optcode == Opcode.CLOSING) { frame = new CloseFrameBuilder(); } else { frame = new FramedataImpl1(); frame.setFin(FIN); frame.setOptcode(optcode); } payload.flip(); frame.setPayload(payload); return frame; } @Override public void reset() { incompleteframe = null; } @Override public Draft copyInstance() { return new Draft_10(); } @Override public CloseHandshakeType getCloseHandshakeType() { return CloseHandshakeType.TWOWAY; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * @since 0.0.21-SNAPSHOT */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } /** * Gets value on passed generic key K of passed {@link Map} as {@link Map} * of generic key values * * @param key * @param from * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } // Sets remote control check Boolean remoteControl = getConfigValue(ConfigKeys.REMOTE_CONTROL.key); if (ObjectUtils.notNull(remoteControl)) { setRemoteControl(remoteControl); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { IOUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USERS_PATH.getValue(); } public static void setAdminUsersPath(String adminUsersPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUsersPath; } public static void setRemoteControl(boolean remoteControl) { ConfigKeys.REMOTE_CONTROL.value = remoteControl; } public static boolean getRemoteControl() { return ConfigKeys.REMOTE_CONTROL.getValue(); } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Path where stored administrative users public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath"; // Netty server / client configuration properties for RPC calls public static final String IP_ADDRESS_KEY = "listeningIp"; public static final String PORT_KEY = "listeningPort"; public static final String BOSS_POOL_KEY = "bossPoolSize"; public static final String WORKER_POOL_KEY = "workerPoolSize"; public static final String CONNECTION_TIMEOUT_KEY = "timeout"; // Properties for data source path and deployment path public static final String DEMPLOYMENT_PATH_KEY = "deploymentPath"; public static final String DATA_SOURCE_PATH_KEY = "dataSourcePath"; // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Default properties public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties"; public static final String IP_ADDRESS_DEF = "0.0.0.0"; public static final String PORT_DEF = "1199"; public static final String BOSS_POOL_DEF = "1"; public static final int WORKER_POOL_DEF = 3; public static final String CONNECTION_TIMEOUT_DEF = "1000"; public static final boolean SERVER_DEF = Boolean.TRUE; public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) private static final String REMOTE_KEY = "remote"; private static final String SERVER_KEY = "server"; private static final String CLIENT_KEY = "client"; public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE))); public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>( Arrays.asList("./ds")); private static final String CONFIG_FILE = "./config/configuration.yaml"; // Configuration keys properties for deployment private static final String DEPLOY_CONFIG_KEY = "deployConfiguration"; private static final String ADMIN_USER_PATH_KEY = "adminPath"; private static final String HOT_DEPLOYMENT_KEY = "hotDeployment"; private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = SERVER_DEF; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(DEPLOY_CONFIG_KEY, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(DEPLOY_CONFIG_KEY, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, PERSISTENCE_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(PERSISTENCE_CONFIG_KEY, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, POOL_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(POOL_CONFIG_KEY, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(POOL_PROPERTIES_KEY); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(POOL_PROVIDER_TYPE_KEY); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(POOL_PROPERTIES_PATH_KEY); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(IP_ADDRESS_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(IP_ADDRESS_KEY, IP_ADDRESS_DEF); } contains = containsConfigKey(PORT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(PORT_KEY, PORT_DEF); } contains = containsConfigKey(BOSS_POOL_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(BOSS_POOL_KEY, BOSS_POOL_DEF); } contains = containsConfigKey(WORKER_POOL_KEY); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF; String workerProperty = String.valueOf(workers); setConfigValue(WORKER_POOL_KEY, workerProperty); } contains = containsConfigKey(CONNECTION_TIMEOUT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(CONNECTION_TIMEOUT_KEY, CONNECTION_TIMEOUT_DEF); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(SERVER_KEY); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(REMOTE_KEY); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ public void configureDeployments() { // Sets administrator user configuration file path ADMIN_USERS_PATH = getConfigValue(ADMIN_USER_PATH_KEY, ADMIN_USERS_PATH_DEF); // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); if (hotDeployment == null) { setConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(WATCH_STATUS_KEY, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = DEPLOYMENT_PATHS_DEF; setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error("Could not open config file", ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error("Could not open config file", ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error("Configuration resource doesn't exist"); } else { loadFromStream(resourceStream); } } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { String errorMessage = "Could not load configuration"; try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(errorMessage, ex); } finally { ObjectUtils.close(propertiesStream); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(CLIENT_KEY, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(CLIENT_KEY, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(DATA_SOURCE_PATH_KEY); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(DATA_SOURCE_PATH_KEY, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(DEMPLOYMENT_PATH_KEY); } public Set<String> getDataSourcePath() { return getConfigValue(DATA_SOURCE_PATH_KEY); } public String[] getLibraryPaths() { return getConfigValue(LIBRARY_PATH_KEY); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(LIBRARY_PATH_KEY, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(HOT_DEPLOYMENT_KEY, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(WATCH_STATUS_KEY, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(WATCH_STATUS_KEY, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(ObjectUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USER_PATH.getValue(); } public static void setAdminUsersPath(String adminUserPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUserPath; } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.utils.ObjectUtils; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable, Serializable { /** * Default serial version UUID just for cloning */ private static final long serialVersionUID = 1L; // cache for all configuration passed programmatically or read from file private final Map<String, String> config = new HashMap<String, String>(); // path where stored adminitrator users public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath"; /** * <a href="netty.io">Netty</a> server / client configuration properties for * RPC calls */ public static final String IP_ADDRESS = "listening_ip"; public static final String PORT = "listening_port"; public static final String BOSS_POOL = "boss_pool_size"; public static final String WORKER_POOL = "worker_pool_size"; public static final String CONNECTION_TIMEOUT = "timeout"; // properties for datasource path and deployment path public static final String DATA_SOURCE_PATH_KEY = "dspath"; private Set<DeploymentDirectory> deploymentPaths; private Set<String> dataSourcePaths; // runtime to get avaliable processors private static final Runtime RUNTIME = Runtime.getRuntime(); /** * Default properties */ public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties"; public static final String IP_ADDRESS_DEF = "0.0.0.0"; public static final String PORT_DEF = "1199"; public static final String BOSS_POOL_DEF = "1"; public static final int WORKER_POOL_DEF = 3; public static final String CONNECTION_TIMEOUT_DEF = "1000"; public static final boolean SERVER_DEF = Boolean.TRUE; public static final String DATA_SOURCE_PATH_DEF = "./ds"; public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE))); public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>( Arrays.asList("./ds")); /** * Properties which version of server is running remote it requires server * client RPC infrastructure or local (embeddable mode) */ private boolean remote; private static boolean server = SERVER_DEF; private boolean client; private static final String CONFIG_FILE = "./config/config.properties"; // String prefixes for jndi names public static final String JPA_NAME = "java:comp/env/"; public static final String EJB_NAME = "ejb:"; public static final int EJB_NAME_LENGTH = 4; // Configuration properties for deployment private boolean scanForEntities; private String annotatedUnitName; private String persXmlPath; private String[] libraryPaths; private boolean persXmlFromJar; private boolean swapDataSource; private boolean scanArchives; private boolean hotDeployment; private boolean watchStatus; // Connection configuration private boolean pooledDataSource; private PoolConfig poolConfig; private static String ADMIN_USERS_PATH; private Map<Object, Object> persistenceProperties; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } public void setDefaults() { boolean contains = config.containsKey(IP_ADDRESS); if (ObjectUtils.notTrue(contains)) { config.put(IP_ADDRESS, IP_ADDRESS_DEF); } contains = config.containsKey(PORT); if (ObjectUtils.notTrue(contains)) { config.put(PORT, PORT_DEF); } contains = config.containsKey(BOSS_POOL); if (ObjectUtils.notTrue(contains)) { config.put(BOSS_POOL, BOSS_POOL_DEF); } contains = config.containsKey(WORKER_POOL); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF; String workerProperty = String.valueOf(workers); config.put(WORKER_POOL, workerProperty); } contains = config.containsKey(CONNECTION_TIMEOUT); if (ObjectUtils.notTrue(contains)) { config.put(CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_DEF); } if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } if (deploymentPaths == null) { deploymentPaths = DEPLOYMENT_PATHS_DEF; } } public void configure() { setDefaults(); } public String getStringValue(String key) { return config.get(key); } public int getIntValue(String key) { return Integer.parseInt(config.get(key)); } public long getLongValue(String key) { return Long.parseLong(config.get(key)); } public boolean getBooleanValue(String key) { return Boolean.parseBoolean(config.get(key)); } public void putValue(String key, String value) { config.put(key, value); } public void loadFromFile() { try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); propertiesStream.close(); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error("Could not open config file", ex); } } /** * Loads configuration form file * * @param configFilename */ public void loadFromFile(String configFilename) { try { FileInputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); propertiesStream.close(); } catch (IOException ex) { LOG.error("Could not open config file", ex); } } public void loadFromResource(String resourceName, ClassLoader loader) { InputStream resourceStream = loader .getResourceAsStream(new StringBuilder("META-INF/").append( resourceName).toString()); if (resourceStream == null) { LOG.error("Configuration resource doesn't exist"); return; } loadFromStream(resourceStream); try { resourceStream.close(); } catch (IOException ex) { LOG.error("Could not load resource", ex); } } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } propertiesStream.close(); } catch (IOException ex) { LOG.error("Could not load configuration", ex); } } public boolean isRemote() { return remote; } public void setRemote(boolean remote) { this.remote = remote; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return client; } public void setClient(boolean client) { this.client = client; } public void addDeploymentPath(String path, boolean scan) { synchronized (Configuration.class) { if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } } public void addDataSourcePath(String path) { synchronized (Configuration.class) { if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); } dataSourcePaths.add(path); } } public Set<DeploymentDirectory> getDeploymentPath() { return deploymentPaths; } public Set<String> getDataSourcePath() { return dataSourcePaths; } public boolean isScanForEntities() { return scanForEntities; } public void setScanForEntities(boolean scanForEntities) { this.scanForEntities = scanForEntities; } public String getAnnotatedUnitName() { return annotatedUnitName; } public void setAnnotatedUnitName(String annotatedUnitName) { this.annotatedUnitName = annotatedUnitName; } public String getPersXmlPath() { return persXmlPath; } public void setPersXmlPath(String persXmlPath) { this.persXmlPath = persXmlPath; } public String[] getLibraryPaths() { return libraryPaths; } public void setLibraryPaths(String[] libraryPaths) { this.libraryPaths = libraryPaths; } public boolean isPersXmlFromJar() { return persXmlFromJar; } public void setPersXmlFromJar(boolean persXmlFromJar) { this.persXmlFromJar = persXmlFromJar; } public boolean isSwapDataSource() { return swapDataSource; } public void setSwapDataSource(boolean swapDataSource) { this.swapDataSource = swapDataSource; } public boolean isScanArchives() { return scanArchives; } public void setScanArchives(boolean scanArchives) { this.scanArchives = scanArchives; } public boolean isHotDeployment() { return hotDeployment; } public void setHotDeployment(boolean hotDeployment) { this.hotDeployment = hotDeployment; } public boolean isWatchStatus() { return watchStatus; } public void setWatchStatus(boolean watchStatus) { this.watchStatus = watchStatus; } public boolean isPooledDataSource() { return pooledDataSource; } public void setPooledDataSource(boolean pooledDataSource) { this.pooledDataSource = pooledDataSource; } public PoolConfig getPoolConfig() { return poolConfig; } public void setPoolConfig(PoolConfig poolConfig) { this.poolConfig = poolConfig; } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public Map<Object, Object> getPersistenceProperties() { return persistenceProperties; } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { this.persistenceProperties = persistenceProperties; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
import java.lang.reflect.*; import java.io.*; import java.net.*; import java.util.*; import DNS.*; import DNS.utils.*; public class jnamed { Cache cache; Hashtable znames; Hashtable TSIGs; public jnamed(String conffile) throws IOException { FileInputStream fs; try { fs = new FileInputStream(conffile); } catch (Exception e) { System.out.println("Cannot open " + conffile); return; } cache = null; znames = new Hashtable(); TSIGs = new Hashtable(); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); String line = null; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); if (!st.hasMoreTokens()) continue; String keyword = st.nextToken(); if (!st.hasMoreTokens()) { System.out.println("Invalid line: " + line); continue; } if (keyword.equals("primary")) addZone(st.nextToken()); else if (keyword.equals("cache")) cache = new Cache(st.nextToken()); else if (keyword.equals("key")) addTSIG(st.nextToken(), st.nextToken()); } if (cache == null) { System.out.println("no cache specified"); System.exit(-1); } addUDP((short)12345); addTCP((short)12345); }; public void addZone(String zonefile) throws IOException { Zone newzone = new Zone(zonefile, cache); znames.put(newzone.getOrigin(), newzone); /*System.out.println("Adding zone named <" + newzone.getOrigin() + ">");*/ }; public void addTSIG(String name, String key) { TSIGs.put(new Name(name), base64.fromString(key)); } public Zone findBestZone(Name name) { Zone foundzone = null; Name tname = name; do { /*System.out.println("Looking for zone named <" + tname + ">");*/ foundzone = (Zone) znames.get(tname); if (foundzone != null) return foundzone; tname = new Name(tname, 1); } while (!tname.equals(Name.root)); return null; } public RRset findExactMatch(Name name, short type, short dclass) { Zone zone = findBestZone(name); if (zone != null) return zone.findRecords(name, type); else return cache.findRecords(name, type); } void addRRset(Message response, RRset rrset) { Enumeration e = rrset.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); response.addRecord(Section.ANSWER, r); } } void addAuthority(Message response, Name name, Zone zone) { if (response.getHeader().getCount(Section.ANSWER) > 0 || zone == null) { RRset nsRecords = findExactMatch(name, Type.NS, DClass.IN); if (nsRecords == null) { if (zone != null) nsRecords = zone.getNS(); else nsRecords = cache.findRecords(Name.root, Type.NS); } Enumeration e = nsRecords.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (response.findRecord(Section.ANSWER, r) == false) response.addRecord(Section.AUTHORITY, r); } } else { SOARecord soa = (SOARecord) zone.getSOA(); response.addRecord(Section.AUTHORITY, soa); } } private void addGlue(Message response, Name name) { RRset a = findExactMatch(name, Type.A, DClass.IN); Enumeration e = a.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (response.findRecord(r) == false) response.addRecord(Section.ADDITIONAL, r); } } private void addAdditional2(Message response, int section) { Enumeration e = response.getSection(section); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); try { Method m = r.getClass().getMethod("getTarget", null); Name glueName = (Name) m.invoke(r, null); addGlue(response, glueName); } catch (Exception ex) { } } } void addAdditional(Message response) { addAdditional2(response, Section.ANSWER); addAdditional2(response, Section.AUTHORITY); } /* FIX ME */ TSIG findTSIG(Name name) { byte [] key = (byte []) TSIGs.get(name); if (key != null) return new TSIG(name.toString(), key); else return null; } Message generateReply(Message query, byte [] in, int maxLength) { Enumeration qds = query.getSection(Section.QUESTION); Record queryRecord = (Record) qds.nextElement(); TSIGRecord queryTSIG = query.getTSIG(); TSIG tsig = null; if (queryTSIG != null) { tsig = findTSIG(queryTSIG.getName()); if (!tsig.verify(query, in, null)) return formerrMessage(in); } Message response = new Message(); response.getHeader().setID(query.getHeader().getID()); response.getHeader().setFlag(Flags.AA); response.getHeader().setFlag(Flags.QR); response.addRecord(Section.QUESTION, queryRecord); Name name = queryRecord.getName(); short type = queryRecord.getType(); Zone zone = findBestZone(name); /*System.out.println("Looking up name <" + name + "> in [" + zone.getOrigin() + "]");*/ Hashtable nameRecords = (Hashtable) zone.findName(name); if (nameRecords == null) { response.getHeader().setRcode(Rcode.NXDOMAIN); } else { if (type == Type.ANY) { Enumeration e = nameRecords.elements(); while (e.hasMoreElements()) { RRset rrset = (RRset) e.nextElement(); addRRset(response, rrset); } } else { Short Type = new Short(type); RRset rrset = (RRset) nameRecords.get(Type); if (rrset != null) addRRset(response, rrset); } } addAuthority(response, name, zone); addAdditional(response); if (queryTSIG != null) { try { if (tsig != null) tsig.apply(response, queryTSIG); } catch (IOException e) { } } try { byte [] out = response.toWire(); if (out.length > maxLength) { truncate(response, out.length, maxLength); if (tsig != null) tsig.apply(response, queryTSIG); } } catch (IOException e) { } return response; } public int truncateSection(Message in, int maxLength, int length, int section) { int removed = 0; Record [] records = in.getSectionArray(section); for (int i = records.length - 1; i >= 0; i Record r = records[i]; removed += r.getWireLength(); length -= r.getWireLength(); in.removeRecord(section, r); if (length > maxLength) continue; else { for (int j = i - 1; j >= 0; j Record r2 = records[j]; if (!r.getName().equals(r2.getName()) || r.getType() != r2.getType() || r.getDClass() != r2.getDClass()) break; removed += r2.getWireLength(); length -= r2.getWireLength(); in.removeRecord(section, r2); } return removed; } } return removed; } public void truncate(Message in, int length, int maxLength) { TSIGRecord tsig = in.getTSIG(); if (tsig != null) maxLength -= tsig.getWireLength(); length -= truncateSection(in, maxLength, length, Section.ADDITIONAL); if (length < maxLength) return; in.getHeader().setFlag(Flags.TC); if (tsig != null) { in.removeAllRecords(Section.ANSWER); in.removeAllRecords(Section.AUTHORITY); return; } length -= truncateSection(in, maxLength, length, Section.AUTHORITY); if (length < maxLength) return; length -= truncateSection(in, maxLength, length, Section.ANSWER); } public Message formerrMessage(byte [] in) { Header header; try { header = new Header(new DataByteInputStream(in)); for (int i = 0; i < 4; i++) header.setCount(i, 0); } catch (IOException e) { header = new Header(0); } Message response = new Message(); header.setRcode(Rcode.FORMERR); response.setHeader(header); return response; } public void serveTCP(short port) { try { ServerSocket sock = new ServerSocket(port); while (true) { Socket s = sock.accept(); int inLength; DataInputStream dataIn; DataOutputStream dataOut; byte [] in; try { InputStream is = s.getInputStream(); dataIn = new DataInputStream(is); inLength = dataIn.readUnsignedShort(); in = new byte[inLength]; dataIn.readFully(in); } catch (InterruptedIOException e) { s.close(); continue; } Message query, response; try { query = new Message(in); response = generateReply(query, in, 65535); } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dataOut = new DataOutputStream(s.getOutputStream()); dataOut.writeShort(out.length); dataOut.write(out); s.close(); } } catch (IOException e) { System.out.println("serveTCP: " + e); } } public void serveUDP(short port) { try { DatagramSocket sock = new DatagramSocket(port); while (true) { short udpLength = 512; DatagramPacket dp = new DatagramPacket(new byte[512], 512); try { sock.receive(dp); } catch (InterruptedIOException e) { continue; } byte [] in = new byte[dp.getLength()]; System.arraycopy(dp.getData(), 0, in, 0, in.length); Message query, response; try { query = new Message(in); OPTRecord opt = query.getOPT(); if (opt != null) udpLength = opt.getPayloadSize(); response = generateReply(query, in, udpLength); } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dp = new DatagramPacket(out, out.length, dp.getAddress(), dp.getPort()); sock.send(dp); } } catch (IOException e) { System.out.println("serveUDP: " + e); } } public void addTCP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveTCP(port);}}); t.start(); } public void addUDP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveUDP(port);}}); t.start(); } public static void main(String [] args) { if (args.length != 1) { System.out.println("usage: server conf"); System.exit(0); } jnamed s; try { s = new jnamed(args[0]); } catch (IOException e) { System.out.println(e); } } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USER_PATH.getValue(); } public static void setAdminUsersPath(String adminUserPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUserPath; } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
import java.lang.reflect.*; import java.io.*; import java.net.*; import java.util.*; import org.xbill.DNS.*; import org.xbill.DNS.utils.*; /** @author Brian Wellington &lt;bwelling@xbill.org&gt; */ public class jnamed { Hashtable caches; Hashtable znames; Hashtable TSIGs; public jnamed(String conffile) throws IOException { FileInputStream fs; boolean started = false; try { fs = new FileInputStream(conffile); } catch (Exception e) { System.out.println("Cannot open " + conffile); return; } caches = new Hashtable(); znames = new Hashtable(); TSIGs = new Hashtable(); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); String line = null; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); if (!st.hasMoreTokens()) continue; String keyword = st.nextToken(); if (!st.hasMoreTokens()) { System.out.println("Invalid line: " + line); continue; } if (keyword.charAt(0) == ' continue; if (keyword.equals("primary")) addPrimaryZone(st.nextToken()); if (keyword.equals("secondary")) addSecondaryZone(st.nextToken(), st.nextToken()); else if (keyword.equals("cache")) { Cache cache = new Cache(st.nextToken()); caches.put(new Short(DClass.IN), cache); } else if (keyword.equals("key")) addTSIG(st.nextToken(), st.nextToken()); else if (keyword.equals("port")) { short port = Short.parseShort(st.nextToken()); addUDP(port); addTCP(port); started = true; } } if (!started) { addUDP((short) 53); addTCP((short) 53); } System.out.println("running"); } public void addPrimaryZone(String zonefile) throws IOException { Cache cache = getCache(DClass.IN); Zone newzone = new Zone(zonefile, cache); znames.put(newzone.getOrigin(), newzone); /*System.out.println("Adding zone named <" + newzone.getOrigin() + ">");*/ } public void addSecondaryZone(String zone, String remote) throws IOException { Cache cache = getCache(DClass.IN); Name zname = new Name(zone); Zone newzone = new Zone(zname, DClass.IN, remote, cache); znames.put(zname, newzone); /*System.out.println("Adding zone named <" + zname + ">");*/ } public void addTSIG(String name, String key) { TSIGs.put(new Name(name), base64.fromString(key)); } public Cache getCache(short dclass) { Cache c = (Cache) caches.get(new Short(dclass)); if (c == null) { c = new Cache(dclass); caches.put(new Short(dclass), c); } return c; } public Zone findBestZone(Name name) { Zone foundzone = null; foundzone = (Zone) znames.get(name); if (foundzone != null) return foundzone; Name tname = name; while (!tname.equals(Name.root)) { tname = new Name(tname, 1); foundzone = (Zone) znames.get(tname); if (foundzone != null) return foundzone; } return null; } public RRset findExactMatch(Name name, short type, short dclass, boolean glue) { Zone zone = findBestZone(name); if (zone != null) return zone.findExactMatch(name, type); else { RRset [] rrsets; Cache cache = getCache(dclass); if (glue) rrsets = cache.findAnyRecords(name, type); else rrsets = cache.findRecords(name, type); if (rrsets == null) return null; else return rrsets[0]; /* not quite right */ } } void addRRset(Name name, Message response, RRset rrset, byte section, boolean sigonly) { Enumeration e; if (!sigonly) { e = rrset.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (!name.isWild() && r.getName().isWild()) r = r.withName(name); for (byte s = 1; s < section; s++) if (response.findRecord(r, s)) continue; response.addRecord(r, section); } } e = rrset.sigs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (!name.isWild() && r.getName().isWild()) r = r.withName(name); for (byte s = 1; s < section; s++) if (response.findRecord(r, s)) continue; response.addRecord(r, section); } } private void addSOA(Message response, Zone zone) { response.addRecord(zone.getSOA(), Section.AUTHORITY); } private void addNS(Message response, Zone zone) { RRset nsRecords = zone.getNS(); Enumeration e = nsRecords.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); response.addRecord(r, Section.AUTHORITY); } } private void addGlue(Message response, Name name) { RRset a = findExactMatch(name, Type.A, DClass.IN, true); if (a == null) return; Enumeration e = a.rrs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (response.findRecord(r) == false) response.addRecord(r, Section.ADDITIONAL); } e = a.sigs(); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); if (response.findRecord(r) == false) response.addRecord(r, Section.ADDITIONAL); } } private void addAdditional2(Message response, int section) { Enumeration e = response.getSection(section); while (e.hasMoreElements()) { Record r = (Record) e.nextElement(); Name glueName = null; switch (r.getType()) { case Type.MX: glueName = ((MXRecord)r).getTarget(); break; case Type.NS: glueName = ((NSRecord)r).getTarget(); break; case Type.KX: glueName = ((KXRecord)r).getTarget(); break; case Type.NAPTR: glueName = ((NAPTRRecord)r).getReplacement(); break; case Type.SRV: glueName = ((SRVRecord)r).getTarget(); break; default: break; } if (glueName != null) addGlue(response, glueName); } } void addAdditional(Message response) { addAdditional2(response, Section.ANSWER); addAdditional2(response, Section.AUTHORITY); } byte addAnswer(Message response, Name name, short type, short dclass, int iterations) { SetResponse sr; boolean sigonly; byte rcode = Rcode.NOERROR; if (iterations > 6) return Rcode.SERVFAIL; if (type == Type.SIG) { type = Type.ANY; sigonly = true; } else sigonly = false; Zone zone = findBestZone(name); if (zone != null) { if (iterations == 0) response.getHeader().setFlag(Flags.AA); sr = zone.findRecords(name, type); } else { Cache cache = getCache(dclass); sr = cache.lookupRecords(name, type, Credibility.NONAUTH_ANSWER); } if (sr.isUnknown()) { /* Do nothing, I guess. This should never happen. */ } if (sr.isNXDOMAIN()) { response.getHeader().setRcode(Rcode.NXDOMAIN); if (zone != null && iterations == 0) addSOA(response, zone); } else if (sr.isNXRRSET()) { if (zone != null && iterations == 0) addSOA(response, zone); } else if (sr.isDelegation()) { RRset nsRecords = sr.getNS(); addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, false); } else if (sr.isCNAME()) { RRset rrset = new RRset(); CNAMERecord cname = sr.getCNAME(); rrset.addRR(cname); addRRset(name, response, rrset, Section.ANSWER, false); if (zone != null && iterations == 0) addNS(response, zone); rcode = addAnswer(response, cname.getTarget(), type, dclass, ++iterations); } else if (sr.isDNAME()) { RRset rrset = new RRset(); DNAMERecord dname = sr.getDNAME(); rrset.addRR(dname); addRRset(name, response, rrset, Section.ANSWER, false); Name newname = name.fromDNAME(dname); if (newname == null) return Rcode.SERVFAIL; try { rrset = new RRset(); rrset.addRR(new CNAMERecord(name, dclass, 0, newname)); addRRset(name, response, rrset, Section.ANSWER, false); } catch (IOException e) {} if (zone != null && iterations == 0) addNS(response, zone); rcode = addAnswer(response, newname, type, dclass, ++iterations); } else if (sr.isSuccessful()) { RRset [] rrsets = sr.answers(); for (int i = 0; i < rrsets.length; i++) addRRset(name, response, rrsets[i], Section.ANSWER, sigonly); if (zone != null && iterations == 0) addNS(response, zone); } return rcode; } TSIG findTSIG(Name name) { byte [] key = (byte []) TSIGs.get(name); if (key != null) return new TSIG(name, key); else return null; } Message doAXFR(Name name, Message query, Socket s) { Zone zone = (Zone) znames.get(name); if (zone == null) { /* System.out.println("no zone " + name + " to AXFR");*/ return errorMessage(query, Rcode.REFUSED); } Enumeration e = zone.AXFR(); try { DataOutputStream dataOut; dataOut = new DataOutputStream(s.getOutputStream()); while (e.hasMoreElements()) { RRset rrset = (RRset) e.nextElement(); Message response = new Message(); addRRset(rrset.getName(), response, rrset, Section.ANSWER, false); byte [] out = response.toWire(); dataOut.writeShort(out.length); dataOut.write(out); } } catch (IOException ex) { System.out.println("AXFR failed"); } try { s.close(); } catch (IOException ex) { } return null; } /* * Note: a null return value means that the caller doesn't need to do * anything. Currently this only happens if this is an AXFR request over * TCP. */ Message generateReply(Message query, byte [] in, Socket s) { boolean badversion; int maxLength; boolean sigonly; SetResponse sr; if (query.getHeader().getOpcode() != Opcode.QUERY) return errorMessage(query, Rcode.NOTIMPL); Record queryRecord = query.getQuestion(); TSIGRecord queryTSIG = query.getTSIG(); TSIG tsig = null; if (queryTSIG != null) { tsig = findTSIG(queryTSIG.getName()); if (!tsig.verify(query, in, null)) return formerrMessage(in); } OPTRecord queryOPT = query.getOPT(); if (queryOPT != null && queryOPT.getVersion() > 0) badversion = true; if (s != null) maxLength = 65535; else if (queryOPT != null) maxLength = queryOPT.getPayloadSize(); else maxLength = 512; Message response = new Message(); response.getHeader().setID(query.getHeader().getID()); response.getHeader().setFlag(Flags.QR); response.addRecord(queryRecord, Section.QUESTION); Name name = queryRecord.getName(); short type = queryRecord.getType(); short dclass = queryRecord.getDClass(); if (type == Type.AXFR && s != null) return doAXFR(name, query, s); if (!Type.isRR(type) && type != Type.ANY) return errorMessage(query, Rcode.NOTIMPL); byte rcode = addAnswer(response, name, type, dclass, 0); if (rcode != Rcode.NOERROR) return errorMessage(query, rcode); addAdditional(response); if (queryTSIG != null) { try { if (tsig != null) tsig.apply(response, queryTSIG); } catch (IOException e) { } } try { byte [] out = response.toWire(); if (out.length > maxLength) { truncate(response, out.length, maxLength); if (tsig != null) tsig.apply(response, queryTSIG); } } catch (IOException e) { } return response; } public int truncateSection(Message in, int maxLength, int length, int section) { int removed = 0; Record [] records = in.getSectionArray(section); for (int i = records.length - 1; i >= 0; i Record r = records[i]; removed += r.getWireLength(); length -= r.getWireLength(); in.removeRecord(r, section); if (length > maxLength) continue; else { for (int j = i - 1; j >= 0; j Record r2 = records[j]; if (!r.getName().equals(r2.getName()) || r.getType() != r2.getType() || r.getDClass() != r2.getDClass()) break; removed += r2.getWireLength(); length -= r2.getWireLength(); in.removeRecord(r2, section); } return removed; } } return removed; } public void truncate(Message in, int length, int maxLength) { TSIGRecord tsig = in.getTSIG(); if (tsig != null) maxLength -= tsig.getWireLength(); length -= truncateSection(in, maxLength, length, Section.ADDITIONAL); if (length < maxLength) return; in.getHeader().setFlag(Flags.TC); if (tsig != null) { in.removeAllRecords(Section.ANSWER); in.removeAllRecords(Section.AUTHORITY); return; } length -= truncateSection(in, maxLength, length, Section.AUTHORITY); if (length < maxLength) return; length -= truncateSection(in, maxLength, length, Section.ANSWER); } public Message formerrMessage(byte [] in) { Header header; try { header = new Header(new DataByteInputStream(in)); } catch (IOException e) { header = new Header(0); } Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) response.removeAllRecords(i); header.setRcode(Rcode.FORMERR); return response; } public Message errorMessage(Message query, short rcode) { Header header = query.getHeader(); Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) response.removeAllRecords(i); header.setRcode(rcode); return response; } public void serveTCP(short port) { try { ServerSocket sock = new ServerSocket(port); while (true) { Socket s = sock.accept(); int inLength; DataInputStream dataIn; DataOutputStream dataOut; byte [] in; try { InputStream is = s.getInputStream(); dataIn = new DataInputStream(is); inLength = dataIn.readUnsignedShort(); in = new byte[inLength]; dataIn.readFully(in); } catch (InterruptedIOException e) { s.close(); continue; } Message query, response; try { query = new Message(in); response = generateReply(query, in, s); if (response == null) continue; } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dataOut = new DataOutputStream(s.getOutputStream()); dataOut.writeShort(out.length); dataOut.write(out); s.close(); } } catch (IOException e) { System.out.println("serveTCP: " + e); } } public void serveUDP(short port) { try { DatagramSocket sock = new DatagramSocket(port); while (true) { short udpLength = 512; DatagramPacket dp = new DatagramPacket(new byte[512], 512); try { sock.receive(dp); } catch (InterruptedIOException e) { continue; } byte [] in = new byte[dp.getLength()]; System.arraycopy(dp.getData(), 0, in, 0, in.length); Message query, response; try { query = new Message(in); response = generateReply(query, in, null); if (response == null) continue; } catch (IOException e) { response = formerrMessage(in); } byte [] out = response.toWire(); dp = new DatagramPacket(out, out.length, dp.getAddress(), dp.getPort()); sock.send(dp); } } catch (IOException e) { System.out.println("serveUDP: " + e); } } public void addTCP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveTCP(port);}}); t.start(); } public void addUDP(final short port) { Thread t; t = new Thread(new Runnable() {public void run() {serveUDP(port);}}); t.start(); } public static void main(String [] args) { if (args.length > 1) { System.out.println("usage: jnamed [conf]"); System.exit(0); } jnamed s; try { String conf; if (args.length == 1) conf = args[0]; else conf = "jnamed.conf"; s = new jnamed(conf); } catch (IOException e) { System.out.println(e); } } }