answer
stringlengths
17
10.2M
package org.lp20.aikuma.storage; import java.util.List; import java.util.Map; public interface Index { /** * Downloads metadata for the item. * * @param identifier * @return The metadata for the item as a key-value pairs. Null if item is * not found in the index. */ public abstract Map<String, String> get_item_metadata(String identifier); /** * Search the index according to the specified constraints. * TODO: Specify the structure of the constraints param. * @param constraints * @return A list of item ids. */ public abstract List<String> search(Map<String,String> constraints); /** * Index an item. If item already exists, it gets updated. * For metadata, the following keys are required: * * - data_store_uri - the Google Drive URI * - item_id - A way of grouping multiple items under a single identifier * - file_type - Mime type * - language - language * - speakers (comma-separated list) - speakers * * @param identifier * @param metadata */ public abstract void index(String identifier, Map<String,String> metadata); }
package edu.umd.cs.findbugs; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantFloat; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.ClassMember; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.LVTHelper; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * tracks the types and numbers of objects that are currently on the operand stack * throughout the execution of method. To use, a detector should instantiate one for * each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method. * at any point you can then inspect the stack and see what the types of objects are on * the stack, including constant values if they were pushed. The types described are of * course, only the static types. * There are some outstanding opcodes that have yet to be implemented, I couldn't * find any code that actually generated these, so i didn't put them in because * I couldn't test them: * <ul> * <li>dup2_x2</li> * <li>jsr_w</li> * <li>wide</li> * </ul> */ public class OpcodeStack implements Constants2 { private static final boolean DEBUG = SystemProperties.getBoolean("ocstack.debug"); private static final boolean DEBUG2 = DEBUG; private List<Item> stack; private List<Item> lvValues; private List<Integer> lastUpdate; private boolean top; private boolean seenTransferOfControl = false; private boolean useIterativeAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS); public static class Item { public static final int SIGNED_BYTE = 1; public static final int RANDOM_INT = 2; public static final int LOW_8_BITS_CLEAR = 3; public static final int HASHCODE_INT = 4; public static final int INTEGER_SUM = 5; public static final int AVERAGE_COMPUTED_USING_DIVISION = 6; public static final int FLOAT_MATH = 7; public static final int RANDOM_INT_REMAINDER = 8; public static final int HASHCODE_INT_REMAINDER = 9; public static final int FILE_SEPARATOR_STRING = 10; public static final int MATH_ABS = 11; public static final int NON_NEGATIVE = 12; public static final int NASTY_FLOAT_MATH = 13; public static final int FILE_OPENED_IN_APPEND_MODE = 14; public static final int SERVLET_REQUEST_TAINTED = 15; private static final int IS_INITIAL_PARAMETER_FLAG=1; private static final int COULD_BE_ZERO_FLAG = 2; private static final int IS_NULL_FLAG = 4; public static final Object UNKNOWN = null; private int specialKind; private String signature; private Object constValue = UNKNOWN; private @CheckForNull ClassMember source; private int flags; // private boolean isNull = false; private int registerNumber = -1; // private boolean isInitialParameter = false; // private boolean couldBeZero = false; private Object userValue = null; private int fieldLoadedFromRegister = -1; public int getSize() { if (signature.equals("J") || signature.equals("D")) return 2; return 1; } public boolean isWide() { return getSize() == 2; } private static boolean equals(Object o1, Object o2) { if (o1 == o2) return true; if (o1 == null || o2 == null) return false; return o1.equals(o2); } @Override public int hashCode() { int r = 42 + specialKind; if (signature != null) r+= signature.hashCode(); r *= 31; if (constValue != null) r+= constValue.hashCode(); r *= 31; if (source != null) r+= source.hashCode(); r *= 31; r += flags; r *= 31; r += registerNumber; return r; } @Override public boolean equals(Object o) { if (!(o instanceof Item)) return false; Item that = (Item) o; return equals(this.signature, that.signature) && equals(this.constValue, that.constValue) && equals(this.source, that.source) && this.specialKind == that.specialKind && this.registerNumber == that.registerNumber && this.flags == that.flags && this.userValue == that.userValue && this.fieldLoadedFromRegister == that.fieldLoadedFromRegister; } @Override public String toString() { StringBuffer buf = new StringBuffer("< "); buf.append(signature); switch(specialKind) { case SIGNED_BYTE: buf.append(", byte_array_load"); break; case RANDOM_INT: buf.append(", random_int"); break; case LOW_8_BITS_CLEAR: buf.append(", low8clear"); break; case HASHCODE_INT: buf.append(", hashcode_int"); break; case INTEGER_SUM: buf.append(", int_sum"); break; case AVERAGE_COMPUTED_USING_DIVISION: buf.append(", averageComputingUsingDivision"); break; case FLOAT_MATH: buf.append(", floatMath"); break; case NASTY_FLOAT_MATH: buf.append(", nastyFloatMath"); break; case HASHCODE_INT_REMAINDER: buf.append(", hashcode_int_rem"); break; case RANDOM_INT_REMAINDER: buf.append(", random_int_rem"); break; case FILE_SEPARATOR_STRING: buf.append(", file_separator_string"); break; case MATH_ABS: buf.append(", Math.abs"); break; case NON_NEGATIVE: buf.append(", non_negative"); break; case FILE_OPENED_IN_APPEND_MODE: buf.append(", file opened in append mode"); break; case SERVLET_REQUEST_TAINTED: buf.append(", servlet request tainted"); break; case 0 : break; default: buf.append(", #" + specialKind); break; } if (constValue != UNKNOWN) { if (constValue instanceof String) { buf.append(", \""); buf.append(constValue); buf.append("\""); } else { buf.append(", "); buf.append(constValue); } } if (source instanceof XField) { buf.append(", "); if (fieldLoadedFromRegister != -1) buf.append(fieldLoadedFromRegister).append(':'); buf.append(source); } if (source instanceof XMethod) { buf.append(", return value from "); buf.append(source); } if (isInitialParameter()) { buf.append(", IP"); } if (isNull()) { buf.append(", isNull"); } if (registerNumber != -1) { buf.append(", r"); buf.append(registerNumber); } if (isCouldBeZero()) buf.append(", cbz"); buf.append(" >"); return buf.toString(); } public static Item merge(Item i1, Item i2) { if (i1 == null) return i2; if (i2 == null) return i1; if (i1.equals(i2)) return i1; Item m = new Item(); m.flags = i1.flags & i2.flags; m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero()); if (equals(i1.signature,i2.signature)) m.signature = i1.signature; if (equals(i1.constValue,i2.constValue)) m.constValue = i1.constValue; if (equals(i1.source,i2.source)) { m.source = i1.source; } if (i1.registerNumber == i2.registerNumber) m.registerNumber = i1.registerNumber; if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister) m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister; if (i1.specialKind == i2.specialKind) m.specialKind = i1.specialKind; else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH) m.specialKind = NASTY_FLOAT_MATH; else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH) m.specialKind = FLOAT_MATH; else if (i1.specialKind == SERVLET_REQUEST_TAINTED || i2.specialKind == SERVLET_REQUEST_TAINTED) m.specialKind = SERVLET_REQUEST_TAINTED; if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m); return m; } public Item(String signature, int constValue) { this(signature, (Object)(Integer)constValue); } public Item(String signature) { this(signature, UNKNOWN); } public Item(Item it) { this.signature = it.signature; this.constValue = it.constValue; this.source = it.source; this.registerNumber = it.registerNumber; this.userValue = it.userValue; this.flags = it.flags; this.specialKind = it.specialKind; } public Item(Item it, int reg) { this(it); this.registerNumber = reg; } public Item(String signature, FieldAnnotation f) { this.signature = signature; if (f != null) source = XFactory.createXField(f); fieldLoadedFromRegister = -1; } public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) { this.signature = signature; if (f != null) source = XFactory.createXField(f); this.fieldLoadedFromRegister = fieldLoadedFromRegister; } public int getFieldLoadedFromRegister() { return fieldLoadedFromRegister; } public Item(String signature, Object constantValue) { this.signature = signature; constValue = constantValue; if (constantValue instanceof Integer) { int value = (Integer) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } else if (constantValue instanceof Long) { long value = (Long) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } } public Item() { signature = "Ljava/lang/Object;"; constValue = null; setNull(true); } /** Returns null for primitive and arrays */ public @CheckForNull JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; try { if (isPrimitive() || isArray()) return null; baseSig = signature; if (baseSig.length() == 0) return null; baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); } catch (RuntimeException e) { e.printStackTrace(); throw e; } } public boolean isArray() { return signature.startsWith("["); } public String getElementSignature() { if (!isArray()) return signature; else { int pos = 0; int len = signature.length(); while (pos < len) { if (signature.charAt(pos) != '[') break; pos++; } return signature.substring(pos); } } public boolean isNonNegative() { if (specialKind == NON_NEGATIVE) return true; if (constValue instanceof Number) { double value = ((Number) constValue).doubleValue(); return value >= 0; } return false; } public boolean isPrimitive() { return !signature.startsWith("L") && !signature.startsWith("["); } public int getRegisterNumber() { return registerNumber; } public String getSignature() { return signature; } /** * Returns a constant value for this Item, if known. * NOTE: if the value is a constant Class object, the constant value returned is the name of the class. */ public Object getConstant() { return constValue; } /** Use getXField instead */ @Deprecated public FieldAnnotation getFieldAnnotation() { return FieldAnnotation.fromXField(getXField()); } public XField getXField() { if (source instanceof XField) return (XField) source; return null; } /** * @param specialKind The specialKind to set. */ public void setSpecialKind(int specialKind) { this.specialKind = specialKind; } /** * @return Returns the specialKind. */ public int getSpecialKind() { return specialKind; } /** * attaches a detector specified value to this item * * @param value the custom value to set */ public void setUserValue(Object value) { userValue = value; } /** * * @return if this value is the return value of a method, give the method * invoked */ public @CheckForNull XMethod getReturnValueOf() { if (source instanceof XMethod) return (XMethod) source; return null; } public boolean couldBeZero() { return isCouldBeZero(); } public boolean mustBeZero() { Object value = getConstant(); return value instanceof Number && ((Number)value).intValue() == 0; } /** * gets the detector specified value for this item * * @return the custom value */ public Object getUserValue() { return userValue; } public boolean isServletParameterTainted() { return getSpecialKind() == Item.SERVLET_REQUEST_TAINTED; } public void setServletParameterTainted() { setSpecialKind(Item.SERVLET_REQUEST_TAINTED); } public boolean valueCouldBeNegative() { return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.SIGNED_BYTE || getSpecialKind() == Item.HASHCODE_INT || getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER); } /** * @param isInitialParameter The isInitialParameter to set. */ private void setInitialParameter(boolean isInitialParameter) { setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG); } /** * @return Returns the isInitialParameter. */ public boolean isInitialParameter() { return (flags & IS_INITIAL_PARAMETER_FLAG) != 0; } /** * @param couldBeZero The couldBeZero to set. */ private void setCouldBeZero(boolean couldBeZero) { setFlag(couldBeZero, COULD_BE_ZERO_FLAG); } /** * @return Returns the couldBeZero. */ private boolean isCouldBeZero() { return (flags & COULD_BE_ZERO_FLAG) != 0; } /** * @param isNull The isNull to set. */ private void setNull(boolean isNull) { setFlag(isNull, IS_NULL_FLAG); } private void setFlag(boolean value, int flagBit) { if (value) flags |= flagBit; else flags &= ~flagBit; } /** * @return Returns the isNull. */ public boolean isNull() { return (flags & IS_NULL_FLAG) != 0; } } @Override public String toString() { if (isTop()) return "TOP"; return stack.toString() + "::" + lvValues.toString(); } public OpcodeStack() { stack = new ArrayList<Item>(); lvValues = new ArrayList<Item>(); lastUpdate = new ArrayList<Integer>(); } boolean needToMerge = true; private boolean reachOnlyByBranch = false; public static String getExceptionSig(DismantleBytecode dbc, CodeException e) { if (e.getCatchType() == 0) return "Ljava/lang/Throwable;"; Constant c = dbc.getConstantPool().getConstant(e.getCatchType()); if (c instanceof ConstantClass) return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";"; return "Ljava/lang/Throwable;"; } public void mergeJumps(DismantleBytecode dbc) { if (!needToMerge) return; needToMerge = false; boolean stackUpdated = false; if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) { pop(); Item top = new Item("I"); top.setCouldBeZero(true); push(top); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; stackUpdated = true; } List<Item> jumpEntry = null; if (jumpEntryLocations.get(dbc.getPC())) jumpEntry = jumpEntries.get(dbc.getPC()); if (jumpEntry != null) { setReachOnlyByBranch(false); List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC()); if (DEBUG2) { System.out.println("XXXXXXX " + isReachOnlyByBranch()); System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry); System.out.println(" current lvValues " + lvValues); System.out.println(" merging stack entry " + jumpStackEntry); System.out.println(" current stack values " + stack); } if (isTop()) { lvValues = new ArrayList<Item>(jumpEntry); if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); setTop(false); return; } if (isReachOnlyByBranch()) { setTop(false); lvValues = new ArrayList<Item>(jumpEntry); if (!stackUpdated) { if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); } } else { setTop(false); mergeLists(lvValues, jumpEntry, false); if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false); } if (DEBUG) System.out.println(" merged lvValues " + lvValues); } else if (isReachOnlyByBranch() && !stackUpdated) { stack.clear(); for(CodeException e : dbc.getCode().getExceptionTable()) { if (e.getHandlerPC() == dbc.getPC()) { push(new Item(getExceptionSig(dbc, e))); setReachOnlyByBranch(false); setTop(false); return; } } setTop(true); } } int convertJumpToOneZeroState = 0; int convertJumpToZeroOneState = 0; private void setLastUpdate(int reg, int pc) { while (lastUpdate.size() <= reg) lastUpdate.add(0); lastUpdate.set(reg, pc); } public int getLastUpdate(int reg) { if (lastUpdate.size() <= reg) return 0; return lastUpdate.get(reg); } public int getNumLastUpdates() { return lastUpdate.size(); } public void sawOpcode(DismantleBytecode dbc, int seen) { int register; String signature; Item it, it2, it3; Constant cons; if (dbc.isRegisterStore()) setLastUpdate(dbc.getRegisterOperand(), dbc.getPC()); mergeJumps(dbc); needToMerge = true; try { if (isTop()) { encountedTop = true; return; } switch (seen) { case ICONST_1: convertJumpToOneZeroState = 1; break; case GOTO: if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4) convertJumpToOneZeroState = 2; else convertJumpToOneZeroState = 0; break; case ICONST_0: if (convertJumpToOneZeroState == 2) convertJumpToOneZeroState = 3; else convertJumpToOneZeroState = 0; break; default:convertJumpToOneZeroState = 0; } switch (seen) { case ICONST_0: convertJumpToZeroOneState = 1; break; case GOTO: if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4) convertJumpToZeroOneState = 2; else convertJumpToZeroOneState = 0; break; case ICONST_1: if (convertJumpToZeroOneState == 2) convertJumpToZeroOneState = 3; else convertJumpToZeroOneState = 0; break; default:convertJumpToZeroOneState = 0; } switch (seen) { case ALOAD: pushByLocalObjectLoad(dbc, dbc.getRegisterOperand()); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: pushByLocalObjectLoad(dbc, seen - ALOAD_0); break; case DLOAD: pushByLocalLoad("D", dbc.getRegisterOperand()); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: pushByLocalLoad("D", seen - DLOAD_0); break; case FLOAD: pushByLocalLoad("F", dbc.getRegisterOperand()); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: pushByLocalLoad("F", seen - FLOAD_0); break; case ILOAD: pushByLocalLoad("I", dbc.getRegisterOperand()); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: pushByLocalLoad("I", seen - ILOAD_0); break; case LLOAD: pushByLocalLoad("J", dbc.getRegisterOperand()); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: pushByLocalLoad("J", seen - LLOAD_0); break; case GETSTATIC: { FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc); Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE); if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) { i.setSpecialKind(Item.FILE_SEPARATOR_STRING); } push(i); break; } case LDC: case LDC_W: case LDC2_W: cons = dbc.getConstantRefOperand(); pushByConstant(dbc, cons); break; case INSTANCEOF: pop(); push(new Item("I")); break; case IFEQ: case IFNE: case IFLT: case IFLE: case IFGT: case IFGE: case IFNONNULL: case IFNULL: seenTransferOfControl = true; { Item top = pop(); // if we see a test comparing a special negative value with 0, // reset all other such values on the opcode stack if (top.valueCouldBeNegative() && (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) { int specialKind = top.getSpecialKind(); for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); } } addJumpValue(dbc.getPC(), dbc.getBranchTarget()); break; case LOOKUPSWITCH: case TABLESWITCH: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); int pc = dbc.getBranchTarget() - dbc.getBranchOffset(); for(int offset : dbc.getSwitchOffsets()) addJumpValue(dbc.getPC(), offset+pc); break; case ARETURN: case DRETURN: case FRETURN: case IRETURN: case LRETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); break; case MONITORENTER: case MONITOREXIT: case POP: case PUTSTATIC: pop(); break; case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGT: case IF_ICMPGE: { seenTransferOfControl = true; pop(2); int branchTarget = dbc.getBranchTarget(); addJumpValue(dbc.getPC(), branchTarget); break; } case POP2: it = pop(); if (it.getSize() == 1) pop(); break; case PUTFIELD: pop(2); break; case IALOAD: case SALOAD: pop(2); push(new Item("I")); break; case DUP: handleDup(); break; case DUP2: handleDup2(); break; case DUP_X1: handleDupX1(); break; case DUP_X2: handleDupX2(); break; case DUP2_X1: handleDup2X1(); break; case DUP2_X2: handleDup2X2(); break; case IINC: register = dbc.getRegisterOperand(); it = getLVValue( register ); it2 = new Item("I", dbc.getIntConstant()); pushByIntMath(dbc, IADD, it2, it); pushByLocalStore(register); break; case ATHROW: pop(); seenTransferOfControl = true; setReachOnlyByBranch(true); setTop(true); break; case CHECKCAST: { String castTo = dbc.getClassConstantOperand(); if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";"; it = new Item(pop()); it.signature = castTo; push(it); break; } case NOP: break; case RET: case RETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); break; case GOTO: case GOTO_W: seenTransferOfControl = true; setReachOnlyByBranch(true); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); stack.clear(); setTop(true); break; case SWAP: handleSwap(); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: push(new Item("I", (seen-ICONST_0))); break; case LCONST_0: case LCONST_1: push(new Item("J", (long)(seen-LCONST_0))); break; case DCONST_0: case DCONST_1: push(new Item("D", (double)(seen-DCONST_0))); break; case FCONST_0: case FCONST_1: case FCONST_2: push(new Item("F", (float)(seen-FCONST_0))); break; case ACONST_NULL: push(new Item()); break; case ASTORE: case DSTORE: case FSTORE: case ISTORE: case LSTORE: pushByLocalStore(dbc.getRegisterOperand()); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: pushByLocalStore(seen - ASTORE_0); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: pushByLocalStore(seen - DSTORE_0); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: pushByLocalStore(seen - FSTORE_0); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: pushByLocalStore(seen - ISTORE_0); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: pushByLocalStore(seen - LSTORE_0); break; case GETFIELD: { Item item = pop(); int reg = item.getRegisterNumber(); push(new Item(dbc.getSigConstantOperand(), FieldAnnotation.fromReferencedField(dbc), reg)); } break; case ARRAYLENGTH: { pop(); Item v = new Item("I"); v.setSpecialKind(Item.NON_NEGATIVE); push(v); } break; case BALOAD: { pop(2); Item v = new Item("I"); v.setSpecialKind(Item.SIGNED_BYTE); push(v); break; } case CALOAD: pop(2); push(new Item("I")); break; case DALOAD: pop(2); push(new Item("D")); break; case FALOAD: pop(2); push(new Item("F")); break; case LALOAD: pop(2); push(new Item("J")); break; case AASTORE: case BASTORE: case CASTORE: case DASTORE: case FASTORE: case IASTORE: case LASTORE: case SASTORE: pop(3); break; case BIPUSH: case SIPUSH: push(new Item("I", (Integer)dbc.getIntConstant())); break; case IADD: case ISUB: case IMUL: case IDIV: case IAND: case IOR: case IXOR: case ISHL: case ISHR: case IREM: case IUSHR: it = pop(); it2 = pop(); pushByIntMath(dbc, seen, it2, it); break; case INEG: it = pop(); if (it.getConstant() instanceof Integer) { push(new Item("I", ( Integer)(-(Integer) it.getConstant()))); } else { push(new Item("I")); } break; case LNEG: it = pop(); if (it.getConstant() instanceof Long) { push(new Item("J", ( Long)(-(Long) it.getConstant()))); } else { push(new Item("J")); } break; case FNEG: it = pop(); if (it.getConstant() instanceof Float) { push(new Item("F", ( Float)(-(Float) it.getConstant()))); } else { push(new Item("F")); } break; case DNEG: it = pop(); if (it.getConstant() instanceof Double) { push(new Item("D", ( Double)(-(Double) it.getConstant()))); } else { push(new Item("D")); } break; case LADD: case LSUB: case LMUL: case LDIV: case LAND: case LOR: case LXOR: case LSHL: case LSHR: case LREM: case LUSHR: it = pop(); it2 = pop(); pushByLongMath(seen, it2, it); break; case LCMP: handleLcmp(); break; case FCMPG: case FCMPL: handleFcmp(seen); break; case DCMPG: case DCMPL: handleDcmp(seen); break; case FADD: case FSUB: case FMUL: case FDIV: case FREM: it = pop(); it2 = pop(); pushByFloatMath(seen, it, it2); break; case DADD: case DSUB: case DMUL: case DDIV: case DREM: it = pop(); it2 = pop(); pushByDoubleMath(seen, it, it2); break; case I2B: it = pop(); if (it.getConstant() != null) { it =new Item("I", (byte)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.SIGNED_BYTE); push(it); break; case I2C: it = pop(); if (it.getConstant() != null) { it = new Item("I", (char)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.NON_NEGATIVE); push(it); break; case I2L: case D2L: case F2L:{ it = pop(); Item newValue; if (it.getConstant() != null) { newValue = new Item("J", constantToLong(it)); } else { newValue = new Item("J"); } newValue.setSpecialKind(it.getSpecialKind()); push(newValue); } break; case I2S: it = pop(); if (it.getConstant() != null) { push(new Item("I", (short)constantToInt(it))); } else { push(new Item("I")); } break; case L2I: case D2I: case F2I: it = pop(); if (it.getConstant() != null) { push(new Item("I",constantToInt(it))); } else { push(new Item("I")); } break; case L2F: case D2F: case I2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", (Float)(constantToFloat(it)))); } else { push(new Item("F")); } break; case F2D: case I2D: case L2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", constantToDouble(it))); } else { push(new Item("D")); } break; case NEW: pushBySignature("L" + dbc.getClassConstantOperand() + ";"); break; case NEWARRAY: pop(); signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature(); pushBySignature(signature); break; // According to the VM Spec 4.4.1, anewarray and multianewarray // can refer to normal class/interface types (encoded in // "internal form"), or array classes (encoded as signatures // beginning with "["). case ANEWARRAY: pop(); signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { signature = "[L" + signature + ";"; } pushBySignature(signature); break; case MULTIANEWARRAY: int dims = dbc.getIntConstant(); while ((dims pop(); } signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { dims = dbc.getIntConstant(); signature = Util.repeat("[", dims) +"L" + signature + ";"; } pushBySignature(signature); break; case AALOAD: pop(); it = pop(); pushBySignature(it.getElementSignature()); break; case JSR: seenTransferOfControl = true; setReachOnlyByBranch(false); push(new Item("")); // push return address on stack addJumpValue(dbc.getPC(), dbc.getBranchTarget()); pop(); if (dbc.getBranchOffset() < 0) { // OK, backwards JSRs are weird; reset the stack. int stackSize = stack.size(); stack.clear(); for(int i = 0; i < stackSize; i++) stack.add(new Item()); } setTop(false); break; case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEVIRTUAL: processMethodCall(dbc, seen); break; default: throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " ); } } catch (RuntimeException e) { //If an error occurs, we clear the stack and locals. one of two things will occur. //Either the client will expect more stack items than really exist, and so they're condition check will fail, //or the stack will resync with the code. But hopefully not false positives String msg = "Error processing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); if (DEBUG) e.printStackTrace(); clear(); } finally { if (DEBUG) { System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth()); System.out.println(this); } } } /** * @param it * @return */ private int constantToInt(Item it) { return ((Number)it.getConstant()).intValue(); } /** * @param it * @return */ private float constantToFloat(Item it) { return ((Number)it.getConstant()).floatValue(); } /** * @param it * @return */ private double constantToDouble(Item it) { return ((Number)it.getConstant()).doubleValue(); } /** * @param it * @return */ private long constantToLong(Item it) { return ((Number)it.getConstant()).longValue(); } /** * handle dcmp * */ private void handleDcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { double d = (Double) it.getConstant(); double d2 = (Double) it.getConstant(); if (Double.isNaN(d) || Double.isNaN(d2)) { if (opcode == DCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (d2 < d) push(new Item("I", (Integer) (-1) )); else if (d2 > d) push(new Item("I", (Integer)1)); else push(new Item("I", (Integer)0)); } else { push(new Item("I")); } } /** * handle fcmp * */ private void handleFcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { float f = (Float) it.getConstant(); float f2 = (Float) it.getConstant(); if (Float.isNaN(f) || Float.isNaN(f2)) { if (opcode == FCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (f2 < f) push(new Item("I", (Integer)(-1))); else if (f2 > f) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle lcmp */ private void handleLcmp() { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { long l = (Long) it.getConstant(); long l2 = (Long) it.getConstant(); if (l2 < l) push(new Item("I", (Integer)(-1))); else if (l2 > l) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle swap */ private void handleSwap() { Item i1 = pop(); Item i2 = pop(); push(i1); push(i2); } /** * handleDup */ private void handleDup() { Item it; it = pop(); push(it); push(it); } /** * handle dupX1 */ private void handleDupX1() { Item it; Item it2; it = pop(); it2 = pop(); push(it); push(it2); push(it); } /** * handle dup2 */ private void handleDup2() { Item it, it2; it = pop(); if (it.getSize() == 2) { push(it); push(it); } else { it2 = pop(); push(it2); push(it); push(it2); push(it); } } /** * handle Dup2x1 */ private void handleDup2X1() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it2); push(it); push(it3); push(it2); push(it); } } private void handleDup2X2() { String signature; Item it = pop(); Item it2 = pop(); if (it.isWide()) { if (it2.isWide()) { push(it); push(it2); push(it); } else { Item it3 = pop(); push(it); push(it3); push(it2); push(it); } } else { Item it3 = pop(); if (it3.isWide()) { push(it2); push(it); push(it3); push(it2); push(it); } else { Item it4 = pop(); push(it2); push(it); push(it4); push(it3); push(it2); push(it); } } } /** * Handle DupX2 */ private void handleDupX2() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it2.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it); push(it3); push(it2); push(it); } } private void processMethodCall(DismantleBytecode dbc, int seen) { String clsName = dbc.getClassConstantOperand(); String methodName = dbc.getNameConstantOperand(); String signature = dbc.getSigConstantOperand(); String appenderValue = null; boolean servletRequestParameterTainted = false; boolean sawUnknownAppend = false; Item sbItem = null; //TODO: stack merging for trinaries kills the constant.. would be nice to maintain. if ("java/lang/StringBuffer".equals(clsName) || "java/lang/StringBuilder".equals(clsName)) { if ("<init>".equals(methodName)) { if ("(Ljava/lang/String;)V".equals(signature)) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("()V".equals(signature)) { appenderValue = ""; } } else if ("toString".equals(methodName) && getStackDepth() >= 1) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("append".equals(methodName)) { if (signature.indexOf("II)") == -1 && getStackDepth() >= 2) { sbItem = getStackItem(1); Item i = getStackItem(0); if (i.isServletParameterTainted() || sbItem.isServletParameterTainted()) servletRequestParameterTainted = true; Object sbVal = sbItem.getConstant(); Object sVal = i.getConstant(); if ((sbVal != null) && (sVal != null)) { appenderValue = sbVal + sVal.toString(); } else if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else if (signature.startsWith("([CII)")) { sawUnknownAppend = true; sbItem = getStackItem(3); if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else { sawUnknownAppend = true; } } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/FileOutputStream") && methodName.equals("<init>") && (signature.equals("(Ljava/io/File;Z)V") || signature.equals("(Ljava/lang/String;Z)V"))) { OpcodeStack.Item item = getStackItem(0); Object value = item.getConstant(); if ( value instanceof Integer && ((Integer)value).intValue() == 1) { pop(3); Item top = getStackItem(0); if (top.signature.equals("Ljava/io/FileOutputStream;")) { top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); } return; } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/BufferedOutputStream") && methodName.equals("<init>") && signature.equals("(Ljava/io/OutputStream;)V")) { OpcodeStack.Item item = getStackItem(0); if (getStackItem(0).getSpecialKind() == Item.FILE_OPENED_IN_APPEND_MODE && getStackItem(2).signature.equals("Ljava/io/BufferedOutputStream;")) { pop(2); Item top = getStackItem(0); top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); return; } } pushByInvoke(dbc, seen != INVOKESTATIC); if ((sawUnknownAppend || appenderValue != null || servletRequestParameterTainted) && getStackDepth() > 0) { Item i = this.getStackItem(0); i.constValue = appenderValue; if (!sawUnknownAppend && servletRequestParameterTainted) i.setServletParameterTainted(); if (sbItem != null) { i.registerNumber = sbItem.registerNumber; i.source = sbItem.source; i.userValue = sbItem.userValue; if (sbItem.registerNumber >= 0) setLVValue(sbItem.registerNumber, i ); } return; } if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) { Item i = pop(); i.setSpecialKind(Item.RANDOM_INT); i.source = XFactory.createReferencedXMethod(dbc); push(i); } else if (methodName.equals("getParameter") && clsName.equals("javax/servlet/http/HttpServletRequest")) { Item i = pop(); i.setSpecialKind(Item.SERVLET_REQUEST_TAINTED); i.source = XFactory.createReferencedXMethod(dbc); push(i); } else if (clsName.equals("java/lang/Math") && methodName.equals("abs")) { Item i = pop(); i.setSpecialKind(Item.MATH_ABS); i.source = XFactory.createReferencedXMethod(dbc); push(i); } else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I") || seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) { Item i = pop(); i.setSpecialKind(Item.HASHCODE_INT); i.source = XFactory.createReferencedXMethod(dbc); push(i); } else if (!signature.endsWith(")V")) { Item i = pop(); i.source = XFactory.createReferencedXMethod(dbc); push(i); } } private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) { // merge stacks int intoSize = mergeInto.size(); int fromSize = mergeFrom.size(); if (errorIfSizesDoNotMatch && intoSize != fromSize) { if (DEBUG2) { System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } } else { if (DEBUG2) { if (intoSize == fromSize) System.out.println("Merging items"); else System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } for (int i = 0; i < Math.min(intoSize, fromSize); i++) mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i))); if (DEBUG2) { System.out.println("merged items: " + mergeInto); } } } public void clear() { stack.clear(); lvValues.clear(); } boolean encountedTop; boolean backwardsBranch; BitSet exceptionHandlers = new BitSet(); private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>(); private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>(); private BitSet jumpEntryLocations = new BitSet(); static class JumpInfo { final Map<Integer, List<Item>> jumpEntries; final Map<Integer, List<Item>> jumpStackEntries; final BitSet jumpEntryLocations; JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) { this.jumpEntries = jumpEntries; this.jumpStackEntries = jumpStackEntries; this.jumpEntryLocations = jumpEntryLocations; } } public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> { public JumpInfoFactory() { super("Jump info for opcode stack", JumpInfo.class); } public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { Method method = analysisCache.getMethodAnalysis(Method.class, descriptor); JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor()); Code code = method.getCode(); final OpcodeStack stack = new OpcodeStack(); if (code == null) { return null; } DismantleBytecode branchAnalysis = new DismantleBytecode() { @Override public void sawOpcode(int seen) { stack.sawOpcode(this, seen); } }; branchAnalysis.setupVisitorForClass(jclass); int oldCount = 0; while (true) { stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method); branchAnalysis.doVisitMethod(method); int newCount = stack.jumpEntries.size(); if (newCount == oldCount || !stack.encountedTop || !stack.backwardsBranch) break; oldCount = newCount; } return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations); }} private void addJumpValue(int from, int target) { if (DEBUG) System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues ); if (from >= target) backwardsBranch = true; List<Item> atTarget = jumpEntries.get(target); if (atTarget == null) { if (DEBUG) System.out.println("Was null"); jumpEntries.put(target, new ArrayList<Item>(lvValues)); jumpEntryLocations.set(target); if (stack.size() > 0) { jumpStackEntries.put(target, new ArrayList<Item>(stack)); } return; } mergeLists(atTarget, lvValues, false); List<Item> stackAtTarget = jumpStackEntries.get(target); if (stack.size() > 0 && stackAtTarget != null) mergeLists(stackAtTarget, stack, false); if (DEBUG) System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget); } private String methodName; DismantleBytecode v; public void learnFrom(JumpInfo info) { jumpEntries = new HashMap<Integer, List<Item>>(info.jumpEntries); jumpStackEntries = new HashMap<Integer, List<Item>>(info.jumpStackEntries); jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone(); } public void initialize() { setTop(false); jumpEntries.clear(); jumpStackEntries.clear(); jumpEntryLocations.clear(); encountedTop = false; backwardsBranch = false; lastUpdate.clear(); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; setReachOnlyByBranch(false); } public int resetForMethodEntry(final DismantleBytecode v) { this.v = v; initialize(); int result = resetForMethodEntry0(v); Code code = v.getMethod().getCode(); if (code == null) return result; if (useIterativeAnalysis) { IAnalysisCache analysisCache = Global.getAnalysisCache(); XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod()); try { JumpInfo jump = analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor()); if (jump != null) { learnFrom(jump); } } catch (CheckedAnalysisException e) { AnalysisContext.logError("Error getting jump information", e); } } return result; } private int resetForMethodEntry0(PreorderVisitor v) { return resetForMethodEntry0(v.getClassName(), v.getMethod()); } private int resetForMethodEntry0(@SlashedClassName String className, Method m) { methodName = m.getName(); if (DEBUG) System.out.println(" String signature = m.getSignature(); stack.clear(); lvValues.clear(); top = false; encountedTop = false; backwardsBranch = false; setReachOnlyByBranch(false); seenTransferOfControl = false; exceptionHandlers.clear(); Code code = m.getCode(); if (code != null) { CodeException[] exceptionTable = code.getExceptionTable(); if (exceptionTable != null) for(CodeException ex : exceptionTable) exceptionHandlers.set(ex.getHandlerPC()); } if (DEBUG) System.out.println(" --- " + className + " " + m.getName() + " " + signature); Type[] argTypes = Type.getArgumentTypes(signature); int reg = 0; if (!m.isStatic()) { Item it = new Item("L" + className+";"); it.setInitialParameter(true); it.registerNumber = reg; setLVValue( reg, it); reg += it.getSize(); } for (Type argType : argTypes) { Item it = new Item(argType.getSignature()); it.registerNumber = reg; it.setInitialParameter(true); setLVValue(reg, it); reg += it.getSize(); } return reg; } public int getStackDepth() { return stack.size(); } public Item getStackItem(int stackOffset) { if (stackOffset < 0 || stackOffset >= stack.size()) { AnalysisContext.logError("Can't get stack offset " + stackOffset + " from " + stack.toString() +" @ " + v.getPC() + " in " + v.getFullyQualifiedMethodName(), new IllegalArgumentException()); return new Item("Lfindbugs/OpcodeStackError;"); } int tos = stack.size() - 1; int pos = tos - stackOffset; try { return stack.get(pos); } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException( "Requested item at offset " + stackOffset + " in a stack of size " + stack.size() +", made request for position " + pos); } } private Item pop() { return stack.remove(stack.size()-1); } public void replaceTop(Item newTop) { pop(); push(newTop); } private void pop(int count) { while ((count pop(); } private void push(Item i) { stack.add(i); } private void pushByConstant(DismantleBytecode dbc, Constant c) { if (c instanceof ConstantClass) push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool()))); else if (c instanceof ConstantInteger) push(new Item("I", (Integer)(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantString) { int s = ((ConstantString) c).getStringIndex(); push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s))); } else if (c instanceof ConstantFloat) push(new Item("F", (Float)(((ConstantFloat) c).getBytes()))); else if (c instanceof ConstantDouble) push(new Item("D", (Double)(((ConstantDouble) c).getBytes()))); else if (c instanceof ConstantLong) push(new Item("J", (Long)(((ConstantLong) c).getBytes()))); else throw new UnsupportedOperationException("Constant type not expected" ); } private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) { Method m = dbc.getMethod(); LocalVariableTable lvt = m.getLocalVariableTable(); if (lvt != null) { LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC()); if (lv != null) { String signature = lv.getSignature(); pushByLocalLoad(signature, register); return; } } pushByLocalLoad("", register); } private void pushByIntMath(DismantleBytecode dbc, int seen, Item lhs, Item rhs) { Item newValue = new Item("I"); if (lhs == null || rhs == null) { push(newValue); return; } try { if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() ); if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Integer lhsValue = (Integer) lhs.getConstant(); Integer rhsValue = (Integer) rhs.getConstant(); if (seen == IADD) newValue = new Item("I",lhsValue + rhsValue); else if (seen == ISUB) newValue = new Item("I",lhsValue - rhsValue); else if (seen == IMUL) newValue = new Item("I", lhsValue * rhsValue); else if (seen == IDIV) newValue = new Item("I", lhsValue / rhsValue); else if (seen == IAND) { newValue = new Item("I", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == IOR) newValue = new Item("I",lhsValue | rhsValue); else if (seen == IXOR) newValue = new Item("I",lhsValue ^ rhsValue); else if (seen == ISHL) { newValue = new Item("I",lhsValue << rhsValue); if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == ISHR) newValue = new Item("I",lhsValue >> rhsValue); else if (seen == IREM) newValue = new Item("I", lhsValue % rhsValue); else if (seen == IUSHR) newValue = new Item("I", lhsValue >>> rhsValue); } else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == IAND) { int value = (Integer) lhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } else if (rhs.getConstant() != null && seen == IAND) { int value = (Integer) rhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } } catch (ArithmeticException e) { assert true; // ignore it } catch (RuntimeException e) { String msg = "Error processing2 " + lhs + OPCODE_NAMES[seen] + rhs + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); } if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) { int rhsValue = (Integer) rhs.getConstant(); if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1) newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION; } if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null ) newValue.specialKind = Item.INTEGER_SUM; if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT) newValue.specialKind = Item.HASHCODE_INT_REMAINDER; if (seen == IREM && lhs.specialKind == Item.RANDOM_INT) newValue.specialKind = Item.RANDOM_INT_REMAINDER; if (DEBUG) System.out.println("push: " + newValue); push(newValue); } private void pushByLongMath(int seen, Item lhs, Item rhs) { Item newValue = new Item("J"); try { if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Long lhsValue = ((Long) lhs.getConstant()); if (seen == LSHL) { newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue()); if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LSHR) newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue()); else if (seen == LUSHR) newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue()); else { Long rhsValue = ((Long) rhs.getConstant()); if (seen == LADD) newValue = new Item("J", lhsValue + rhsValue); else if (seen == LSUB) newValue = new Item("J", lhsValue - rhsValue); else if (seen == LMUL) newValue = new Item("J", lhsValue * rhsValue); else if (seen == LDIV) newValue =new Item("J", lhsValue / rhsValue); else if (seen == LAND) { newValue = new Item("J", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LOR) newValue = new Item("J", lhsValue | rhsValue); else if (seen == LXOR) newValue =new Item("J", lhsValue ^ rhsValue); else if (seen == LREM) newValue =new Item("J", lhsValue % rhsValue); } } else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } catch (RuntimeException e) { // ignore it } push(newValue); } private void pushByFloatMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) { if (seen == FADD) result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant())); else if (seen == FSUB) result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant())); else if (seen == FMUL) result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant())); else if (seen == FDIV) result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant())); else if (seen == FREM) result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant())); else result =new Item("F"); } else { result =new Item("F"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByDoubleMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) { if (seen == DADD) result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant())); else if (seen == DSUB) result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant())); else if (seen == DMUL) result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant())); else if (seen == DDIV) result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant())); else if (seen == DREM) result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant())); else result = new Item("D"); } else { result = new Item("D"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByInvoke(DismantleBytecode dbc, boolean popThis) { String signature = dbc.getSigConstantOperand(); pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0)); pushBySignature(Type.getReturnType(signature).getSignature()); } private String getStringFromIndex(DismantleBytecode dbc, int i) { ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i); return name.getBytes(); } private void pushBySignature(String s) { if ("V".equals(s)) return; push(new Item(s, (Object) null)); } private void pushByLocalStore(int register) { Item it = pop(); if (it.getRegisterNumber() != register) { for(Item i : lvValues) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } for(Item i : stack) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } } setLVValue( register, it ); } private void pushByLocalLoad(String signature, int register) { Item it = getLVValue(register); if (it == null) { Item item = new Item(signature); item.registerNumber = register; push(item); } else if (it.getRegisterNumber() >= 0) push(it); else { push(new Item(it, register)); } } private void setLVValue(int index, Item value ) { int addCount = index - lvValues.size() + 1; while ((addCount lvValues.add(null); if (!useIterativeAnalysis && seenTransferOfControl) value = Item.merge(value, lvValues.get(index) ); lvValues.set(index, value); } private Item getLVValue(int index) { if (index >= lvValues.size()) return new Item(); return lvValues.get(index); } /** * @param top The top to set. */ private void setTop(boolean top) { if (top) { if (!this.top) this.top = true; } else if (this.top) this.top = false; } /** * @return Returns the top. */ public boolean isTop() { if (top) return true; return false; } /** * @param reachOnlyByBranch The reachOnlyByBranch to set. */ void setReachOnlyByBranch(boolean reachOnlyByBranch) { if (reachOnlyByBranch) setTop(true); this.reachOnlyByBranch = reachOnlyByBranch; } /** * @return Returns the reachOnlyByBranch. */ boolean isReachOnlyByBranch() { return reachOnlyByBranch; } } // vim:ts=4
package org.minimalj.frontend.editor; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.logging.Logger; import org.minimalj.application.Configuration; import org.minimalj.frontend.Frontend; import org.minimalj.frontend.Frontend.IContent; import org.minimalj.frontend.action.Action; import org.minimalj.frontend.form.Form; import org.minimalj.frontend.page.Page.Dialog; import org.minimalj.model.validation.ValidationMessage; import org.minimalj.util.CloneHelper; import org.minimalj.util.ExceptionUtils; import org.minimalj.util.GenericUtils; import org.minimalj.util.mock.Mocking; import org.minimalj.util.resources.Resources; /** * * @param <T> The class of the edited object * @param <RESULT> The class of the object returned by the save method. This can be the same as the one * of the edited object. Then you could use the {@link SimpleEditor}. In more complex situations the * backend called in the save method will do some business logic resulting in a different output object. */ public abstract class Editor<T, RESULT> extends Action implements Dialog { private static final Logger logger = Logger.getLogger(Editor.class.getName()); private T object; private Form<T> form; private SaveAction saveAction; private final CancelAction cancelAction = new CancelAction(); private Consumer<RESULT> finishedListener; public Editor() { super(); } public Editor(String actionName) { super(actionName); } @Override protected Object[] getNameArguments() { Class<?> editedClass = getEditedClass(); if (editedClass != null) { String resourceName = Resources.getResourceName(editedClass); return new Object[]{Resources.getString(resourceName)}; } return null; } protected Class<?> getEditedClass() { return GenericUtils.getGenericClass(getClass()); } @Override public String getTitle() { return getName(); } @Override public IContent getContent() { return form.getContent(); } @Override public void run() { object = createObject(); form = createForm(); form.setChangeListener(this::validate); form.setObject(object); saveAction = new SaveAction(); saveAction.setForm(form); validate(form); Frontend.showDialog(this); } public void run(Consumer<RESULT> finishedListenr) { this.finishedListener = finishedListenr; run(); } @Override public List<Action> getActions() { List<Action> actions = new ArrayList<>(createAdditionalActions()); actions.add(cancelAction); actions.add(saveAction); return actions; } protected List<Action> createAdditionalActions() { List<Action> actions = new ArrayList<>(); if (Configuration.isDevModeActive() && (object instanceof Mocking || this instanceof Mocking)) { actions.add(new FillWithDemoDataAction()); } return actions; } protected abstract T createObject(); protected T getObject() { return object; } protected abstract Form<T> createForm(); private void validate(Form<?> form) { List<ValidationMessage> validationMessages = new ArrayList<>(); validationMessages.addAll(Validator.validate(object)); validate(object, validationMessages); boolean relevantValidationMessage = form.indicate(validationMessages); saveAction.setEnabled(!relevantValidationMessage); } protected void validate(T object, List<ValidationMessage> validationMessages) { } @Override public Action getSaveAction() { return saveAction; } @Override public Action getCancelAction() { return cancelAction; } private void save() { try { RESULT result = save(object); if (closeWith(result)) { Frontend.closeDialog(this); finished(result); } } catch (Exception x) { ExceptionUtils.logReducedStackTrace(logger, x); // TODO clever error handling, for example at login if jdbc is wrong Frontend.showError(x.getLocalizedMessage() != null ? x.getLocalizedMessage() : x.getClass().getSimpleName()); } } protected boolean closeWith(RESULT result) { return true; } protected abstract RESULT save(T object); protected void finished(RESULT result) { if (finishedListener != null) { finishedListener.accept(result); } } protected final class SaveAction extends ValidationAwareAction { @Override public void run() { save(); } } private class CancelAction extends Action { @Override public void run() { cancel(); } } private void cancel() { Frontend.closeDialog(this); } protected void objectChanged() { form.setObject(object); validate(form); } private class FillWithDemoDataAction extends Action { @Override public void run() { mock(); } } protected void mock() { if (object instanceof Mocking) { ((Mocking) object).mock(); objectChanged(); } else if (this instanceof Mocking) { form.mock(); validate(form); } } public static abstract class SimpleEditor<T> extends Editor<T, T> { public SimpleEditor() { } public SimpleEditor(String actionName) { super(actionName); } } public static abstract class NewObjectEditor<T> extends SimpleEditor<T> { public NewObjectEditor() { } public NewObjectEditor(String actionName) { super(actionName); } @Override protected T createObject() { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) getEditedClass(); return CloneHelper.newInstance(clazz); } } }
package com.fede.Utilities; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.CallLog; import android.provider.ContactsContract; import android.telephony.SmsManager; import com.fede.DbAdapter; import com.fede.GMailSender; import com.fede.HomeAloneService; import com.fede.MainTabActivity; import com.fede.NameNotFoundException; import com.fede.OkDialogInterface; import com.fede.R; import com.fede.TestStubInterface; public class GeneralUtils { public static final String EVENT_LIST_INTENT = "ShowEventList"; static TestStubInterface mTest = null; public static void setStubInterface(TestStubInterface test) { mTest = test; } public static void sendSms(String number, String message) { if(mTest != null){ // TODO Test only mTest.sendSms(number, message); return; } SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> parts = smsManager.divideMessage(message); smsManager.sendMultipartTextMessage(number, null, parts, null, null); } public static void sendMail(Context c, String body) throws Exception{ if(mTest != null){ // TODO Test only mTest.sendMail(body); return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); String mailDest = PrefUtils.getStringPreference(prefs, R.string.mail_to_forward_key, c); String mailUser = PrefUtils.getStringPreference(prefs, R.string.gmail_user_key, c); String mailPwd = PrefUtils.getStringPreference(prefs, R.string.gmail_pwd_key, c); GMailSender sender = new GMailSender(mailUser, mailPwd); boolean sent = false; for (int i = 0; i < 2; i++){ try{ sender.sendMail("HOMEALONE", body, "HomeAloneSoftware", mailDest); sent = true; break; }catch (Exception e){ } } if(!sent){ try{ sender.sendMail("HOMEALONE", body, "HomeAloneSoftware", mailDest); }catch (Exception e){ String shortDesc = c.getString(R.string.failed_to_send_email_to) + " " + mailDest ; String fullDesc = String.format(("%s %s %s"), c.getString(R.string.email_body_not_sent), body, e.getMessage()) ; notifyEvent(fullDesc, shortDesc, c); throw e; } } } // tells if the network is available public static boolean isNetworkAvailable(Context context) { boolean value = false; ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { value = true; } return value; } // Returns contact name from number public static String getNameFromNumber(String number, Context c) throws NameNotFoundException { String name = ""; String[] columns = {ContactsContract.PhoneLookup.DISPLAY_NAME}; Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, number); Cursor idCursor = c.getContentResolver().query(lookupUri, columns, null, null, null); if (idCursor.moveToFirst()) { int nameIdx = idCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME); name = idCursor.getString(nameIdx); }else{ throw new NameNotFoundException(number); } idCursor.close(); return name; } // Tells if is a valid phone number static public boolean isPhoneNumber(String number){ // TODO Singleton is more efficent Pattern phoneNumPattern = Pattern.compile("\\+?[0-9]+"); // Begins (or not) with a plus and then the number Matcher matcher = phoneNumPattern.matcher(number); if(matcher.matches()) return true; else return false; } // Tells if is a valid email address static public boolean isMail(String number){ Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+"); Matcher matcher = pattern.matcher(number); if(matcher.matches()) return true; else return false; } public static void showErrorDialog(String errorString, Context context) { showErrorDialog(errorString, context, new OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { // do nothing } }); return; } public static void showErrorDialog(String errorString, Context context, OnClickListener l) { String button1String = context.getString(R.string.ok_name); AlertDialog.Builder ad = new AlertDialog.Builder(context); ad.setTitle(context.getString(R.string.error_name)); ad.setMessage(errorString); OkDialogInterface j; ad.setPositiveButton(button1String,l); ad.show(); return; } public static void showConfirmDialog(String errorString, Context context, OnClickListener l) { AlertDialog.Builder ad = new AlertDialog.Builder(context); ad.setMessage(errorString); ad.setPositiveButton(R.string.ok_name,l); ad.setNegativeButton(R.string.cancel, null); ad.show(); return; } public static void notifyEvent(String event, String fullDescEvent, Context c, DbAdapter dbHelper){ dbHelper.addEvent(fullDescEvent, event); // Add to sqlite anyway if(PrefUtils.homeAloneEnabled(c) == false) // if the status is disabled I dont want to show the notification return; String svcName = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager)c.getSystemService(svcName); // TODO set a valid icon int icon = R.drawable.ic_stat_home_alone_notify; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, event, when); notification.number = -1; String expandedText = fullDescEvent; String expandedTitle = c.getString(R.string.home_alone_event); // Intent to launch an activity when the extended text is clicked Intent intent = new Intent(c, MainTabActivity.class); intent.putExtra(EVENT_LIST_INTENT, true); PendingIntent launchIntent = PendingIntent.getActivity(c, 0, intent, 0); notification.setLatestEventInfo(c, expandedTitle, expandedText, launchIntent); int notificationRef = 1; notificationManager.notify(notificationRef, notification); } public static void removeNotifications(Context c){ String svcName = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager)c.getSystemService(svcName); notificationManager.cancel(1); } public static void notifyEvent(String event, String fullDescEvent, Context c){ DbAdapter dbHelper = new DbAdapter(c); dbHelper.open(); notifyEvent(event, fullDescEvent, c, dbHelper); dbHelper.close(); Intent i = new Intent(HomeAloneService.HOMEALONE_EVENT_PROCESSED); c.sendBroadcast(i); } public static String[] getContactNumbers(String contact, Context c) throws NameNotFoundException{ // Find a contact using a partial name match Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, contact); Cursor idCursor = c.getContentResolver().query(lookupUri, null, null, null, null); String id = null; if (idCursor.moveToFirst()) { // I try with the first record int idIdx = idCursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID); id = idCursor.getString(idIdx); } idCursor.close(); if (id != null) { // Return all the contact details of type PHONE for the contact we found String where = ContactsContract.Data.CONTACT_ID + " = " + id + " AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE +"'"; Cursor dataCursor = c.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, null, null); // Use the convenience properties to get the index of the columns int nameIdx = dataCursor.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME); int phoneIdx = dataCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER); String[] result = new String[dataCursor.getCount()]; if (dataCursor.moveToFirst()) do { // Extract the name. String name = dataCursor.getString(nameIdx); // Extract the phone number. String number = dataCursor.getString(phoneIdx); result[dataCursor.getPosition()] = name + " (" + number + ")"; } while(dataCursor.moveToNext()); dataCursor.close(); return result; } throw new NameNotFoundException(""); } private static Long get24HoursAgoTime(){ Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR, -24); return cal.getTimeInMillis(); } public static String[] getMissedCalls(Context context){ Long lastFlushed = PrefUtils.getLastFlushedCalls(context); java.text.DateFormat timeForm = android.text.format.DateFormat.getTimeFormat(context); Long yesterday = get24HoursAgoTime(); if(lastFlushed == 0 || lastFlushed < yesterday){ lastFlushed = yesterday; // not later than 24 hours ago } String where = android.provider.CallLog.Calls.TYPE + " = " + android.provider.CallLog.Calls.MISSED_TYPE + " and " + android.provider.CallLog.Calls.DATE + " > " + lastFlushed; Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, where, null, android.provider.CallLog.Calls.DATE + " DESC"); int nameIdx = c.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME); int numbIdx = c.getColumnIndexOrThrow(CallLog.Calls.NUMBER); int dateIdx = c.getColumnIndexOrThrow(CallLog.Calls.DATE); String[] result = new String[c.getCount()]; if (c.moveToFirst()) do { String name = c.getString(nameIdx); name = (name != null)? name : ""; String number = c.getString(numbIdx); String when = timeForm.format(c.getLong(dateIdx)); result[c.getPosition()] = String.format(context.getString(R.string.flushed_calls), name, number, when); } while(c.moveToNext()); c.close(); PrefUtils.setLastFlushedCalls( context); return result; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jbpm.console.ng.ht.service; import java.util.Date; import java.util.List; import java.util.Map; import org.jboss.errai.bus.server.annotations.Remote; import org.jbpm.console.ng.ht.model.CommentSummary; import org.jbpm.console.ng.ht.model.Day; import org.jbpm.console.ng.ht.model.IdentitySummary; import org.jbpm.console.ng.ht.model.TaskSummary; @Remote public interface TaskServiceEntryPoint { List<TaskSummary> getTasksAssignedAsBusinessAdministrator(String userId, String language); List<TaskSummary> getTasksAssignedAsExcludedOwner(String userId, String language); List<TaskSummary> getTasksAssignedAsPotentialOwner(String userId, String language); List<TaskSummary> getTasksAssignedAsPotentialOwner(String userId, List<String> groupIds, String language); List<TaskSummary> getTasksAssignedAsPotentialOwner(String userId, List<String> groupIds, String language, int firstResult, int maxResult); List<TaskSummary> getTasksAssignedAsRecipient(String userId, String language); List<TaskSummary> getTasksAssignedAsTaskInitiator(String userId, String language); List<TaskSummary> getTasksAssignedAsTaskStakeholder(String userId, String language); List<TaskSummary> getTasksAssignedByGroup(String groupId, String language); List<TaskSummary> getTasksAssignedByGroups(List<String> groupsId, String language); /** * Gets the mapping '{@link Day} -> list of owned tasks' from start day to end day (including). * * Only active tasks are considered (task with status "InProgress", "Reserved" or "Created"). * * @param userId id of the task owner * @param from start day * @param to end day * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksOwnedFromDateToDateByDays(String userId, Date from, Date to, String language); /** * Gets the mapping '{@link Day} -> list of owned tasks' starting from specified day and for specified number of days. * * Only active tasks are considered (task with status "InProgress", "Reserved" or "Created"). * * @param userId id of the task owner * @param from start day * @param nrOfDaysTotal how many days to return including start date * @param language * * @return list of task per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksOwnedFromDateToDateByDays(String userId, Date from, int nrOfDaysTotal, String language); /** * Gets the mapping '{@link Day} -> list of owned tasks' from start day to end day (including). * Only tasks with specified statuses are considered. * * @param userId id of the task owner * @param strStatuses list of statuses * @param from start day * @param to end day * @param language * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksOwnedFromDateToDateByDays(String userId, List<String> strStatuses, Date from, Date to, String language); /** * Gets the mapping '{@link Day} -> list of owned tasks' starting from specified dayand for specified number of days. * Only tasks with specified statuses are considered. * * @param userId id of the task owner * @param from start day * @param nrOfDaysTotal how many days to return including start date * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksOwnedFromDateToDateByDays(String userId, List<String> strStatuses, Date from, int nrOfDaysTotal, String language); /** * Gets the mapping '{@link Day} -> list of assigned personal and groups tasks' from start day to end day (including). * * Only tasks with status "Ready", "InProgress", "Reserved" or "Created" are considered. * * @param userId id of the task owner * @param groupIds list of group ids * @param from start day * @param to end day * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksAssignedFromDateToDatePersonalAndGroupsTasksByDays(String userId, List<String> groupIds, Date from, Date to, String language); /** * Gets the mapping '{@link Day} -> list of assigned personal and groups tasks' starting from specified day and for specified number of days. * * Only tasks with status "Ready", "InProgress", "Reserved" or "Created" are considered. * * @param userId id of the task owner * @param groupIds list of group ids * @param from start day * @param nrOfDaysTotal how many days to return including start date * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksAssignedFromDateToDatePersonalAndGroupsTasksByDays(String userId, List<String> groupIds, Date from, int nrOfDaysTotal, String language); /** * Gets the mapping '{@link Day} -> list of assigned groups tasks' from start day to end day (including). * * @param groupIds list of group ids * @param from start day * @param to end day * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksAssignedFromDateToDateByGroupsByDays(List<String> groupIds, Date from, Date to, String language); /** * Gets the mapping '{@link Day} -> list of assigned groups tasks' starting from specified day and for specified number of days. * * @param groupIds list of group ids * @param from start day * @param nrOfDaysTotal how many days to return including start date * @param language * * @return list of tasks per day for specified days (dates) */ Map<Day, List<TaskSummary>> getTasksAssignedFromDateToDateByGroupsByDays(List<String> groupIds, Date from, int nrOfDaysTotal, String language); List<TaskSummary> getTasksOwned(String userId); List<TaskSummary> getTasksOwned(String userId, List<String> status, String language); List<TaskSummary> getSubTasksAssignedAsPotentialOwner(long parentId, String userId, String language); List<TaskSummary> getSubTasksByParent(long parentId); long addTask(String taskString, Map<String, Object> inputs, Map<String, Object> templateInputs); long addTaskAndStart(String taskString, Map<String, Object> inputs, String userId, Map<String, Object> templateInputs); void start(long taskId, String user); void startBatch(List<Long> taskIds, String user); void claim(long taskId, String user); void claimBatch(List<Long> taskIds, String user); void complete(long taskId, String user, Map<String, Object> params); void completeBatch(List<Long> taskIds, String user, Map<String, Object> params); void release(long taskId, String user); void releaseBatch(List<Long> taskIds, String user); void forward(long taskId, String userId, String targetEntityId); void setPriority(long taskId, int priority); void setExpirationDate(long taskId, Date date); void setDescriptions(long taskId, List<String> descriptions); void setSkipable(long taskId, boolean skipable); void setSubTaskStrategy(long taskId, String strategy); int getPriority(long taskId); Date getExpirationDate(long taskId); List<String> getDescriptions(long taskId); boolean isSkipable(long taskId); String getSubTaskStrategy(long taskId); TaskSummary getTaskDetails(long taskId); long saveContent(long taskId, Map<String, String> values); Map<String, String> getContentListById(long contentId); Map<String, String> getTaskOutputContentByTaskId(long taskId); Map<String, String> getContentListByTaskId(long taskId); int getCompletedTaskByUserId(String userId); int getPendingTaskByUserId(String userId); List<TaskSummary> getTasksAssignedPersonalAndGroupTasks(String userId, String groupId, String language); List<TaskSummary> getTasksAssignedPersonalAndGroupsTasks(String userId, List<String> groupIds, String language); IdentitySummary getOrganizationalEntityById(String entityId); List<IdentitySummary> getOrganizationalEntities(); long addComment(long taskId, String text, String addedBy, Date addedOn); void deleteComment(long taskId, long commentId); List<CommentSummary> getAllCommentsByTaskId(long taskId); CommentSummary getCommentById(long commentId); void updateSimpleTaskDetails(long taskId, List<String> taskNames, int priority, List<String> taskDescription, String subTaskStrategy, Date dueDate); }
package org.neo4j.com; import java.io.IOException; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.List; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.queue.BlockingReadHandler; import org.neo4j.com.storecopy.StoreWriter; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.nioneo.xa.CommandReaderFactory; import org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource; import org.neo4j.kernel.impl.nioneo.xa.command.Command; import org.neo4j.kernel.impl.transaction.xaframework.CommandWriter; import org.neo4j.kernel.impl.transaction.xaframework.CommittedTransactionRepresentation; import org.neo4j.kernel.impl.transaction.xaframework.LogEntry; import org.neo4j.kernel.impl.transaction.xaframework.LogEntryReader; import org.neo4j.kernel.impl.transaction.xaframework.LogEntryWriterv1; import org.neo4j.kernel.impl.transaction.xaframework.PhysicalTransactionCursor; import org.neo4j.kernel.impl.transaction.xaframework.PhysicalTransactionRepresentation; import org.neo4j.kernel.impl.transaction.xaframework.ReadableLogChannel; import org.neo4j.kernel.impl.transaction.xaframework.TransactionRepresentation; import org.neo4j.kernel.impl.transaction.xaframework.VersionAwareLogEntryReader; import static org.neo4j.kernel.impl.util.Cursors.exhaustAndClose; /** * Contains the logic for serializing requests and deserializing responses. Still missing the inverse, serializing * responses and deserializing requests, which is hard-coded in the server class. That should be moved over * eventually. */ public class Protocol { public static final int MEGA = 1024 * 1024; public static final int DEFAULT_FRAME_LENGTH = 16*MEGA; private final int chunkSize; private final byte applicationProtocolVersion; private final byte internalProtocolVersion; public Protocol( int chunkSize, byte applicationProtocolVersion, byte internalProtocolVersion ) { this.chunkSize = chunkSize; this.applicationProtocolVersion = applicationProtocolVersion; this.internalProtocolVersion = internalProtocolVersion; } public void serializeRequest( Channel channel, ChannelBuffer buffer, RequestType<?> type, RequestContext ctx, Serializer payload ) throws IOException { buffer.clear(); ChunkingChannelBuffer chunkingBuffer = new ChunkingChannelBuffer( buffer, channel, chunkSize, internalProtocolVersion, applicationProtocolVersion ); chunkingBuffer.writeByte( type.id() ); writeContext( ctx, chunkingBuffer ); payload.write( chunkingBuffer ); chunkingBuffer.done(); } public <PAYLOAD> Response<PAYLOAD> deserializeResponse(BlockingReadHandler<ChannelBuffer> reader, ByteBuffer input, long timeout, Deserializer<PAYLOAD> payloadDeserializer, ResourceReleaser channelReleaser) throws IOException { DechunkingChannelBuffer dechunkingBuffer = new DechunkingChannelBuffer( reader, timeout, internalProtocolVersion, applicationProtocolVersion ); PAYLOAD response = payloadDeserializer.read( dechunkingBuffer, input ); StoreId storeId = readStoreId( dechunkingBuffer, input ); return new Response<PAYLOAD>( response, storeId, readTransactionStreams( dechunkingBuffer ), channelReleaser ); } private void writeContext( RequestContext context, ChannelBuffer targetBuffer ) { targetBuffer.writeLong( context.getEpoch() ); targetBuffer.writeInt( context.machineId() ); targetBuffer.writeInt( context.getEventIdentifier() ); long tx = context.lastAppliedTransaction(); targetBuffer.writeLong( tx ); targetBuffer.writeInt( context.getMasterId() ); targetBuffer.writeLong( context.getChecksum() ); } private Iterable<CommittedTransactionRepresentation> readTransactionStreams( final ChannelBuffer buffer ) throws IOException { return COMMITTED_TRANSACTION_DESERIALIZER.read( buffer, null ); } private static void makeSureNextTransactionIsFullyFetched( ChannelBuffer buffer ) { buffer.markReaderIndex(); try { if ( buffer.readUnsignedByte() > 0 /* datasource id */ ) { buffer.skipBytes( 8 ); // tx id int blockSize = 0; while ( (blockSize = buffer.readUnsignedByte()) == 0 ) { buffer.skipBytes( BlockLogBuffer.DATA_SIZE ); } buffer.skipBytes( blockSize ); } } finally { buffer.resetReaderIndex(); } } private StoreId readStoreId( ChannelBuffer source, ByteBuffer byteBuffer ) { byteBuffer.clear(); byteBuffer.limit( StoreId.SIZE_IN_BYTES ); source.readBytes( byteBuffer ); byteBuffer.flip(); return StoreId.deserialize( byteBuffer ); } public static final ObjectSerializer<Integer> INTEGER_SERIALIZER = new ObjectSerializer<Integer>() { @Override @SuppressWarnings( "boxing" ) public void write( Integer responseObject, ChannelBuffer result ) throws IOException { result.writeInt( responseObject ); } }; public static final ObjectSerializer<Long> LONG_SERIALIZER = new ObjectSerializer<Long>() { @Override @SuppressWarnings( "boxing" ) public void write( Long responseObject, ChannelBuffer result ) throws IOException { result.writeLong( responseObject ); } }; public static final ObjectSerializer<Void> VOID_SERIALIZER = new ObjectSerializer<Void>() { @Override public void write( Void responseObject, ChannelBuffer result ) throws IOException { } }; public static final Deserializer<Integer> INTEGER_DESERIALIZER = new Deserializer<Integer>() { @Override public Integer read( ChannelBuffer buffer, ByteBuffer temporaryBuffer ) throws IOException { return buffer.readInt(); } }; public static final Deserializer<Void> VOID_DESERIALIZER = new Deserializer<Void>() { @Override public Void read( ChannelBuffer buffer, ByteBuffer temporaryBuffer ) throws IOException { return null; } }; public static final Serializer EMPTY_SERIALIZER = new Serializer() { @Override public void write( ChannelBuffer buffer ) throws IOException { } }; public static class FileStreamsDeserializer implements Deserializer<Void> { private final StoreWriter writer; public FileStreamsDeserializer( StoreWriter writer ) { this.writer = writer; } // NOTICE: this assumes a "smart" ChannelBuffer that continues to next chunk @Override public Void read( ChannelBuffer buffer, ByteBuffer temporaryBuffer ) throws IOException { int pathLength; while ( 0 != ( pathLength = buffer.readUnsignedShort() ) ) { String path = readString( buffer, pathLength ); boolean hasData = buffer.readByte() == 1; writer.write( path, hasData ? new BlockLogReader( buffer ) : null, temporaryBuffer, hasData ); } writer.close(); return null; } } public static class TransactionSerializer implements Serializer { private final TransactionRepresentation tx; public TransactionSerializer( TransactionRepresentation tx ) { this.tx = tx; } @Override public void write( ChannelBuffer buffer ) throws IOException { NetworkWritableLogChannel channel = new NetworkWritableLogChannel( buffer ); writeString( buffer, NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); channel.putInt( tx.getAuthorId() ); channel.putInt( tx.getMasterId() ); channel.putLong( tx.getLatestCommittedTxWhenStarted() ); channel.putLong( tx.getTimeWritten() ); channel.putInt( tx.additionalHeader().length ); channel.put( tx.additionalHeader(), tx.additionalHeader().length ); new LogEntryWriterv1( channel, new CommandWriter( channel ) ).serialize( tx ); } } public static final Deserializer<TransactionRepresentation> TRANSACTION_REPRESENTATION_DESERIALIZER = new Deserializer<TransactionRepresentation>() { @Override public TransactionRepresentation read( ChannelBuffer buffer, ByteBuffer temporaryBuffer ) throws IOException { LogEntryReader<ReadableLogChannel> reader = new VersionAwareLogEntryReader( CommandReaderFactory.DEFAULT ); NetworkReadableLogChannel channel = new NetworkReadableLogChannel( buffer ); int authorId = channel.getInt(); int masterId = channel.getInt(); long latestCommittedTxWhenStarted = channel.getLong(); long timeWritten = channel.getLong(); int headerLength = channel.getInt(); byte[] header = new byte[headerLength]; channel.get( header, headerLength ); LogEntry.Command entryRead; List<Command> commands = new LinkedList<>(); while ( (entryRead = (LogEntry.Command) reader.readLogEntry( channel )) != null ) { commands.add( entryRead.getXaCommand() ); } PhysicalTransactionRepresentation toReturn = new PhysicalTransactionRepresentation( commands ); toReturn.setHeader( header, masterId, authorId, timeWritten, latestCommittedTxWhenStarted ); return toReturn; } }; public static final Deserializer<Iterable<CommittedTransactionRepresentation>> COMMITTED_TRANSACTION_DESERIALIZER = new Deserializer<Iterable<CommittedTransactionRepresentation>>() { @Override public Iterable<CommittedTransactionRepresentation> read( ChannelBuffer buffer, ByteBuffer temporaryBuffer ) throws IOException { LogEntryReader<ReadableLogChannel> reader = new VersionAwareLogEntryReader( CommandReaderFactory.DEFAULT ); NetworkReadableLogChannel channel = new NetworkReadableLogChannel( buffer ); AccumulatorVisitor<CommittedTransactionRepresentation> accumulator = new AccumulatorVisitor<>(); exhaustAndClose( new PhysicalTransactionCursor( channel, reader, accumulator ) ); return accumulator.getAccumulator(); } }; public static class CommittedTransactionRepresentationSerializer implements Serializer { private final Iterable<CommittedTransactionRepresentation> txs; public CommittedTransactionRepresentationSerializer( Iterable<CommittedTransactionRepresentation> txs ) { this.txs = txs; } @Override public void write( ChannelBuffer buffer ) throws IOException { NetworkWritableLogChannel channel = new NetworkWritableLogChannel( buffer ); LogEntryWriterv1 writer = new LogEntryWriterv1( channel, new CommandWriter( channel ) ); for ( CommittedTransactionRepresentation tx : txs ) { LogEntry.Start startEntry = tx.getStartEntry(); writer.writeStartEntry( startEntry.getMasterId(), startEntry.getLocalId(), startEntry.getTimeWritten(), startEntry.getLastCommittedTxWhenTransactionStarted(), startEntry.getAdditionalHeader() ); writer.serialize( tx.getTransactionRepresentation() ); LogEntry.Commit commitEntry = tx.getCommitEntry(); writer.writeCommitEntry( commitEntry.getTxId(), commitEntry.getTimeWritten() ); } } } public static void addLengthFieldPipes( ChannelPipeline pipeline, int frameLength ) { pipeline.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( frameLength + 4, 0, 4, 0, 4 ) ); pipeline.addLast( "frameEncoder", new LengthFieldPrepender( 4 ) ); } public static void writeString( ChannelBuffer buffer, String name ) { char[] chars = name.toCharArray(); buffer.writeInt( chars.length ); writeChars( buffer, chars ); } public static void writeChars( ChannelBuffer buffer, char[] chars ) { // TODO optimize? for ( char ch : chars ) { buffer.writeChar( ch ); } } public static String readString( ChannelBuffer buffer ) { return readString( buffer, buffer.readInt() ); } public static boolean readBoolean( ChannelBuffer buffer ) { byte value = buffer.readByte(); switch ( value ) { case 0: return false; case 1: return true; default: throw new ComException( "Invalid boolean value " + value ); } } public static String readString( ChannelBuffer buffer, int length ) { char[] chars = new char[length]; for ( int i = 0; i < length; i++ ) { chars[i] = buffer.readChar(); } return new String( chars ); } public static void assertChunkSizeIsWithinFrameSize( int chunkSize, int frameLength ) { if ( chunkSize > frameLength ) { throw new IllegalArgumentException( "Chunk size " + chunkSize + " needs to be equal or less than frame length " + frameLength ); } } }
package edu.umd.cs.findbugs; import java.util.ArrayList; import java.util.List; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantFloat; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; /** * tracks the types and numbers of objects that are currently on the operand stack * throughout the execution of method. To use, a detector should instantiate one for * each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method. * at any point you can then inspect the stack and see what the types of objects are on * the stack, including constant values if they were pushed. The types described are of * course, only the static types. This class is far, far from being done. */ public class OpcodeStack implements Constants2 { private static final boolean DEBUG = Boolean.getBoolean("ocstack.debug"); private List<Item> stack; private List<Item> lvValues; public static class Item { private String signature; private Object constValue; private boolean isNull; public Item(String s) { this(s, null); } public Item(String s, Object v) { signature = s; constValue = v; isNull = false; } public Item() { signature = "Ljava/lang/Object;"; constValue = null; isNull = true; } public JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; if (isPrimitive()) return null; if (isArray()) { baseSig = getElementSignature(); } else { baseSig = signature; } if (baseSig.length() == 0) return null; baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); } public boolean isArray() { return signature.startsWith("["); } public String getElementSignature() { if (!isArray()) return signature; else { int pos = 0; int len = signature.length(); while (pos < len) { if (signature.charAt(pos) != '[') break; pos++; } return signature.substring(pos); } } public boolean isPrimitive() { return !signature.startsWith("L"); } public String getSignature() { return signature; } public boolean isNull() { return isNull; } public Object getConstant() { return constValue; } } public OpcodeStack() { stack = new ArrayList<Item>(); lvValues = new ArrayList<Item>(); } public void sawOpcode(DismantleBytecode dbc, int seen) { int register; JavaClass cls; String signature; Item it, it2, it3; Constant cons; try { switch (seen) { case ALOAD: pushByLocalObjectLoad(dbc, dbc.getRegisterOperand()); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: pushByLocalObjectLoad(dbc, seen - ALOAD_0); break; case DLOAD: pushByLocalLoad("D", dbc.getRegisterOperand()); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: pushByLocalLoad("D", seen - DLOAD_0); break; case FLOAD: pushByLocalLoad("F", dbc.getRegisterOperand()); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: pushByLocalLoad("F", seen - FLOAD_0); break; case ILOAD: pushByLocalLoad("I", dbc.getRegisterOperand()); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: pushByLocalLoad("I", seen - ILOAD_0); break; case LLOAD: pushByLocalLoad("J", dbc.getRegisterOperand()); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: pushByLocalLoad("J", seen - LLOAD_0); break; case GETSTATIC: pushBySignature(dbc.getSigConstantOperand()); break; case LDC: case LDC_W: case LDC2_W: cons = dbc.getConstantRefOperand(); pushByConstant(dbc, cons); break; case INSTANCEOF: pop(); push(new Item("I")); break; case ARETURN: case DRETURN: case FRETURN: case IFEQ: case IFNE: case IFLT: case IFLE: case IFGT: case IFGE: case IFNONNULL: case IFNULL: case IRETURN: case LOOKUPSWITCH: case LRETURN: case MONITORENTER: case MONITOREXIT: case POP: case PUTSTATIC: case TABLESWITCH: pop(); break; case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGT: case IF_ICMPGE: case POP2: case PUTFIELD: pop(2); break; case IALOAD: case SALOAD: pop(2); push(new Item("I")); break; case DUP: it = pop(); push(it); push(it); break; case DUP2: it = pop(); it2 = pop(); push(it2); push(it); push(it2); push(it); break; case DUP_X1: it = pop(); it2 = pop(); push(it); push(it2); push(it); break; case DUP_X2: it = pop(); it2 = pop(); signature = it2.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it); push(it3); push(it2); push(it); } break; case DUP2_X1: it = pop(); it2 = pop(); signature = it.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it2); push(it); push(it3); push(it2); push(it); } break; case ATHROW: case CHECKCAST: case GOTO: case GOTO_W: case IINC: case NOP: case RET: case RETURN: break; case SWAP: Item i1 = pop(); Item i2 = pop(); push(i1); push(i2); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: push(new Item("I", new Integer(seen-ICONST_0))); break; case LCONST_0: case LCONST_1: push(new Item("J", new Long(seen-LCONST_0))); break; case DCONST_0: case DCONST_1: push(new Item("D", new Double(seen-DCONST_0))); break; case FCONST_0: case FCONST_1: case FCONST_2: push(new Item("F", new Float(seen-FCONST_0))); break; case ACONST_NULL: push(new Item()); break; case ASTORE: case DSTORE: case FSTORE: case ISTORE: case LSTORE: pushByLocalStore(dbc.getRegisterOperand()); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: pushByLocalStore(seen - ASTORE_0); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: pushByLocalStore(seen - DSTORE_0); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: pushByLocalStore(seen - FSTORE_0); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: pushByLocalStore(seen - ISTORE_0); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: pushByLocalStore(seen - LSTORE_0); break; case GETFIELD: pop(); push(new Item(dbc.getSigConstantOperand())); break; case ARRAYLENGTH: pop(); push(new Item("I")); break; case BALOAD: case CALOAD: pop(2); push(new Item("I")); break; case DALOAD: pop(2); push(new Item("D")); break; case FALOAD: pop(2); push(new Item("F")); break; case LALOAD: pop(2); push(new Item("J")); break; case AASTORE: case BASTORE: case CASTORE: case DASTORE: case FASTORE: case IASTORE: case LASTORE: case SASTORE: pop(3); break; case BIPUSH: case SIPUSH: push(new Item("I", new Integer((int)dbc.getIntConstant()))); break; case IADD: case ISUB: case IMUL: case IDIV: case IAND: case IOR: case IXOR: case ISHL: case ISHR: case IREM: case IUSHR: it = pop(); it2 = pop(); pushByIntMath(seen, it, it2); break; case INEG: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer(-((Integer)it.getConstant()).intValue()))); } else { push(new Item("I")); } break; case LNEG: it = pop(); if (it.getConstant() != null) { push(new Item("J", new Long(-((Long)it.getConstant()).longValue()))); } else { push(new Item("J")); } break; case DNEG: it = pop(); if (it.getConstant() != null) { push(new Item("D", new Double(-((Double)it.getConstant()).doubleValue()))); } else { push(new Item("D")); } break; case LADD: case LSUB: case LMUL: case LDIV: case LAND: case LOR: case LXOR: case LSHL: case LSHR: case LREM: case LUSHR: it = pop(); it2 = pop(); pushByLongMath(seen, it, it2); break; case LCMP: it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { long l = ((Long)it.getConstant()).longValue(); long l2 = ((Long)it.getConstant()).longValue(); if (l2 < l) push(new Item("I", new Integer(-1))); else if (l2 > l) push(new Item("I", new Integer(1))); else push(new Item("I", new Integer(0))); } else { push(new Item("I")); } break; case FCMPG: case FCMPL: it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { float f = ((Float)it.getConstant()).floatValue(); float f2 = ((Float)it.getConstant()).floatValue(); if (f2 < f) push(new Item("I", new Integer(-1))); else if (f2 > f) push(new Item("I", new Integer(1))); else push(new Item("I", new Integer(0))); } else { push(new Item("I")); } break; case DCMPG: case DCMPL: it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { double d = ((Double)it.getConstant()).doubleValue(); double d2 = ((Double)it.getConstant()).doubleValue(); if (d2 < d) push(new Item("I", new Integer(-1))); else if (d2 > d) push(new Item("I", new Integer(1))); else push(new Item("I", new Integer(0))); } else { push(new Item("I")); } break; case FADD: case FSUB: case FMUL: case FDIV: it = pop(); it2 = pop(); pushByFloatMath(seen, it, it2); break; case DADD: case DSUB: case DMUL: case DDIV: case DREM: it = pop(); it2 = pop(); pushByDoubleMath(seen, it, it2); break; case I2B: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((byte)((Integer)it.getConstant()).intValue())))); } else { push(new Item("I")); } break; case I2C: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((char)((Integer)it.getConstant()).intValue())))); } else { push(new Item("I")); } break; case I2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", new Double((double)((Integer)it.getConstant()).intValue()))); } else { push(new Item("D")); } break; case I2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", new Float((float)((Integer)it.getConstant()).intValue()))); } else { push(new Item("F")); } break; case I2L: it = pop(); if (it.getConstant() != null) { push(new Item("J", new Long((long)((Integer)it.getConstant()).intValue()))); } else { push(new Item("J")); } break; case I2S: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((short)((Integer)it.getConstant()).intValue())))); } else { push(new Item("I")); } break; case D2I: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((Integer)it.getConstant()).intValue()))); } else { push(new Item("I")); } break; case D2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", new Float((float)((Double)it.getConstant()).doubleValue()))); } else { push(new Item("F")); } break; case D2L: it = pop(); if (it.getConstant() != null) { push(new Item("J", new Long((long)((Double)it.getConstant()).doubleValue()))); } else { push(new Item("J")); } break; case L2I: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((Long)it.getConstant()).longValue()))); } else { push(new Item("I")); } break; case L2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", new Double((double)((Long)it.getConstant()).longValue()))); } else { push(new Item("D")); } break; case L2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", new Float((float)((Long)it.getConstant()).longValue()))); } else { push(new Item("F")); } break; case F2I: it = pop(); if (it.getConstant() != null) { push(new Item("I", new Integer((int)((Float)it.getConstant()).floatValue()))); } else { push(new Item("I")); } break; case F2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", new Double((double)((Float)it.getConstant()).floatValue()))); } else { push(new Item("D")); } break; case NEW: pushBySignature(dbc.getClassConstantOperand()); break; case NEWARRAY: pop(); signature = BasicType.getType((byte)dbc.getIntConstant()).getSignature(); pushBySignature(signature); break; case ANEWARRAY: pop(); pushBySignature("L"+dbc.getClassConstantOperand()+";"); break; case MULTIANEWARRAY: int dims = dbc.getIntConstant(); while ((dims pop(); } push(new Item(dbc.getClassConstantOperand())); break; case AALOAD: pop(); it = pop(); pushBySignature(it.getElementSignature()); break; case JSR: push(new Item("")); break; case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEVIRTUAL: pushByInvoke(dbc, seen != INVOKESTATIC); break; default: throw new UnsupportedOperationException("OpCode not supported yet" ); } } catch (Exception e) { //If an error occurs, we clear the stack and locals. one of two things will occur. //Either the client will expect more stack items than really exist, and so they're condition check will fail, //or the stack will resync with the code. But hopefully not false positives stack.clear(); lvValues.clear(); } finally { if (DEBUG) System.out.println(OPCODE_NAMES[seen] + " stack depth: " + getStackDepth()); } } public int getStackDepth() { return stack.size(); } public Item getStackItem(int stackOffset) { int tos = stack.size() - 1; int pos = tos - stackOffset; return stack.get(pos); } private Item pop() { return stack.remove(stack.size()-1); } private void pop(int count) { while ((count pop(); } private void push(Item i) { stack.add(i); } private void pushByConstant(DismantleBytecode dbc, Constant c) { if (c instanceof ConstantInteger) push(new Item("I", new Integer(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantString) { int s = ((ConstantString) c).getStringIndex(); push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s))); } else if (c instanceof ConstantFloat) push(new Item("F", new Float(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantDouble) push(new Item("D", new Double(((ConstantDouble) c).getBytes()))); else if (c instanceof ConstantLong) push(new Item("J", new Long(((ConstantLong) c).getBytes()))); else throw new UnsupportedOperationException("Constant type not expected" ); } private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) { Method m = dbc.getMethod(); LocalVariableTable lvt = m.getLocalVariableTable(); if (lvt != null) { LocalVariable lv = lvt.getLocalVariable(register); if (lv != null) { String signature = lv.getSignature(); pushByLocalLoad(signature, register); return; } } pushBySignature(""); } private void pushByIntMath(int seen, Item it, Item it2) { if ((it.getConstant() != null) && it2.getConstant() != null) { if (seen == IADD) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() + ((Integer)it.getConstant()).intValue()))); else if (seen == ISUB) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() - ((Integer)it.getConstant()).intValue()))); else if (seen == IMUL) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() * ((Integer)it.getConstant()).intValue()))); else if (seen == IDIV) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() / ((Integer)it.getConstant()).intValue()))); else if (seen == IAND) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() & ((Integer)it.getConstant()).intValue()))); else if (seen == IOR) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() | ((Integer)it.getConstant()).intValue()))); else if (seen == IXOR) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() ^ ((Integer)it.getConstant()).intValue()))); else if (seen == ISHL) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() << ((Integer)it.getConstant()).intValue()))); else if (seen == ISHR) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >> ((Integer)it.getConstant()).intValue()))); else if (seen == IREM) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() % ((Integer)it.getConstant()).intValue()))); else if (seen == IUSHR) push(new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >>> ((Integer)it.getConstant()).intValue()))); } else { push(new Item("I")); } } private void pushByLongMath(int seen, Item it, Item it2) { if ((it.getConstant() != null) && it2.getConstant() != null) { if (seen == LADD) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() + ((Long)it.getConstant()).longValue()))); else if (seen == LSUB) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() - ((Long)it.getConstant()).longValue()))); else if (seen == LMUL) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() * ((Long)it.getConstant()).longValue()))); else if (seen == LDIV) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() / ((Long)it.getConstant()).longValue()))); else if (seen == LAND) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() & ((Long)it.getConstant()).longValue()))); else if (seen == LOR) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() | ((Long)it.getConstant()).longValue()))); else if (seen == LXOR) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() ^ ((Long)it.getConstant()).longValue()))); else if (seen == LSHL) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() << ((Long)it.getConstant()).longValue()))); else if (seen == LSHR) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() >> ((Long)it.getConstant()).longValue()))); else if (seen == LREM) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() % ((Long)it.getConstant()).longValue()))); else if (seen == LUSHR) push(new Item("J", new Long(((Long)it2.getConstant()).longValue() >>> ((Long)it.getConstant()).longValue()))); } else { push(new Item("J")); } } private void pushByFloatMath(int seen, Item it, Item it2) { if ((it.getConstant() != null) && it2.getConstant() != null) { if (seen == FADD) push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() + ((Float)it.getConstant()).floatValue()))); else if (seen == FSUB) push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() - ((Float)it.getConstant()).floatValue()))); else if (seen == FMUL) push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() * ((Float)it.getConstant()).floatValue()))); else if (seen == FDIV) push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() / ((Float)it.getConstant()).floatValue()))); } else { push(new Item("F")); } } private void pushByDoubleMath(int seen, Item it, Item it2) { if ((it.getConstant() != null) && it2.getConstant() != null) { if (seen == DADD) push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() + ((Double)it.getConstant()).doubleValue()))); else if (seen == DSUB) push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() - ((Double)it.getConstant()).doubleValue()))); else if (seen == DMUL) push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() * ((Double)it.getConstant()).doubleValue()))); else if (seen == DDIV) push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() / ((Double)it.getConstant()).doubleValue()))); else if (seen == DREM) push(new Item("D")); } else { push(new Item("D")); } } private void pushByInvoke(DismantleBytecode dbc, boolean popThis) { String signature = dbc.getSigConstantOperand(); Type[] argTypes = Type.getArgumentTypes(signature); pop(argTypes.length+(popThis ? 1 : 0)); pushBySignature(Type.getReturnType(signature).getSignature()); } private String getStringFromIndex(DismantleBytecode dbc, int i) { ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i); return name.getBytes(); } private void pushBySignature(String s) { if ("V".equals(s)) return; push(new Item(s, null)); } private void pushByLocalStore(int register) { Item it = pop(); setLVValue( register, it ); } private void pushByLocalLoad(String signature, int register) { Item it = getLVValue(register); if (it == null) push(new Item(signature)); else push(it); } private void setLVValue(int index, Item value ) { int addCount = index - lvValues.size() + 1; while ((addCount lvValues.add(null); lvValues.set(index, value ); } private Item getLVValue(int index) { if (index >= lvValues.size()) return null; return lvValues.get(index); } }
package org.nanopub.extra.server; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.trustyuri.TrustyUriUtils; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.nanopub.Nanopub; import org.nanopub.NanopubUtils; import org.nanopub.extra.index.IndexUtils; import org.nanopub.extra.index.NanopubIndex; import org.openrdf.model.URI; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; public class FetchIndex { public static final int maxParallelRequestsPerServer = 5; private OutputStream out; private RDFFormat format; private boolean writeIndex, writeContent; private boolean running = false; private List<FetchNanopubTask> fetchTasks; private List<ServerInfo> servers; private Map<String,Set<FetchNanopubTask>> serverLoad; private Map<String,NanopubSurfacePattern> serverPatterns; private int nanopubCount; private Listener listener; private HttpClient httpClient; public FetchIndex(String indexUri, OutputStream out, RDFFormat format, boolean writeIndex, boolean writeContent) { this.out = out; this.format = format; this.writeIndex = writeIndex; this.writeContent = writeContent; fetchTasks = new ArrayList<>(); fetchTasks.add(new FetchNanopubTask(indexUri, true)); servers = new ArrayList<>(); serverLoad = new HashMap<>(); serverPatterns = new HashMap<>(); ServerIterator serverIterator = new ServerIterator(); while (serverIterator.hasNext()) { ServerInfo serverInfo = serverIterator.next(); servers.add(serverInfo); serverLoad.put(serverInfo.getPublicUrl(), new HashSet<FetchNanopubTask>()); serverPatterns.put(serverInfo.getPublicUrl(), new NanopubSurfacePattern(serverInfo)); } try { ServerIterator.writeCachedServers(servers); } catch (Exception ex) {} nanopubCount = 0; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) .setConnectionRequestTimeout(100).setSocketTimeout(5000).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(10); connManager.setMaxTotal(1000); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setConnectionManager(connManager).build(); } public void run() { if (running) return; running = true; while (!fetchTasks.isEmpty()) { checkTasks(); } } private void checkTasks() { for (FetchNanopubTask task : new ArrayList<>(fetchTasks)) { if (task.isRunning()) continue; if (task.getLastServerUrl() != null) { serverLoad.get(task.getLastServerUrl()).remove(task); } if (task.getNanopub() == null) { if (task.getTriedServersCount() == servers.size()) { task.resetServers(); } List<ServerInfo> shuffledServers = new ArrayList<>(servers); Collections.shuffle(shuffledServers); for (ServerInfo serverInfo : shuffledServers) { String serverUrl = serverInfo.getPublicUrl(); if (task.hasServerBeenTried(serverUrl)) continue; if (!serverPatterns.get(serverUrl).matchesUri(task.getNanopubUri())) { task.ignoreServer(serverUrl); continue; } int load = serverLoad.get(serverUrl).size(); if (load >= maxParallelRequestsPerServer) { task.ignoreServer(serverUrl); continue; } assignTask(task, serverUrl); break; } } else if (task.isIndex()) { if (fetchTasks.size() < 1000) { try { Nanopub np = task.getNanopub(); if (!IndexUtils.isIndex(np)) { throw new RuntimeException("NOT AN INDEX: " + np.getUri()); } NanopubIndex npi = IndexUtils.castToIndex(np); if (writeIndex) { writeNanopub(npi); } if (writeContent) { for (URI elementUri : npi.getElements()) { fetchTasks.add(new FetchNanopubTask(elementUri.toString(), false)); } } for (URI subIndexUri : npi.getSubIndexes()) { fetchTasks.add(new FetchNanopubTask(subIndexUri.toString(), true)); } if (npi.getAppendedIndex() != null) { fetchTasks.add(new FetchNanopubTask(npi.getAppendedIndex().toString(), true)); } } catch (Exception ex) { throw new RuntimeException(ex); } fetchTasks.remove(task); } } else { try { writeNanopub(task.getNanopub()); } catch (Exception ex) { throw new RuntimeException(ex); } fetchTasks.remove(task); } } } private void writeNanopub(Nanopub np) throws RDFHandlerException { nanopubCount++; if (listener != null && nanopubCount % 100 == 0) { listener.progress(nanopubCount); } NanopubUtils.writeToStream(np, out, format); } public int getNanopubCount() { return nanopubCount; } public void setProgressListener(Listener l) { listener = l; } private void assignTask(final FetchNanopubTask task, final String serverUrl) { task.prepareForTryingServer(serverUrl); serverLoad.get(serverUrl).add(task); Runnable runFetchTask = new Runnable() { @Override public void run() { task.tryServer(serverUrl); } }; Thread thread = new Thread(runFetchTask); thread.start(); } private class FetchNanopubTask { private String npUri; private boolean isIndex; private Nanopub nanopub; private Set<String> servers = new HashSet<>(); private boolean running = false; private String lastServerUrl; public FetchNanopubTask(String npUri, boolean isIndex) { this.npUri = npUri; this.isIndex = isIndex; } public boolean isIndex() { return isIndex; } public Nanopub getNanopub() { return nanopub; } public String getNanopubUri() { return npUri; } public boolean isRunning() { return running; } public boolean hasServerBeenTried(String serverUrl) { return servers.contains(serverUrl); } public void resetServers() { servers.clear(); } public int getTriedServersCount() { return servers.size(); } public String getLastServerUrl() { return lastServerUrl; } public void ignoreServer(String serverUrl) { servers.add(serverUrl); } public void prepareForTryingServer(String serverUrl) { servers.add(serverUrl); lastServerUrl = serverUrl; running = true; } public void tryServer(String serverUrl) { try { nanopub = GetNanopub.get(TrustyUriUtils.getArtifactCode(npUri), serverUrl, httpClient); } catch (Exception ex) { if (listener != null) listener.exceptionHappened(ex); } finally { running = false; } } } public static interface Listener { public void progress(int count); public void exceptionHappened(Exception ex); } }
package com.mapswithme.maps.bookmarks.data; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class Metadata implements Parcelable { // Values must correspond to definitions from feature_meta.hpp. public enum MetadataType { FMD_CUISINE(1), FMD_OPEN_HOURS(2), FMD_PHONE_NUMBER(3), FMD_FAX_NUMBER(4), FMD_STARS(5), FMD_OPERATOR(6), FMD_URL(7), FMD_WEBSITE(8), FMD_INTERNET(9), FMD_ELE(10), FMD_TURN_LANES(11), FMD_TURN_LANES_FORWARD(12), FMD_TURN_LANES_BACKWARD(13), FMD_EMAIL(14), FMD_POSTCODE(15), // TODO: It is hacked in jni and returns full Wikipedia url. Should use separate getter instead. FMD_WIKIPEDIA(16), FMD_MAXSPEED(17), FMD_FLATS(18), FMD_HEIGHT(19), FMD_MIN_HEIGHT(20), FMD_DENOMINATION(21), FMD_BUILDING_LEVELS(22), FMD_SPONSORED_ID(24), FMD_PRICE_RATE(25), FMD_RATING(26), FMD_BANNER_URL(27), FMD_LEVEL(28); private final int mMetaType; MetadataType(int metadataType) { mMetaType = metadataType; } @NonNull public static MetadataType fromInt(@IntRange(from = 1, to = 28) int metaType) { for (MetadataType type : values()) if (type.mMetaType == metaType) return type; throw new IllegalArgumentException("Illegal metaType arg!"); } public int toInt() { return mMetaType; } } private final Map<MetadataType, String> mMetadataMap = new HashMap<>(); /** * Adds metadata with type code and value. Returns false if metaType is wrong or unknown * * @return true, if metadata was added, false otherwise */ boolean addMetadata(int metaType, String metaValue) { final MetadataType type = MetadataType.fromInt(metaType); mMetadataMap.put(type, metaValue); return true; } /** * Adds metadata with type and value. * * @return true, if metadata was added, false otherwise */ public boolean addMetadata(MetadataType type, String value) { mMetadataMap.put(type, value); return true; } @Nullable String getMetadata(MetadataType type) { return mMetadataMap.get(type); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mMetadataMap.size()); for (Map.Entry<MetadataType, String> metaEntry : mMetadataMap.entrySet()) { dest.writeInt(metaEntry.getKey().mMetaType); dest.writeString(metaEntry.getValue()); } } public static Metadata readFromParcel(Parcel source) { final Metadata metadata = new Metadata(); final int size = source.readInt(); for (int i = 0; i < size; i++) metadata.addMetadata(source.readInt(), source.readString()); return metadata; } public static final Creator<Metadata> CREATOR = new Creator<Metadata>() { @Override public Metadata createFromParcel(Parcel source) { return readFromParcel(source); } @Override public Metadata[] newArray(int size) { return new Metadata[size]; } }; }
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.swig.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The Entry class represents one node in a bencoded hierarchy. It works as a * variant type, it can be either a list, a dictionary, an integer * or a string. * * @author gubatron * @author aldenml */ public final class Entry { private final entry e; public Entry(entry e) { this.e = e; } public Entry(String s) { this(new entry(s)); } public Entry(long n) { this(new entry(n)); } public entry getSwig() { return e; } public byte[] bencode() { return Vectors.char_vector2bytes(e.bencode()); } public String string() { return e.string(); } public long integer() { return e.integer(); } public ArrayList<Entry> list() { entry_vector v = e.list().to_vector(); int size = (int) v.size(); ArrayList<Entry> list = new ArrayList<Entry>(size); for (int i = 0; i < size; i++) { list.add(new Entry(v.get(i))); } return list; } public Map<String, Entry> dictionary() { string_entry_map dict = e.dict(); string_vector keys = dict.keys(); int size = (int) keys.size(); Map<String, Entry> map = new HashMap<String, Entry>(size); for (int i = 0; i < size; i++) { String key = keys.get(i); Entry value = new Entry(dict.get(key)); map.put(key, value); } return map; } @Override public String toString() { return e.to_string(); } public static Entry bdecode(byte[] data) { return new Entry(entry.bdecode(Vectors.bytes2char_vector(data))); } public static Entry bdecode(File file) throws IOException { byte[] data = Utils.readFileToByteArray(file); return bdecode(data); } public static Entry fromList(List<?> list) { entry e = new entry(entry.data_type.list_t); entry_list d = e.list(); for (Object v : list) { if (v instanceof String) { d.push_back(new entry((String) v)); } else if (v instanceof Integer) { d.push_back(new entry((Integer) v)); } else if (v instanceof Entry) { d.push_back(((Entry) v).getSwig()); } else if (v instanceof entry) { d.push_back((entry) v); } else if (v instanceof List) { d.push_back(fromList((List<?>) v).getSwig()); } else if (v instanceof Map) { d.push_back(fromMap((Map<?, ?>) v).getSwig()); } else { d.push_back(new entry(v.toString())); } } return new Entry(e); } public static Entry fromMap(Map<?, ?> map) { entry e = new entry(entry.data_type.dictionary_t); string_entry_map d = e.dict(); for (Map.Entry<?, ?> kv : map.entrySet()) { String k = kv.getKey().toString(); Object v = kv.getValue(); if (v instanceof String) { d.set(k, new entry((String) v)); } else if (v instanceof Integer) { d.set(k, new entry((Integer) v)); } else if (v instanceof Entry) { d.set(k, ((Entry) v).getSwig()); } else if (v instanceof entry) { d.set(k, (entry) v); } else if (v instanceof List) { d.set(k, fromList((List<?>) v).getSwig()); } else if (v instanceof Map) { d.set(k, fromMap((Map<?, ?>) v).getSwig()); } else { d.set(k, new entry(v.toString())); } } return new Entry(e); } }
package org.bouncycastle.asn1; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.bouncycastle.util.Arrays; /** * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public abstract class ASN1TaggedObject extends ASN1Primitive implements ASN1TaggedObjectParser { private static final int DECLARED_EXPLICIT = 1; private static final int DECLARED_IMPLICIT = 2; // TODO It will probably be better to track parsing constructed vs primitive instead private static final int PARSED_EXPLICIT = 3; private static final int PARSED_IMPLICIT = 4; final int explicitness; final int tagClass; final int tagNo; final ASN1Encodable obj; public static ASN1TaggedObject getInstance(ASN1TaggedObject obj, boolean explicit) { if (BERTags.CONTEXT_SPECIFIC != obj.getTagClass()) { throw new IllegalStateException("this method only valid for CONTEXT_SPECIFIC tags"); } if (explicit) { return obj.getExplicitBaseTagged(); } throw new IllegalArgumentException("this method not valid for implicitly tagged tagged objects"); } static public ASN1TaggedObject getInstance(Object obj) { if (obj == null || obj instanceof ASN1TaggedObject) { return (ASN1TaggedObject)obj; } // else if (obj instanceof ASN1TaggedObjectParser) else if (obj instanceof ASN1Encodable) { ASN1Primitive primitive = ((ASN1Encodable)obj).toASN1Primitive(); if (primitive instanceof ASN1TaggedObject) { return (ASN1TaggedObject)primitive; } } else if (obj instanceof byte[]) { try { return ASN1TaggedObject.getInstance(fromByteArray((byte[])obj)); } catch (IOException e) { throw new IllegalArgumentException("failed to construct tagged object from byte[]: " + e.getMessage()); } } throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); } /** * Create a tagged object with the style given by the value of explicit. * <p> * If the object implements ASN1Choice the tag style will always be changed * to explicit in accordance with the ASN.1 encoding rules. * </p> * @param explicit true if the object is explicitly tagged. * @param tagNo the tag number for this object. * @param obj the tagged object. */ protected ASN1TaggedObject(boolean explicit, int tagNo, ASN1Encodable obj) { this(explicit, BERTags.CONTEXT_SPECIFIC, tagNo, obj); } protected ASN1TaggedObject(boolean explicit, int tagClass, int tagNo, ASN1Encodable obj) { this(explicit ? DECLARED_EXPLICIT : DECLARED_IMPLICIT, tagClass, tagNo, obj); } ASN1TaggedObject(int explicitness, int tagClass, int tagNo, ASN1Encodable obj) { if (null == obj) { throw new NullPointerException("'obj' cannot be null"); } if (tagClass == BERTags.UNIVERSAL || (tagClass & BERTags.PRIVATE) != tagClass) { throw new IllegalArgumentException("invalid tag class: " + tagClass); } this.explicitness = (obj instanceof ASN1Choice) ? DECLARED_EXPLICIT : explicitness; this.tagClass = tagClass; this.tagNo = tagNo; this.obj = obj; } boolean asn1Equals(ASN1Primitive other) { if (other instanceof ASN1ApplicationSpecific) { return other.equals(this); } if (!(other instanceof ASN1TaggedObject)) { return false; } ASN1TaggedObject that = (ASN1TaggedObject)other; if (this.tagNo != that.tagNo || this.tagClass != that.tagClass) { return false; } if (this.explicitness != that.explicitness) { /* * TODO This seems incorrect for some cases of implicit tags e.g. if one is a * declared-implicit SET and the other a parsed object. */ if (this.isExplicit() != that.isExplicit()) { return false; } } ASN1Primitive p1 = this.obj.toASN1Primitive(); ASN1Primitive p2 = that.obj.toASN1Primitive(); if (p1 == p2) { return true; } if (!this.isExplicit()) { try { byte[] d1 = this.getEncoded(); byte[] d2 = that.getEncoded(); return Arrays.areEqual(d1, d2); } catch (IOException e) { return false; } } return p1.asn1Equals(p2); } public int hashCode() { return (tagClass * 7919) ^ tagNo ^ (isExplicit() ? 0x0F : 0xF0) ^ obj.toASN1Primitive().hashCode(); } public int getTagClass() { return tagClass; } /** * Return the tag number associated with this object. * * @return the tag number. */ public int getTagNo() { return tagNo; } public boolean hasContextTag(int tagNo) { return this.tagClass == BERTags.CONTEXT_SPECIFIC && this.tagNo == tagNo; } public boolean hasTag(int tagClass, int tagNo) { return this.tagClass == tagClass && this.tagNo == tagNo; } /** * return whether or not the object may be explicitly tagged. * <p> * Note: if the object has been read from an input stream, the only * time you can be sure if isExplicit is returning the true state of * affairs is if it returns false. An implicitly tagged object may appear * to be explicitly tagged, so you need to understand the context under * which the reading was done as well, see getObject below. */ public boolean isExplicit() { // TODO New methods like 'isKnownExplicit' etc. to distinguish uncertain cases? switch (explicitness) { case DECLARED_EXPLICIT: case PARSED_EXPLICIT: return true; default: return false; } } /** * Return the contents of this object as a byte[] * * @return the encoded contents of the object. */ // TODO Need this public if/when ASN1ApplicationSpecific extends ASN1TaggedObject byte[] getContents() { try { byte[] baseEncoding = obj.toASN1Primitive().getEncoded(getASN1Encoding()); if (isExplicit()) { return baseEncoding; } ByteArrayInputStream input = new ByteArrayInputStream(baseEncoding); int tag = input.read(); ASN1InputStream.readTagNumber(input, tag); int length = ASN1InputStream.readLength(input, input.available(), false); int remaining = input.available(); // For indefinite form, account for end-of-contents octets int contentsLength = length < 0 ? remaining - 2 : remaining; if (contentsLength < 0) { throw new IllegalStateException(); } byte[] contents = new byte[contentsLength]; System.arraycopy(baseEncoding, baseEncoding.length - remaining, contents, 0, contentsLength); return contents; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Return whatever was following the tag. * <p> * Note: tagged objects are generally context dependent. If you're trying to * extract a tagged object you should be going via the appropriate getInstance * method. * * @deprecated Tagged objects now include the {@link #getTagClass() tag class}. * This method will raise an exception if it is not * {@link BERTags#CONTEXT_SPECIFIC}. Use * {@link #getBaseUniversal(boolean, int)} only after confirming the * expected tag class. */ public ASN1Primitive getObject() { if (BERTags.CONTEXT_SPECIFIC != getTagClass()) { throw new IllegalStateException("this method only valid for CONTEXT_SPECIFIC tags"); } return obj.toASN1Primitive(); } public ASN1TaggedObject getExplicitBaseTagged() { if (!isExplicit()) { throw new IllegalStateException("object implicit - explicit expected."); } return checkedCast(obj.toASN1Primitive()); } public ASN1TaggedObject getImplicitBaseTagged(int baseTagClass, int baseTagNo) { if (baseTagClass == BERTags.UNIVERSAL || (baseTagClass & BERTags.PRIVATE) != baseTagClass) { throw new IllegalArgumentException("invalid base tag class: " + baseTagClass); } switch (explicitness) { case DECLARED_EXPLICIT: throw new IllegalStateException("object explicit - implicit expected."); case DECLARED_IMPLICIT: { ASN1TaggedObject declared = checkedCast(obj.toASN1Primitive()); if (!declared.hasTag(baseTagClass, baseTagNo)) { String expected = ASN1Util.getTagText(tagClass, tagNo); String found = ASN1Util.getTagText(declared); throw new IllegalStateException("Expected " + expected + " tag but found " + found); } return declared; } // Parsed; return a virtual tag (i.e. that couldn't have been present in the encoding) default: return replaceTag(baseTagClass, baseTagNo); } } /** * Note: tagged objects are generally context dependent. Before trying to * extract a tagged object this way, make sure you have checked that both the * {@link #getTagClass() tag class} and {@link #getTagNo() tag number} match * what you are looking for. * * @param declaredExplicit Whether the tagged type for this object was declared * EXPLICIT. * @param tagNo The universal {@link BERTags tag number} of the * expected base object. */ public ASN1Primitive getBaseUniversal(boolean declaredExplicit, int tagNo) { ASN1UniversalType universalType = ASN1UniversalTypes.get(tagNo); if (declaredExplicit) { if (!isExplicit()) { throw new IllegalArgumentException("object implicit - explicit expected."); } // TODO Implement all universal types, then remove this block if (null == universalType) { return obj.toASN1Primitive(); } return universalType.checkedCast(obj.toASN1Primitive()); } if (DECLARED_EXPLICIT == explicitness) { throw new IllegalArgumentException("object explicit - implicit expected."); } // TODO Implement all universal types, then remove this block if (null == universalType) { // Handle implicit objects generically by re-encoding with new tag try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ASN1OutputStream output = ASN1OutputStream.create(buf, getASN1Encoding()); encode(output, true, BERTags.UNIVERSAL, tagNo); output.flushInternal(); byte[] encoding = buf.toByteArray(); return ASN1Primitive.fromByteArray(encoding); } catch (IOException e) { throw new IllegalStateException("failed to re-tag implicit object", e); } } ASN1Primitive primitive = obj.toASN1Primitive(); switch (explicitness) { case PARSED_EXPLICIT: return universalType.fromImplicitConstructed(rebuildConstructed(primitive)); case PARSED_IMPLICIT: { if (primitive instanceof ASN1Sequence) { return universalType.fromImplicitConstructed((ASN1Sequence)primitive); } return universalType.fromImplicitPrimitive((DEROctetString)primitive); } default: return universalType.checkedCast(primitive); } } /** * @deprecated See {@link ASN1TaggedObjectParser#getObjectParser(int, boolean)}. */ public ASN1Encodable getObjectParser(int tag, boolean isExplicit) throws IOException { if (BERTags.CONTEXT_SPECIFIC != getTagClass()) { throw new ASN1Exception("this method only valid for CONTEXT_SPECIFIC tags"); } return parseBaseUniversal(isExplicit, tag); } public ASN1Encodable parseBaseUniversal(boolean declaredExplicit, int baseTagNo) throws IOException { // TODO These method use getInstance that should only work for BERTags.CONTEXT_SPECIFIC switch (baseTagNo) { case BERTags.SET: return ASN1Set.getInstance(this, declaredExplicit).parser(); case BERTags.SEQUENCE: return ASN1Sequence.getInstance(this, declaredExplicit).parser(); case BERTags.OCTET_STRING: return ASN1OctetString.getInstance(this, declaredExplicit).parser(); } return getBaseUniversal(declaredExplicit, baseTagNo); } public final ASN1Primitive getLoadedObject() { return this; } final void encode(ASN1OutputStream out, boolean withTag) throws IOException { encode(out, withTag, getTagClass(), getTagNo()); } abstract void encode(ASN1OutputStream out, boolean withTag, int tagClass, int tagNo) throws IOException; abstract String getASN1Encoding(); abstract ASN1Sequence rebuildConstructed(ASN1Primitive primitive); abstract ASN1TaggedObject replaceTag(int tagClass, int tagNo); ASN1Primitive toDERObject() { return new DERTaggedObject(explicitness, tagClass, tagNo, obj); } ASN1Primitive toDLObject() { return new DLTaggedObject(explicitness, tagClass, tagNo, obj); } public String toString() { return ASN1Util.getTagText(tagClass, tagNo) + obj; } static ASN1Primitive createConstructed(int tagClass, int tagNo, boolean isIL, ASN1EncodableVector contentsElements) { boolean maybeExplicit = (contentsElements.size() == 1); if (isIL) { ASN1TaggedObject taggedObject = maybeExplicit ? new BERTaggedObject(PARSED_EXPLICIT, tagClass, tagNo, contentsElements.get(0)) : new BERTaggedObject(PARSED_IMPLICIT, tagClass, tagNo, BERFactory.createSequence(contentsElements)); switch (tagClass) { case BERTags.APPLICATION: return new BERApplicationSpecific(taggedObject); default: return taggedObject; } } else { ASN1TaggedObject taggedObject = maybeExplicit ? new DLTaggedObject(PARSED_EXPLICIT, tagClass, tagNo, contentsElements.get(0)) : new DLTaggedObject(PARSED_IMPLICIT, tagClass, tagNo, DLFactory.createSequence(contentsElements)); switch (tagClass) { case BERTags.APPLICATION: return new DLApplicationSpecific(taggedObject); default: return taggedObject; } } } static ASN1Primitive createPrimitive(int tagClass, int tagNo, byte[] contentsOctets) { // Note: !CONSTRUCTED => IMPLICIT ASN1TaggedObject taggedObject = new DLTaggedObject(PARSED_IMPLICIT, tagClass, tagNo, new DEROctetString(contentsOctets)); switch (tagClass) { case BERTags.APPLICATION: return new DLApplicationSpecific(taggedObject); default: return taggedObject; } } private static ASN1TaggedObject checkedCast(ASN1Primitive primitive) { if (primitive instanceof ASN1TaggedObject) { return (ASN1TaggedObject)primitive; } throw new IllegalStateException("unexpected object: " + primitive.getClass().getName()); } }
package ${package}; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration("kieServerSecurity") @EnableWebSecurity public class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .csrf().disable() .authorizeRequests()
package xiaren; import com.badlogic.gdx.Files; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; public class Background { private final String backgroundimage; public Background(String imagetoload) { // imagetoload is the file path of the image to load. this.backgroundimage = imagetoload; } public FileHandle loadFIle() { // This method will load a file into memory, so that the // class can read the file's entire contents, bit by bit, as // in assembly language parsing data structures and file formats. FileHandle fhimage = null; try { fhimage = Gdx.files.getFileHandle(this.backgroundimage, Files.FileType.Internal); return fhimage; } catch (GdxRuntimeException e) { System.err.println(e); return fhimage; } } }
package org.narwhal.core; import org.narwhal.annotation.Column; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * <p> * The <code>DatabaseConnection</code> represents connection to the relational database. * This class includes methods for retrieve particular information from the relational databases. * It automatically maps retrieved result set to the particular entity (java class). * DatabaseConnection class also manages all resources like database connection, * prepared statements, result sets etc. * It also provides basic logging using slf4j library for this case. * </p> * * <p> * For using this class properly, all mapped classes have to annotate all fields * that map to the database columns. * * Here's an example how to use the annotation: * * <p><code> * public class Person { * {@literal @}Column("person_id") * private int id; * {@literal @}Column("name) * private String name; * * // get and set methods. * } * </code></p> * * The methods of the <code>DatabaseConnection</code> class use annotations and annotated fields * to retrieve necessary information from database and to invoke set methods through reflection api. * </p> * <p>Here are some examples how DatabaseConnection can be used:</p> * <p><code> * DatabaseConnection connection = new DatabaseConnection(new DatabaseInformation(driver, url, username, password)); * * connection.executeUpdate("UPDATE person SET name = ? WHERE id = ?", name, id); * * Person person = connection.executeQuery("SELECT * FROM person WHERE id = ?", Person.class, id); * </code> * </p> * * @author Miron Aseev * @see DatabaseInformation */ public class DatabaseConnection { /** * The <code>MappedClassInformation</code> class keeps all the information about particular class. * Instance of this class holds data about set methods, constructors and columns name of the database * tables that mapped to the fields of class. * */ private static class MappedClassInformation<T> { private Constructor<T> constructor; private List<Method> methods; private List<String> columns; /** * Initializes a new instance of the MappedClassInformation class. * Instance is specified by the value of the Class<T>. * This constructor tries to retrieve all the necessary information about the class. * * @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc. * @throws NoSuchMethodException If there is no appropriate method to invoke * */ public MappedClassInformation(Class<T> mappedClass) throws NoSuchMethodException { List<Field> annotatedFields = getAnnotatedFields(mappedClass, Column.class); constructor = mappedClass.getConstructor(); methods = getSetMethods(mappedClass, annotatedFields); columns = getColumnsName(annotatedFields); } /** * Returns list of the set methods for corresponding fields of the class. * * @return List of set methods. * */ public List<Method> getMethods() { return methods; } /** * Returns list of the columns that have been retrieved from the annotated fields. * * @return Columns of the database table. * */ public List<String> getColumns() { return columns; } /** * Returns default constructor of the class. * * @return Default constructor of the class. * */ public Constructor<T> getConstructor() { return constructor; } /** * Retrieves columns name of the database table from the annotated fields. * * @param annotatedFields Fields of class that have been annotated by {@literal @}Column annotation. * @return Columns of the database table. * */ private List<String> getColumnsName(List<Field> annotatedFields) { List<String> columns = new ArrayList<String>(); for (Field field : annotatedFields) { columns.add(field.getAnnotation(Column.class).value()); } return columns; } /** * Retrieves all fields of the class that have been annotated by a particular annotation. * * @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc. * @param annotation Annotation which is used as a condition to filter annotated fields of the class. * @return Fields that have been annotated by a particular annotation. * */ private <T, V extends Annotation> List<Field> getAnnotatedFields(Class<T> mappedClass, Class<V> annotation) { Field[] fields = mappedClass.getDeclaredFields(); List<Field> annotatedFields = new ArrayList<Field>(); for (Field field : fields) { if (field.isAnnotationPresent(annotation)) { annotatedFields.add(field); } } return annotatedFields; } /** * Creates and returns name of the set method from string representation of the field. * * @param fieldName String representation of class field. * @return String representation of the set method. * */ private String getSetMethodName(String fieldName) { char[] fieldNameArray = fieldName.toCharArray(); fieldNameArray[0] = Character.toUpperCase(fieldNameArray[0]); return "set" + new String(fieldNameArray); } /** * Returns all set methods from the class. This method uses list of fields * which is used for retrieving set methods from the class. * * @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc. * @param fields Fields of the class that. * @return Set methods of the class. * @throws NoSuchMethodException If there is no appropriate method to invoke. * */ private <T> List<Method> getSetMethods(Class<T> mappedClass, List<Field> fields) throws NoSuchMethodException { List<Method> methods = new ArrayList<Method>(); for (Field field : fields) { String methodName = getSetMethodName(field.getName()); Method method = mappedClass.getMethod(methodName, field.getType()); methods.add(method); } return methods; } } /** * The <code>Cache</code> class is an implementation of the thread-safe cache that * keeps pair of mapped class and mapped class information correspondingly. * Actually, this cache is an implementation of the thread safe hash map. * */ private static class Cache { private ReadWriteLock lock; private Lock readLock; private Lock writeLock; private Map<Class, MappedClassInformation> entityCache; /** * Initializes a new instance of the Cache class. * */ public Cache() { lock = new ReentrantReadWriteLock(); readLock = lock.readLock(); writeLock = lock.writeLock(); entityCache = new HashMap<Class, MappedClassInformation>(); } /** * Tests whether cache contains a particular key or not. * * @param key Key whose presence in this map is to be tested * @return True if cache contains the key. False otherwise. * */ public boolean containsKey(Object key) { readLock.lock(); try { return entityCache.containsKey(key); } finally { readLock.unlock(); } } /** * Associates the specified value with the specified key in the map If the map already * contained the key in the map then the associated is replaced by new value. * * @param mappedClass The value of Class that uses as a key in the map. * @param classInformation The instance of MappedClassInformation that uses as value in the map. * @return The value of MappedClassInformation that was associated with a particular key. * */ public MappedClassInformation put(Class mappedClass, MappedClassInformation classInformation) { writeLock.lock(); try { return entityCache.put(mappedClass, classInformation); } finally { writeLock.unlock(); } } /** * Returns the value to which the specified key is mapped. * * @param key Key whose presence in this map is to be tested * @return Instance of the MappedClassInformation if the key is presence in the map. Null otherwise. * */ public MappedClassInformation get(Object key) { readLock.lock(); try { return entityCache.get(key); } finally { readLock.unlock(); } } } private static Logger logger = LoggerFactory.getLogger(DatabaseConnection.class); private static Cache cache = new Cache(); private Connection connection; /** * Initializes a new instance of the DatabaseConnection class and trying to connect to the database. * Instance is specified by the value of DatabaseInformation class that keeps all the information needed to connect. * * @param databaseInformation instance of {@code DatabaseInformation} class that includes * all the information for making connection to the database. * @throws SQLException If any database access problems happened. * @throws ClassNotFoundException If any problem with register JDBC driver occurs. * */ public DatabaseConnection(DatabaseInformation databaseInformation) throws ClassNotFoundException, SQLException { connection = getConnection(databaseInformation); } public int persist(Object object) { } public int remove(Object object) { } public <T> T find(Class<T> mappedClass, Object column) { } /** * Builds and executes update SQL query. This method returns the number of rows that have been affected. * * Here is an example of usage: * <p> * <code> * connection.executeUpdate("DELETE FROM person WHERE id = ? AND name = ?", id, name); * </code> * </p> * * As you could see in the example above, this method takes the string representation of SQL update query * and the arbitrary number of parameters. * This method combines two parameters, so let's assume that <code>id </code> variable is assigned to 1 * and <code>name</code> variable is assigned to "John". * * Then you'll get the following SQL query: * * <p> * <code> * "DELETE FROM person WHERE id = 1 AND name = 'John'" * </code> * </p> * * @param query SQL update query (UPDATE, DELETE, INSERT) that can include wildcard symbol - "?". * @param parameters Arbitrary number of parameters that will be used to substitute wildcard * symbols in the SQL query parameter. * @return Number of rows that have been affected. * @throws SQLException If any database access error happened * */ public int executeUpdate(String query, Object... parameters) throws SQLException { PreparedStatement preparedStatement = null; int result = 0; try { try { preparedStatement = createPreparedStatement(query, parameters); result = preparedStatement.executeUpdate(); } finally { close(preparedStatement); } } catch (SQLException ex) { logger.error("Database access error has occurred", ex); close(); } return result; } public <T> T executeQuery(String query, Class<T> mappedClass, Object... parameters) throws SQLException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { PreparedStatement preparedStatement = null; ResultSet resultSet = null; T result = null; try { try { preparedStatement = createPreparedStatement(query, parameters); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { result = createEntity(resultSet, mappedClass); } } finally { close(resultSet); close(preparedStatement); } } catch (SQLException ex) { logger.error("Database access error has occurred", ex); close(); } return result; } public <T> List<T> executeQueryForCollection(String query, Class<T> mappedClass, Object... parameters) throws SQLException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { PreparedStatement preparedStatement = null; ResultSet resultSet = null; List<T> collection = new ArrayList<T>(); try { try { preparedStatement = createPreparedStatement(query, parameters); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { collection.add(createEntity(resultSet, mappedClass)); } } finally { close(resultSet); close(preparedStatement); } } catch (SQLException ex) { logger.error("Database access error has occurred", ex); close(); } return collection; } /** * Makes connection to the database. * * @param databaseInformation Instance of the DatabaseInformation class that keeps all the information * about database connection like database driver's name, url, username and password. * @throws SQLException If any database access problems happened. * @throws ClassNotFoundException If any problem with register JDBC driver occurs. * */ public void connect(DatabaseInformation databaseInformation) throws SQLException, ClassNotFoundException { connection = getConnection(databaseInformation); } /** * Closes database connection. * * @throws SQLException If any database access problems happened. * */ public void close() throws SQLException { connection.close(); logger.info("Database connection has been closed"); } /** * Tests whether database connection is closed or not. * * @return true if database connection is closed. false otherwise * @throws SQLException If any database access problems happened. * */ public boolean isClosed() throws SQLException { return connection.isClosed(); } /** * Returns raw connection object. * * @return Connection object corresponding to the DatabaseConnection object. * */ public Connection getRawConnection() { return connection; } /** * Builds prepared statement. This method takes the string representation of SQL query and the arbitrary * number of wildcard parameters. * This method substitutes every wildcard symbol in the SQL query on the corresponding wildcard * parameter that was placed like the second and subsequent argument after SQL query. * * Here's how it works: * In the example below, there are two wildcard symbols and two wildcard parameters. * * <code> * createPreparedStatement("SELECT * FROM person WHERE id = ? AND name = ?", 1, "John"); * </code> * * The query above will be converted to the following representation: * <code> * "SELECT * FROM person WHERE id = 1 AND name = 'John'" * </code> * * @param query SQL query that can keep wildcard symbols. * @param parameters Arbitrary number of parameters that will be used * to substitute the wildcard symbols in the SQL query. * @return object of the PreparedStatement class. * @throws SQLException If any database access problems happened. * */ private PreparedStatement createPreparedStatement(String query, Object... parameters) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(query); for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) { preparedStatement.setObject(parameterIndex + 1, parameters[parameterIndex]); } return preparedStatement; } /** * Closes result set object * * @throws SQLException If any database access problems happened. * */ private void close(ResultSet resultSet) throws SQLException { if (resultSet != null) { resultSet.close(); } } /** * Closes prepared statement object * * @throws SQLException If any database access problems happened. * */ private void close(Statement statement) throws SQLException { if (statement != null) { statement.close(); } } /** * Registers JDBC driver and trying to connect to the database. * * @param databaseInformation Instance of the DatabaseInformation class that keeps all the information * about database connection like database driver's name, url, username and password. * @return A new Connection object associated with particular database. * @throws SQLException If any database access problems happened. * @throws ClassNotFoundException If any problem with register JDBC driver occurs. * */ private Connection getConnection(DatabaseInformation databaseInformation) throws ClassNotFoundException, SQLException { String url = databaseInformation.getUrl(); String username = databaseInformation.getUsername(); String password = databaseInformation.getPassword(); Class.forName(databaseInformation.getDriver()); connection = DriverManager.getConnection(url, username, password); logger.info("Database connection has been opened"); return connection; } @SuppressWarnings("unchecked") private <T> T createEntity(ResultSet resultSet, Class<T> mappedClass) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { T result; if (cache.containsKey(mappedClass)) { MappedClassInformation<T> classInformation = cache.get(mappedClass); result = createEntitySupporter(resultSet, classInformation); } else { MappedClassInformation<T> classInformation = new MappedClassInformation<T>(mappedClass); cache.put(mappedClass, classInformation); result = createEntitySupporter(resultSet, classInformation); } return result; } private <T> T createEntitySupporter(ResultSet resultSet, MappedClassInformation<T> classInformation) throws IllegalAccessException, InvocationTargetException, InstantiationException, SQLException { List<Method> methods = classInformation.getMethods(); List<String> columns = classInformation.getColumns(); T result = classInformation.getConstructor().newInstance(); for (int i = 0; i < columns.size(); ++i) { Object data = resultSet.getObject(columns.get(i)); methods.get(i).invoke(result, data); } return result; } }
package com.mapswithme.util.statistics; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.provider.Settings.Secure; import android.util.Log; import com.flurry.android.FlurryAgent; import com.mapswithme.maps.BuildConfig; import com.mapswithme.maps.R; import com.mapswithme.util.Utils; public class FlurryEngine extends StatisticsEngine { private boolean mDebug = false; private final String mKey; public FlurryEngine(boolean isDebug, String key) { mKey = key; mDebug = isDebug; } @Override public void configure(Context context, Bundle params) { FlurryAgent.setUserId(Secure.ANDROID_ID); FlurryAgent.setLogLevel(mDebug ? Log.DEBUG : Log.ERROR); FlurryAgent.setVersionName(BuildConfig.VERSION_NAME); FlurryAgent.init(context, context.getString(R.string.flurry_app_key)); } @Override public void onStartActivity(Activity activity) { Utils.checkNotNull(mKey); Utils.checkNotNull(activity); FlurryAgent.onStartSession(activity); } @Override public void onEndActivity(Activity activity) { FlurryAgent.onEndSession(activity); } @Override public void postEvent(Event event) { Utils.checkNotNull(event); if (event.hasParams()) FlurryAgent.logEvent(event.getName(), event.getParams()); else FlurryAgent.logEvent(event.getName()); } }
package com.fsck.k9; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.PowerManager; import android.os.Process; import android.os.PowerManager.WakeLock; import android.text.TextUtils; import android.util.Log; import com.fsck.k9.activity.FolderList; import com.fsck.k9.activity.MessageList; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessageRemovalListener; import com.fsck.k9.mail.MessageRetrievalListener; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.LocalStore.PendingCommand; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { private static final int MAX_SMALL_MESSAGE_SIZE = Store.FETCH_BODY_SANE_SUGGESTED_SIZE; private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk"; private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash"; private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk"; private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag"; private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append"; private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead"; private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge"; private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>(); private Thread mThread; private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>(); private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>(); private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>(); ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>(); private final ExecutorService threadPool = Executors.newFixedThreadPool(5); public enum SORT_TYPE { SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true), SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true), SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true), SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true), SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true); private int ascendingToast; private int descendingToast; private boolean defaultAscending; SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) { ascendingToast = ascending; descendingToast = descending; defaultAscending = ndefaultAscending; } public int getToast(boolean ascending) { if (ascending) { return ascendingToast; } else { return descendingToast; } } public boolean isDefaultAscending() { return defaultAscending; } }; private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private MessagingListener checkMailListener = null; private MemorizingListener memorizingListener = new MemorizingListener(); private boolean mBusy; private Application mApplication; // Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>(); // Key is accountUuid:folderName , value is a long of the highest message UID ever emptied from Trash private ConcurrentHashMap<String, Long> expungedUid = new ConcurrentHashMap<String, Long>(); private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid()); } private String createMessageKey(Account account, String folder, String uid) { return account.getUuid() + ":" + folder + ":" + uid; } private String createFolderKey(Account account, String folder) { return account.getUuid() + ":" + folder; } private void suppressMessage(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return; } String messKey = createMessageKey(account, folder, message); deletedUids.put(messKey, "true"); } private void unsuppressMessage(Account account, String folder, String uid) { if (account == null || folder == null || uid == null) { return; } String messKey = createMessageKey(account, folder, uid); deletedUids.remove(messKey); } private boolean isMessageSuppressed(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return false; } String messKey = createMessageKey(account, folder, message); if (deletedUids.containsKey(messKey)) { return true; } Long expungedUidL = expungedUid.get(createFolderKey(account, folder)); if (expungedUidL != null) { long expungedUid = expungedUidL; String messageUidS = message.getUid(); try { long messageUid = Long.parseLong(messageUidS); if (messageUid <= expungedUid) { return false; } } catch (NumberFormatException nfe) { // Nothing to do } } return false; } private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.start(); if (memorizingListener != null) { addListener(memorizingListener); } } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application * @return */ public synchronized static MessagingController getInstance(Application application) { if (inst == null) { inst = new MessagingController(application); } return inst; } public boolean isBusy() { return mBusy; } public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { String commandDescription = null; try { Command command = mCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; command.runnable.run(); if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners()) { l.controllerCommandCompleted(mCommands.size() > 0); } if (command.listener != null && !getListeners().contains(command.listener)) { command.listener.controllerCommandCompleted(mCommands.size() > 0); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; while (retries { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; command.isForeground = isForeground; queue.put(command); return; } catch (InterruptedException ie) { try { Thread.sleep(200); } catch (InterruptedException ne) { } e = ie; } } throw new Error(e); } public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } public void refreshListener(MessagingListener listener) { if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } public void removeListener(MessagingListener listener) { mListeners.remove(listener); } public Set<MessagingListener> getListeners() { return mListeners; } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * TODO this needs to cache the remote folder list * * @param account * @param includeRemote * @param listener * @throws MessagingException */ public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { for (MessagingListener l : getListeners()) { l.listFoldersStarted(account); } if (listener != null) { listener.listFoldersStarted(account); } List<? extends Folder> localFolders = null; try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(); Folder[] folderArray = localFolders.toArray(new Folder[0]); if (refreshRemote || localFolders == null || localFolders.size() == 0) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners()) { l.listFolders(account, folderArray); } if (listener != null) { listener.listFolders(account, folderArray); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.listFoldersFailed(account, e.getMessage()); } if (listener != null) { listener.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } for (MessagingListener l : getListeners()) { l.listFoldersFinished(account); } if (listener != null) { listener.listFoldersFinished(account); } } }); } private void doRefreshRemote(final Account account, MessagingListener listener) { put("doRefreshRemote", listener, new Runnable() { public void run() { List<? extends Folder> localFolders = null; try { Store store = account.getRemoteStore(); List<? extends Folder> remoteFolders = store.getPersonalNamespaces(); LocalStore localStore = account.getLocalStore(); HashSet<String> remoteFolderNames = new HashSet<String>(); for (int i = 0, count = remoteFolders.size(); i < count; i++) { LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName()); if (!localFolder.exists()) { localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount()); } remoteFolderNames.add(remoteFolders.get(i).getName()); } localFolders = localStore.getPersonalNamespaces(); /* * Clear out any folders that are no longer on the remote store. */ for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); if (localFolderName.equalsIgnoreCase(K9.INBOX) || localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName())) { continue; } if (!remoteFolderNames.contains(localFolder.getName())) { localFolder.delete(false); } } localFolders = localStore.getPersonalNamespaces(); Folder[] folderArray = localFolders.toArray(new Folder[0]); for (MessagingListener l : getListeners()) { l.listFolders(account, folderArray); } for (MessagingListener l : getListeners()) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } } }); } /** * List the messages in the local message store for the given folder asynchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { listLocalMessagesSynchronous(account, folder, listener); } }); } /** * List the messages in the local message store for the given folder synchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener) { for (MessagingListener l : getListeners()) { l.listLocalMessagesStarted(account, folder); } if (listener != null && getListeners().contains(listener) == false) { listener.listLocalMessagesStarted(account, folder); } Folder localFolder = null; MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { List<Message> pendingMessages = new ArrayList<Message>(); int totalDone = 0; public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { if (isMessageSuppressed(account, folder, message) == false) { pendingMessages.add(message); totalDone++; if (pendingMessages.size() > 10) { addPendingMessages(); } } else { for (MessagingListener l : getListeners()) { l.listLocalMessagesRemoveMessage(account, folder, message); } if (listener != null && getListeners().contains(listener) == false) { listener.listLocalMessagesRemoveMessage(account, folder, message); } } } public void messagesFinished(int number) { addPendingMessages(); } private void addPendingMessages() { for (MessagingListener l : getListeners()) { l.listLocalMessagesAddMessages(account, folder, pendingMessages); } if (listener != null && getListeners().contains(listener) == false) { listener.listLocalMessagesAddMessages(account, folder, pendingMessages); } pendingMessages.clear(); } }; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); localFolder.getMessages( retrievalListener, false // Skip deleted messages ); if (K9.DEBUG) Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished"); for (MessagingListener l : getListeners()) { l.listLocalMessagesFinished(account, folder); } if (listener != null && getListeners().contains(listener) == false) { listener.listLocalMessagesFinished(account, folder); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.listLocalMessagesFailed(account, folder, e.getMessage()); } if (listener != null && getListeners().contains(listener) == false) { listener.listLocalMessagesFailed(account, folder, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener) { searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages, searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener); } /** * Find all messages in any local account which match the query 'query' * @param folderNames TODO * @param query * @param listener * @param searchAccounts TODO * @param account TODO * @param account * @throws MessagingException */ public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { if (K9.DEBUG) { Log.i(K9.LOG_TAG, "searchLocalMessages (" + "accountUuids=" + Utility.combine(accountUuids, ',') + ", folderNames = " + Utility.combine(folderNames, ',') + ", messages.size() = " + (messages != null ? messages.length : null) + ", query = " + query + ", integrate = " + integrate + ", requiredFlags = " + Utility.combine(requiredFlags, ',') + ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',') + ")"); } threadPool.execute(new Runnable() { public void run() { final AccountStats stats = new AccountStats(); final Set<String> accountUuidsSet = new HashSet<String>(); if (accountUuids != null) { for (String accountUuid : accountUuids) { accountUuidsSet.add(accountUuid); } } final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); Account[] accounts = prefs.getAccounts(); List<LocalFolder> foldersToSearch = null; boolean displayableOnly = false; boolean noSpecialFolders = true; for (final Account account : accounts) { if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false) { continue; } if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true) { displayableOnly = true; noSpecialFolders = true; } else if (integrate == false && folderNames == null) { Account.Searchable searchableFolders = account.getSearchableFolders(); switch (searchableFolders) { case NONE: continue; case DISPLAYABLE: displayableOnly = true; break; } } List<Message> messagesToSearch = null; if (messages != null) { messagesToSearch = new LinkedList<Message>(); for (Message message : messages) { if (message.getFolder().getAccount().getUuid().equals(account.getUuid())) { messagesToSearch.add(message); } } if (messagesToSearch.isEmpty()) { continue; } } if (listener != null) { listener.listLocalMessagesStarted(account, null); } if (integrate || displayableOnly || folderNames != null || noSpecialFolders) { List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>(); try { LocalStore store = account.getLocalStore(); List<? extends Folder> folders = store.getPersonalNamespaces(); Set<String> folderNameSet = null; if (folderNames != null) { folderNameSet = new HashSet<String>(); for (String folderName : folderNames) { folderNameSet.add(folderName); } } for (Folder folder : folders) { LocalFolder localFolder = (LocalFolder)folder; boolean include = true; folder.refresh(prefs); String localFolderName = localFolder.getName(); if (integrate) { include = localFolder.isIntegrate(); } else { if (folderNameSet != null) { if (folderNameSet.contains(localFolderName) == false) { include = false; } } else if (noSpecialFolders && ( localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName()))) { include = false; } else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass())) { include = false; } } if (include) { tmpFoldersToSearch.add(localFolder); } } if (tmpFoldersToSearch.size() < 1) { continue; } foldersToSearch = tmpFoldersToSearch; } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me); addErrorMessage(account, null, me); } } MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { List<Message> messages = new ArrayList<Message>(); messages.add(message); stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } public void messagesFinished(int number) { } }; try { LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, query, foldersToSearch, messagesToSearch == null ? null : messagesToSearch.toArray(new Message[0]), requiredFlags, forbiddenFlags); } catch (Exception e) { if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } if (listener != null) { listener.searchStats(stats); } } }); } public void loadMoreMessages(Account account, String folder, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); synchronizeMailbox(account, folder, listener); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } public void resetVisibleLimits(Account[] accounts) { for (Account account : accounts) { try { LocalStore localStore = account.getLocalStore(); localStore.resetVisibleLimits(account.getDisplayCount()); } catch (MessagingException e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); } } } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener */ public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener) { putBackground("synchronizeMailbox", listener, new Runnable() { public void run() { synchronizeMailboxSynchronous(account, folder, listener); } }); } /** * Start foreground synchronization of the specified folder. This is generally only called * by synchronizeMailbox. * @param account * @param folder * * TODO Break this method up into smaller chunks. */ public void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; /* * We don't ever sync the Outbox or errors folder */ if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { return; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); for (MessagingListener l : getListeners()) { l.synchronizeMailboxStarted(account, folder); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxStarted(account, folder); } Exception commandException = null; try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); commandException = e; } /* * Get the message list from the local store and create an index of * the uids within the list. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); final LocalFolder localFolder = tLocalFolder; localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); HashMap<String, Message> localUidMap = new HashMap<String, Message>(); for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote store for " + folder); Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || folder.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); return; } } } /* * Synchronization process: Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); } /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); Message[] remoteMessageArray = new Message[0]; final ArrayList<Message> remoteMessages = new ArrayList<Message>(); // final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message thisMess : remoteMessageArray) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store. */ for (Message localMessage : localMessages) { if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED)) { localMessage.setFlag(Flag.X_DESTROYED, true); for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } } localMessages = null; /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages); setLocalFlaggedCountToRemote(localFolder, remoteFolder); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } /* * Notify listeners that we're finally done. */ localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, folder, rootMessage); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxFailed(account, folder, rootMessage); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, folder, rootMessage); } if (listener != null && getListeners().contains(listener) == false) { listener.synchronizeMailboxFailed( account, folder, rootMessage); } addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); } finally { if (remoteFolder != null) { remoteFolder.close(); } if (tLocalFolder != null) { tLocalFolder.close(); } } } private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException { int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); if (remoteUnreadMessageCount != -1) { localFolder.setUnreadMessageCount(remoteUnreadMessageCount); } else { int unreadCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false) { unreadCount++; } } localFolder.setUnreadMessageCount(unreadCount); } return localFolder.getUnreadMessageCount(); } private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException { int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount(); if (remoteFlaggedMessageCount != -1) { localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount); } else { int flaggedCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false) { flaggedCount++; } } localFolder.setFlaggedMessageCount(flaggedCount); } } private int downloadMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException { final String folder = remoteFolder.getName(); ArrayList<Message> syncFlagMessages = new ArrayList<Message>(); List<Message> unsyncedMessages = new ArrayList<Message>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Message> messages = new ArrayList<Message>(inputMessages); for (Message message : messages) { if (isMessageSuppressed(account, folder, message) == false) { Message localMessage = localFolder.getMessage(message.getUid()); if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded at all"); unsyncedMessages.add(message); } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } } else if (localMessage.isSet(Flag.DELETED) == false) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is already locally present"); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); } } } } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); messages.clear(); final ArrayList<Message> largeMessages = new ArrayList<Message>(); final ArrayList<Message> smallMessages = new ArrayList<Message>(); if (unsyncedMessages.size() > 0) { /* * Reverse the order of the messages. Depending on the server this may get us * fetch results for newest to oldest. If not, no harm done. */ Collections.reverse(unsyncedMessages); int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if (listSize > visibleLimit) { unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize); } FetchProfile fp = new FetchProfile(); if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync " + unsyncedMessages.size() + " unsynced messages for folder " + folder); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } if (message.isSet(Flag.DELETED)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was already deleted on server, skipping"); return; } // Store the new message locally localFolder.appendMessages(new Message[] { message }); if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } // And include it in the view if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ if (isMessageSuppressed(account, folder, message) == false) { Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } // Send a notification of this message if (notifyAccount(mApplication, account, message) == true) { newMessages.incrementAndGet(); } } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and " + smallMessages.size() + " small messages out of " + unsyncedMessages.size() + " unsynced messages"); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has now be fully downloaded localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " + account + ":" + folder + ":" + message.getUid()); progress.incrementAndGet(); // Update the listener with what we've found for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } notifyAccount(mApplication, account, message); } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. */ if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found progress.incrementAndGet(); for (MessagingListener l : getListeners()) { Message localMessage = localFolder.getMessage(message.getUid()); l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } notifyAccount(mApplication, account, message); }//for large messsages if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); largeMessages.clear(); /* * Refresh the flags for any messages in the local store that we didn't just * download. */ if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); fp.clear(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(syncFlagMessages.toArray(new Message[0]), fp, null); for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); if (messageChanged) { if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } else { for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); localFolder.purgeToVisibleLimit(new MessageRemovalListener() { public void messageRemoved(Message message) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } }); return newMessages.get(); } private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED }) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } return messageChanged; } private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; do { nextCause = rootCause.getCause(); if (nextCause != null) { rootCause = nextCause; } } while (nextCause != null); return rootCause.getMessage(); } private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } private void processPendingCommands(final Account account) { putBackground("processPendingCommands", null, new Runnable() { public void run() { try { processPendingCommandsSynchronous(account); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList<PendingCommand> commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); if (todo == 0) { return; } for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; try { for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* * We specifically do not catch any exceptions here. If a command fails it is * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ try { if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopy(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); } else { throw me; } } finally { progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; } finally { for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. Once the local message is successfully processed it is deleted so * that the server message will be synchronized down without an additional copy being * created. * TODO update the local message UID instead of deleteing it * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; try { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid); if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } /* * If the message does not exist remotely we just upload it and then * update our local copy with the new uid. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage } , fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } } else { /* * If the remote message exists we need to determine which copy to keep. */ /* * See if the remote message is newer than ours. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.setFlag(Flag.X_DESTROYED, true); } else { /* * Otherwise we'll upload our message and then delete the remote message. */ fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage }, fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); } /** * Process a pending trash message command. * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; try { String srcFolder = command.arguments[0]; if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; String isCopyS = command.arguments[2]; Store remoteStore = account.getRemoteStore(); remoteSrcFolder = remoteStore.getFolder(srcFolder); List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName); } else { remoteDestFolder = remoteStore.getFolder(destFolder); if (isCopy) { remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder); } else { remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder); } } if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } } finally { if (remoteSrcFolder != null) { remoteSrcFolder.close(); } if (remoteDestFolder != null) { remoteDestFolder.close(); } } } private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = folderName; command.arguments[1] = newState; command.arguments[2] = flag; for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); processPendingCommands(account); } }); } /** * Processes a pending mark read or unread command. * * @param command arguments = (String folder, String uid, boolean read) * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } boolean newState = Boolean.parseBoolean(command.arguments[1]); Flag flag = Flag.valueOf(command.arguments[2]); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } if (messages.size() == 0) { return; } remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid); boolean newState = Boolean.parseBoolean(command.arguments[2]); Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } private void queueExpunge(final Account account, final String folderName) { putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; command.arguments = new String[1]; command.arguments[0] = folderName; queuePendingCommand(account, command); processPendingCommands(account); } }); } private void processPendingExpunge(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (account.getErrorFolderName().equals(srcFolder)) { return; } Store remoteStore = account.getRemoteStore(); Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); remoteMessage.delete(account.getTrashFolderName()); remoteSrcFolder.close(); return; } remoteDestFolder.open(OpenMode.READ_WRITE); if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false) { message.setFlag(Flag.SEEN, true); for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } localFolder.setUnreadMessageCount(0); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); } finally { if (localFolder != null) { localFolder.close(); } if (remoteFolder != null) { remoteFolder.close(); } } } static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); public void addErrorMessage(Account account, String subject, Throwable t) { if (K9.ENABLE_ERROR_FOLDER == false) { return; } if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (t == null) { return; } String rootCauseMessage = getRootCauseMessage(t); Log.e(K9.LOG_TAG, "Error " + "'" + rootCauseMessage + "'", t); Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); message.setBody(new TextBody(baos.toString())); message.setFlag(Flag.X_DOWNLOADED_FULL, true); if (subject != null) { message.setSubject(subject); } else { message.setSubject(rootCauseMessage); } long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000)); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, localFolder.getName(), localFolder.getUnreadMessageCount()); } } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void addErrorMessage(Account account, String subject, String body) { if (K9.ENABLE_ERROR_FOLDER == false) { return; } if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (body == null || body.length() < 1) { return; } Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(body)); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setSubject(subject); long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); List<String> args = new ArrayList<String>(); args.add(folder); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MARK_ALL_AS_READ; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } public void setFlag( final Message[] messages, final Flag flag, final boolean newState) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { String[] uids = new String[messages.size()]; for (int i = 0; i < messages.size(); i++) { uids[i] = messages.get(i).getUid(); } setFlag(account, folder.getName(), uids, flag, newState); } }); } public void setFlag( final Account account, final String folderName, final String[] uids, final Flag flag, final boolean newState) { // TODO: put this into the background, but right now that causes odd behavior // because the FolderMessageList doesn't have its own cache of the flag states Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); ArrayList<Message> messages = new ArrayList<Message>(); for (int i = 0; i < uids.length; i++) { String uid = uids[i]; // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && newState == false && uid != null && account.getOutboxFolderName().equals(folderName)) { sendCount.remove(uid); } Message msg = localFolder.getMessage(uid); if (msg != null) { messages.add(msg); } } localFolder.setFlags(messages.toArray(new Message[0]), new Flag[] {flag}, newState); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } if (account.getErrorFolderName().equals(folderName)) { return; } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { if (localFolder != null) { localFolder.close(); } } }//setMesssageFlag public void clearAllPending(final Account account) { try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } private void loadMessageForViewRemote(final Account account, final String folder, final String uid, final MessagingListener listener) { put("loadMessageForViewRemote", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); } else { /* * At this point the message is not available, so we need to download it * fully if possible. */ Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); remoteFolder.open(OpenMode.READ_WRITE); // Get the remote message and fully download it Message remoteMessage = remoteFolder.getMessage(uid); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // Store the message locally and load the stored message into memory localFolder.appendMessages(new Message[] { remoteMessage }); message = localFolder.getMessage(uid); localFolder.fetch(new Message[] { message }, fp, null); // Mark that this message is now fully synched message.setFlag(Flag.X_DOWNLOADED_FULL, true); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners()) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewFinished(account, folder, uid, message); } for (MessagingListener l : getListeners()) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.loadMessageForViewFailed(account, folder, uid, e); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } finally { if (remoteFolder!=null) { remoteFolder.close(); } if (localFolder!=null) { localFolder.close(); } }//finally }//run }); } public void loadMessageForView(final Account account, final String folder, final String uid, final MessagingListener listener) { for (MessagingListener l : getListeners()) { l.loadMessageForViewStarted(account, folder, uid); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewStarted(account, folder, uid); } threadPool.execute(new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = (LocalMessage)localFolder.getMessage(uid); if (message==null || message.getId()==0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlag(new Message[] { message }, Flag.SEEN, true); } for (MessagingListener l : getListeners()) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewHeadersAvailable(account, folder, uid, message); } if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { loadMessageForViewRemote(account, folder, uid, listener); if (!message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { localFolder.close(); return; } } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); for (MessagingListener l : getListeners()) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners()) { l.loadMessageForViewFinished(account, folder, uid, message); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.loadMessageForViewFailed(account, folder, uid, e); } if (listener != null && !getListeners().contains(listener)) { listener.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } } }); } /** * Attempts to load the attachment specified by part from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment( final Account account, final Message message, final Part part, final Object tag, final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ try { if (part.getBody() != null) { for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, false); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } return; } } catch (MessagingException me) { /* * If the header isn't there the attachment isn't downloaded yet, so just continue * on. */ } for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, true); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } put("loadAttachment", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); /* * We clear out any attachments already cached in the entire store and then * we update the passed in message to reflect that there are no cached * attachments. This is in support of limiting the account to having one * attachment downloaded at a time. */ localStore.pruneCachedAttachments(); ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); localFolder = localStore.getFolder(message.getFolder().getName()); remoteFolder = remoteStore.getFolder(message.getFolder().getName()); remoteFolder.open(OpenMode.READ_WRITE); FetchProfile fp = new FetchProfile(); fp.add(part); remoteFolder.fetch(new Message[] { message }, fp, null); localFolder.updateMessage((LocalMessage)message); for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); for (MessagingListener l : getListeners()) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } if (listener != null) { listener.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } addErrorMessage(account, null, me); } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } }); } /** * Stores the given message in the Outbox and starts a sendPendingMessages command to * attempt to send the message. * @param account * @param message * @param listener */ public void sendMessage(final Account account, final Message message, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, null); } catch (Exception e) { /* for (MessagingListener l : getListeners()) { // TODO general failed } */ addErrorMessage(account, null, e); } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final Account account, MessagingListener listener) { putBackground("sendPendingMessages", listener, new Runnable() { public void run() { sendPendingMessagesSynchronous(account); } }); } public boolean messagesPendingSend(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); int localMessages = localFolder.getMessageCount(); if (localMessages > 0) { return true; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); } finally { if (localFolder != null) { localFolder.close(); } } return false; } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); boolean anyFlagged = false; int progress = 0; int todo = localMessages.length; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* * The profile we will use to pull all of the content * for a given local message into memory for sending. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); for (Message message : localMessages) { if (message.isSet(Flag.DELETED)) { message.setFlag(Flag.X_DESTROYED, true); continue; } if (message.isSet(Flag.FLAGGED)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid()); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging"); message.setFlag(Flag.FLAGGED, true); anyFlagged = true; continue; } localFolder.fetch(new Message[] { message }, fp, null); try { message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } if (K9.FOLDER_NONE.equals(account.getSentFolderName())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = (LocalFolder) localStore.getFolder( account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); localFolder.moveMessages( new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localSentFolder.getName(), message.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } } catch (Exception e) { if (e instanceof MessagingException) { MessagingException me = (MessagingException)e; if (me.isPermanentFailure() == false) { // Decrement the counter if the message could not possibly have been sent int newVal = count.decrementAndGet(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal + "; no possible send"); } } message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); /* * We ignore this exception because a future refresh will retry this * message. */ } } if (localFolder.getMessageCount() == 0) { localFolder.delete(false); } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (anyFlagged) { addErrorMessage(account, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME)); NotificationManager notifMgr = (NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis()); Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName()); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0); notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi); notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; notifMgr.notify(-1000 - account.getAccountNumber(), notif); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while closing folder", e); } } } } public void getAccountStats(final Context context, final Account account, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { try { AccountStats stats = account.getStats(context); l.accountStatusChanged(account, stats); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } } }; put("getAccountStats:" + account.getDescription(), l, unreadRunnable); } public void getFolderUnreadMessageCount(final Account account, final String folderName, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { int unreadMessageCount = 0; try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); } }; put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable); } public boolean isMoveCapable(Message message) { if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { return true; } else { return false; } } public boolean isCopyCapable(Message message) { return isMoveCapable(message); } public boolean isMoveCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } public boolean isCopyCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { for (Message message : messages) { suppressMessage(account, srcFolder, message); } putBackground("moveMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { putBackground("copyMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages, final String destFolder, final boolean isCopy, MessagingListener listener) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false)) { return; } if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false)) { return; } Folder localSrcFolder = localStore.getFolder(srcFolder); Folder localDestFolder = localStore.getFolder(destFolder); List<String> uids = new LinkedList<String>(); for (Message message : inMessages) { String uid = message.getUid(); if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } } Message[] messages = localSrcFolder.getMessages(uids.toArray(new String[0]), null); if (messages.length > 0) { Map<String, Message> origUidMap = new HashMap<String, Message>(); for (Message message : messages) { origUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); localSrcFolder.copyMessages(messages, localDestFolder); } else { localSrcFolder.moveMessages(messages, localDestFolder); for (String origUid : origUidMap.keySet()) { for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid()); } unsuppressMessage(account, srcFolder, origUid); } } queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(new String[0])); } processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } public void expunge(final Account account, final String folder, final MessagingListener listener) { putBackground("expunge", null, new Runnable() { public void run() { queueExpunge(account, folder); } }); } public void deleteDraft(final Account account, String uid) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message != null) { deleteMessages(new Message[] { message }, null); } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { if (localFolder != null) { localFolder.close(); } } } public void deleteMessages(final Message[] messages, final MessagingListener listener) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { for (Message message : messages) { suppressMessage(account, folder.getName(), message); } putBackground("deleteMessages", null, new Runnable() { public void run() { deleteMessagesSynchronous(account, folder.getName(), messages.toArray(new Message[0]), listener); } }); } }); } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved for (Message message : messages) { if (listener != null) { listener.messageDeleted(account, folder, message); } for (MessagingListener l : getListeners()) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (localTrashFolder.exists() == false) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists() == true) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); localFolder.moveMessages(messages, localTrashFolder); } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); } else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } for (String uid : uids) { unsuppressMessage(account, folder, uid); } } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); } finally { if (localFolder != null) { localFolder.close(); } if (localTrashFolder != null) { localTrashFolder.close(); } } } private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); try { if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } finally { if (remoteFolder != null) { remoteFolder.close(); } } } public void emptyTrash(final Account account, MessagingListener listener) { putBackground("emptyTrash", listener, new Runnable() { public void run() { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.setFlags(new Flag[] { Flag.DELETED }, true); for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } List<String> args = new ArrayList<String>(); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EMPTY_TRASH; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } }); } public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); try { Intent msg=new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject()); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } }); } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. * * @param context * @param account * @param listener */ public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) { WakeLock twakeLock = null; if (useManualWakeLock) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9"); twakeLock.setReferenceCounted(false); twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT); } final WakeLock wakeLock = twakeLock; for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } putBackground("checkMail", listener, new Runnable() { public void run() { final NotificationManager notifMgr = (NotificationManager)context .getSystemService(Context.NOTIFICATION_SERVICE); try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Account[] accounts; if (account != null) { accounts = new Account[] { account }; } else { accounts = prefs.getAccounts(); } for (final Account account : accounts) { final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (ignoreLastCheckedTime == false && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); account.setRingNotified(false); putBackground("sendPending " + account.getDescription(), null, new Runnable() { public void run() { if (messagesPendingSend(account)) { if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title), account.getDescription() , pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_DIM_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION_ID, notif); } try { sendPendingMessagesSynchronous(account); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION_ID); } } } } } ); try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces()) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode); continue; } if (K9.DEBUG) Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + new Date(folder.getLastChecked())); if (ignoreLastCheckedTime == false && folder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); continue; } putBackground("sync" + folder.getName(), null, new Runnable() { public void run() { LocalFolder tLocalFolder = null; try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder.getName()); tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription() + context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_DIM_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION_ID, notif); } try { synchronizeMailboxSynchronous(account, folder.getName(), listener); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION_ID); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); } finally { if (tLocalFolder != null) { tLocalFolder.close(); } } } } ); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); } } ); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); if (wakeLock != null) { wakeLock.release(); } for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } } } ); } }); } public void compact(final Account account, final MessagingListener ml) { putBackground("compact:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } public void clear(final Account account, final MessagingListener ml) { putBackground("clear:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } /** Creates a notification of new email messages * ringtone, lights, and vibration to be played */ private boolean notifyAccount(Context context, Account account, Message message) { // Do not notify if the user does not have notifications // enabled or if the message has been read if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) { return false; } // If we have a message, set the notification to "<From>: <Subject>" StringBuffer messageNotice = new StringBuffer(); try { if (message != null && message.getFrom() != null) { Address[] fromAddrs = message.getFrom(); String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null; String subject = message.getSubject(); if (subject == null) { subject = context.getString(R.string.general_no_subject); } if (from != null) { // Show From: address by default if (account.isAnIdentity(fromAddrs) == false) { messageNotice.append(from + ": " + subject); } // show To: if the message was sent from me else { // Do not notify of mail from self if !isNotifySelfNewMail if (!account.isNotifySelfNewMail()) { return false; } Address[] rcpts = message.getRecipients(Message.RecipientType.TO); String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null; if (to != null) { messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject); } else { messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject); } } } } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e); } // If we could not set a per-message notification, revert to a default message if (messageNotice.length() == 0) { messageNotice.append(context.getString(R.string.notification_new_title)); } int unreadMessageCount = 0; try { AccountStats stats = account.getStats(context); unreadMessageCount = stats.unreadMessageCount; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis()); notif.number = unreadMessageCount; Intent i = FolderList.actionHandleAccountIntent(context, account, account.getAutoExpandFolderName()); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, account.getDescription()); notif.setLatestEventInfo(context, accountNotice, messageNotice, pi); // Only ring or vibrate if we have not done so already on this // account and fetch if (!account.isRingNotified()) { account.setRingNotified(true); if (account.isRing()) { String ringtone = account.getRingtone(); notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone); } if (account.isVibrate()) { notif.defaults |= Notification.DEFAULT_VIBRATE; } } notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; notifMgr.notify(account.getAccountNumber(), notif); return true; } /** Cancel a notification of new email messages */ public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); } public Message saveDraft(final Account account, final Message message) { Message localMessage = null; try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { return true; } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); class Command implements Comparable<Command> { public Runnable runnable; public MessagingListener listener; public String description; boolean isForeground; int sequence = sequencing.getAndIncrement(); @Override public int compareTo(Command other) { if (other.isForeground == true && isForeground == false) { return 1; } else if (other.isForeground == false && isForeground == true) { return -1; } else { return (sequence - other.sequence); } } } public MessagingListener getCheckMailListener() { return checkMailListener; } public void setCheckMailListener(MessagingListener checkMailListener) { if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; if (this.checkMailListener != null) { addListener(this.checkMailListener); } } public SORT_TYPE getSortType() { return sortType; } public void setSortType(SORT_TYPE sortType) { this.sortType = sortType; } public boolean isSortAscending(SORT_TYPE sortType) { Boolean sortAsc = sortAscending.get(sortType); if (sortAsc == null) { return sortType.isDefaultAscending(); } else return sortAsc; } public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending) { sortAscending.put(sortType, nsortAscending); } public Collection<Pusher> getPushers() { return pushers.values(); } public boolean setupPushing(final Account account) { try { Pusher previousPusher = pushers.remove(account); if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); List<String> names = new ArrayList<String>(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces()) { if (folder.getName().equals(account.getErrorFolderName()) || folder.getName().equals(account.getOutboxFolderName())) { if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which should never be pushed"); continue; } folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in push mode " + fPushClass + " while account is in push mode " + aPushMode); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); names.add(folder.getName()); } if (names.size() > 0) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); names = names.subList(0, maxPushFolders); } try { Store store = account.getRemoteStore(); if (store.isPushCapable() == false) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); Pusher oldPusher = null; if (pusher != null) { oldPusher = pushers.putIfAbsent(account, pusher); } if (oldPusher != null) { pusher = oldPusher; } else { pusher.start(names); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator<Pusher> iter = pushers.values().iterator(); while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() + ", folder " + remoteFolder.getName(), null, new Runnable() { public void run() { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder= localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); account.setRingNotified(false); int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size()); setLocalFlaggedCountToRemote(localFolder, remoteFolder); localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; try { localFolder.setStatus(errorMessage); } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to close localFolder", e); } } latch.countDown(); } } }); try { latch.await(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } enum MemorizingState { STARTED, FINISHED, FAILED }; class Memory { Account account; String folderName; MemorizingState syncingState = null; MemorizingState sendingState = null; MemorizingState pushingState = null; MemorizingState processingState = null; String failureMessage = null; int syncingTotalMessagesInMailbox; int syncingNumNewMessages; int folderCompleted = 0; int folderTotal = 0; String processingCommandTitle = null; Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } String getKey() { return getMemoryKey(account, folderName); } } static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } class MemorizingListener extends MessagingListener { HashMap<String, Memory> memories = new HashMap<String, Memory>(31); Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } return memory; } @Override public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; memory.syncingNumNewMessages = numNewMessages; } @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } synchronized void refreshOther(MessagingListener other) { if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; for (Memory memory : memories.values()) { if (memory.syncingState != null) { switch (memory.syncingState) { case STARTED: syncStarted = memory; break; case FINISHED: other.synchronizeMailboxFinished(memory.account, memory.folderName, memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); break; case FAILED: other.synchronizeMailboxFailed(memory.account, memory.folderName, memory.failureMessage); break; } } if (memory.sendingState != null) { switch (memory.sendingState) { case STARTED: sendStarted = memory; break; case FINISHED: other.sendPendingMessagesCompleted(memory.account); break; case FAILED: other.sendPendingMessagesFailed(memory.account); break; } } if (memory.pushingState != null) { switch (memory.pushingState) { case STARTED: other.setPushActive(memory.account, memory.folderName, true); break; case FINISHED: other.setPushActive(memory.account, memory.folderName, false); break; } } if (memory.processingState != null) { switch (memory.processingState) { case STARTED: processingStarted = memory; break; case FINISHED: case FAILED: other.pendingCommandsFinished(memory.account); break; } } } Memory somethingStarted = null; if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; } @Override public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } private void actOnMessages(Message[] messages, MessageActor actor) { Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>(); for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map<Folder, List<Message>> folderMap = accountMap.get(account); if (folderMap == null) { folderMap = new HashMap<Folder, List<Message>>(); accountMap.put(account, folderMap); } List<Message> messageList = folderMap.get(folder); if (messageList == null) { messageList = new LinkedList<Message>(); folderMap.put(folder, messageList); } messageList.add(message); } for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map<Folder, List<Message>> folderMap = entry.getValue(); for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List<Message> messageList = folderEntry.getValue(); actor.act(account, folder, messageList); } } } interface MessageActor { public void act(final Account account, final Folder folder, final List<Message> messages); } }
package org.bouncycastle.crypto; /** * Ciphers producing a key stream which can be reset to particular points in the stream. */ public interface SkippingCipher { long skip(long numberOfBlocks); }
package org.orbeon.oxf.xml.dom4j; import org.orbeon.dom.*; import org.orbeon.dom.io.*; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.pipeline.api.TransformerXMLReceiver; import org.orbeon.oxf.processor.generator.DOMGenerator; import org.orbeon.oxf.resources.URLFactory; import org.orbeon.oxf.util.StringUtils; import org.orbeon.oxf.util.StringBuilderWriter; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.XMLUtils; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.*; // TODO: move this to Scala/remove unneeded stuff public class Dom4jUtils { /** * 03/30/2005 d : Currently DOM4J doesn't really support read only documents. ( No real * checks in place. If/when DOM4J adds real support then NULL_DOCUMENT should be made a * read only document. */ public static final Document NULL_DOCUMENT; static { NULL_DOCUMENT = DocumentFactory.createDocument(); Element nullElement = DocumentFactory.createElement("null"); nullElement.addAttribute(XMLConstants.XSI_NIL_QNAME, "true"); NULL_DOCUMENT.setRootElement(nullElement); } private static SAXReader createSAXReader(XMLParsing.ParserConfiguration parserConfiguration) throws SAXException { return new SAXReader(XMLParsing.newXMLReader(parserConfiguration)); } private static SAXReader createSAXReader() throws SAXException { return createSAXReader(XMLParsing.ParserConfiguration.XINCLUDE_ONLY); } /** * Convert a dom4j document to a string. * * @param document document to convert * @return resulting string */ public static String domToString(final Document document) { final Element rootElement = document.getRootElement(); return domToString((Branch) rootElement); } /** * Convert a dom4j element to a string. * * @param element element to convert * @return resulting string */ public static String domToString(final Element element) { return domToString((Branch) element); } /** * Convert a dom4j node to a string. * * @param node node to convert * @return resulting string */ public static String nodeToString(final Node node) { final String ret; if (node instanceof Document) { ret = domToString((Branch) ((Document) node).getRootElement()); } else if (node instanceof Element) { ret = domToString((Branch) node); } else if (node instanceof Text) { ret = node.getText(); } else { ret = domToString(node, null); } return ret; } /** * Convert an XML string to a prettified XML string. */ public static String prettyfy(String xmlString) { try { return domToPrettyString(readDom4j(xmlString)); } catch (Exception e) { throw new OXFException(e); } } /** * Convert a dom4j document to a pretty string, for formatting/debugging purposes only. * * @param document document to convert * @return resulting string */ public static String domToPrettyString(final Document document) { return domToPrettyString(document.getRootElement()); } public static String domToPrettyString(final Element element) { return domToString(element, OutputFormat.apply(true, true, true)); } /** * Convert a dom4j document to a compact string, with all text being trimmed. * * @param document document to convert * @return resulting string */ public static String domToCompactString(final Document document) { return domToString(document.getRootElement(), OutputFormat.apply(false, false, true)); } private static String domToString(final Branch branch) { return domToString(branch, OutputFormat.apply(false, false, false)); } private static String domToString(final Node node, final OutputFormat format) { final StringBuilderWriter writer = new StringBuilderWriter(); final XMLWriter xmlWriter = new XMLWriter(writer, format == null ? XMLWriter.DefaultFormat() : format); xmlWriter.write(node); writer.close(); return writer.toString(); } /** * Read a document from a URL. * * @param urlString URL * @param parserConfiguration parser configuration * @return document */ public static Document readFromURL(String urlString, XMLParsing.ParserConfiguration parserConfiguration) { InputStream is = null; try { final URL url = URLFactory.createURL(urlString); is = url.openStream(); return readDom4j(is, urlString, parserConfiguration); } catch (Exception e) { throw new OXFException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new OXFException("Exception while closing stream", e); } } } } public static Document readDom4j(Reader reader) throws SAXException, DocumentException { return createSAXReader().read(reader); } public static Document readDom4j(Reader reader, String uri) throws SAXException, DocumentException { return createSAXReader().read(reader, uri); } /* * Replacement for DocumentHelper.parseText. DocumentHelper.parseText is not used since it creates work for GC * (because it relies on JAXP). */ public static Document readDom4j(String xmlString, XMLParsing.ParserConfiguration parserConfiguration) throws SAXException, DocumentException { final StringReader stringReader = new StringReader(xmlString); return createSAXReader(parserConfiguration).read(stringReader); } public static Document readDom4j(String xmlString) throws SAXException, DocumentException { return readDom4j(xmlString, XMLParsing.ParserConfiguration.PLAIN); } public static Document readDom4j(InputStream inputStream, String uri, XMLParsing.ParserConfiguration parserConfiguration) throws SAXException, DocumentException { return createSAXReader(parserConfiguration).read(inputStream, uri); } public static Document readDom4j(InputStream inputStream) throws SAXException, DocumentException { return createSAXReader(XMLParsing.ParserConfiguration.PLAIN).read(inputStream); } public static String makeSystemId(final Element e) { final LocationData ld = (LocationData) e.getData(); final String ldSid = ld == null ? null : ld.file(); return ldSid == null ? DOMGenerator.DefaultContext : ldSid; } public static Node normalizeTextNodes(Node nodeToNormalize) { final List<Node> nodesToDetach = new ArrayList<Node>(); nodeToNormalize.accept(new VisitorSupport() { public void visit(Element element) { final List children = element.content(); Node previousNode = null; StringBuilder sb = null; for (Iterator i = children.iterator(); i.hasNext();) { final Node currentNode = (Node) i.next(); if (previousNode != null) { if (previousNode instanceof Text && currentNode instanceof Text) { final Text previousNodeText = (Text) previousNode; if (sb == null) sb = new StringBuilder(previousNodeText.getText()); sb.append(currentNode.getText()); nodesToDetach.add(currentNode); } else if (previousNode instanceof Text) { // Update node if needed if (sb != null) { previousNode.setText(sb.toString()); } previousNode = currentNode; sb = null; } else { previousNode = currentNode; sb = null; } } else { previousNode = currentNode; sb = null; } } // Update node if needed if (previousNode != null && sb != null) { previousNode.setText(sb.toString()); } } }); // Detach nodes only in the end so as to not confuse the acceptor above for (final Node currentNode: nodesToDetach) { currentNode.detach(); } return nodeToNormalize; } public static DocumentSource getDocumentSource(final Document d) { /* * Saxon's error handler is expensive for the service it provides so we just use our * singleton instead. * * Wrt expensive, delta in heap dump info below is amount of bytes allocated during the * handling of a single request to '/' in the examples app. i.e. The trace below was * responsible for creating 200k of garbage during the handing of a single request to '/'. * * delta: 213408 live: 853632 alloc: 4497984 trace: 380739 class: byte[] * * TRACE 380739: * java.nio.HeapByteBuffer.<init>(HeapByteBuffer.java:39) * java.nio.ByteBuffer.allocate(ByteBuffer.java:312) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:310) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:290) * sun.nio.cs.StreamEncoder$CharsetSE.<init>(StreamEncoder.java:274) * sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:69) * java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:93) * java.io.PrintWriter.<init>(PrintWriter.java:109) * java.io.PrintWriter.<init>(PrintWriter.java:92) * org.orbeon.saxon.StandardErrorHandler.<init>(StandardErrorHandler.java:22) * org.orbeon.saxon.event.Sender.sendSAXSource(Sender.java:165) * org.orbeon.saxon.event.Sender.send(Sender.java:94) * org.orbeon.saxon.IdentityTransformer.transform(IdentityTransformer.java:31) * org.orbeon.oxf.xml.XMLUtils.getDigest(XMLUtils.java:453) * org.orbeon.oxf.xml.XMLUtils.getDigest(XMLUtils.java:423) * org.orbeon.oxf.processor.generator.DOMGenerator.<init>(DOMGenerator.java:93) * * Before mod * * 1.4.2_06-b03 P4 2.6 Ghz / 50 th tc 4.1.30 10510 ms ( 150 mb ), 7124 ( 512 mb ) 2.131312472239924 ( 150 mb ), 1.7474380872589803 ( 512 mb ) * * after mod * * 1.4.2_06-b03 P4 2.6 Ghz / 50 th tc 4.1.30 9154 ms ( 150 mb ), 6949 ( 512 mb ) 1.7316203642295738 ( 150 mb ), 1.479365288194895 ( 512 mb ) * */ final LocationDocumentSource lds = new LocationDocumentSource(d); final XMLReader rdr = lds.getXMLReader(); rdr.setErrorHandler(XMLParsing.ERROR_HANDLER); return lds; } public static byte[] getDigest(Document document) { final DocumentSource ds = getDocumentSource(document); return DigestContentHandler.getDigest(ds); } public static Document adjustNamespaces(Document document, boolean xml11) { if (xml11) return document; final LocationSAXWriter writer = new LocationSAXWriter(); final LocationSAXContentHandler ch = new LocationSAXContentHandler(); writer.setContentHandler(new NamespaceCleanupXMLReceiver(ch, xml11)); writer.write(document); return ch.getDocument(); } /** * Return a Map of namespaces in scope on the given element. */ public static Map<String, String> getNamespaceContext(Element element) { final Map<String, String> namespaces = new HashMap<String, String>(); for (Element currentNode = element; currentNode != null; currentNode = currentNode.getParent()) { final List currentNamespaces = currentNode.declaredNamespaces(); for (Iterator j = currentNamespaces.iterator(); j.hasNext();) { final Namespace namespace = (Namespace) j.next(); if (!namespaces.containsKey(namespace.prefix())) { namespaces.put(namespace.prefix(), namespace.uri()); // TODO: Intern namespace strings to save memory; should use NamePool later // namespaces.put(namespace.getPrefix().intern(), namespace.getURI().intern()); } } } // It seems that by default this may not be declared. However, it should be: "The prefix xml is by definition // NOT be bound to any other namespace name. Other prefixes MUST NOT be bound to this namespace name, and it // MUST NOT be declared as the default namespace." namespaces.put(XMLConstants.XML_PREFIX, XMLConstants.XML_URI); return namespaces; } /** * Return a Map of namespaces in scope on the given element, without the default namespace. */ public static Map<String, String> getNamespaceContextNoDefault(Element element) { final Map<String, String> namespaces = getNamespaceContext(element); namespaces.remove(""); return namespaces; } /** * Extract a QName from an Element and an attribute name. The prefix of the QName must be in * scope. Return null if the attribute is not found. */ public static QName extractAttributeValueQName(Element element, String attributeName) { return extractTextValueQName(element, element.attributeValue(attributeName), true); } /** * Extract a QName from an Element and an attribute QName. The prefix of the QName must be in * scope. Return null if the attribute is not found. */ public static QName extractAttributeValueQName(Element element, QName attributeQName) { return extractTextValueQName(element, element.attributeValue(attributeQName), true); } public static QName extractAttributeValueQName(Element element, QName attributeQName, boolean unprefixedIsNoNamespace) { return extractTextValueQName(element, element.attributeValue(attributeQName), unprefixedIsNoNamespace); } /** * Extract a QName from an Element's string value. The prefix of the QName must be in scope. * Return null if the text is empty. */ public static QName extractTextValueQName(Element element, boolean unprefixedIsNoNamespace) { return extractTextValueQName(element, element.getStringValue(), unprefixedIsNoNamespace); } /** * Extract a QName from an Element's string value. The prefix of the QName must be in scope. * Return null if the text is empty. * * @param element Element containing the attribute * @param qNameString QName to analyze * @param unprefixedIsNoNamespace if true, an unprefixed value is in no namespace; if false, it is in the default namespace * @return a QName object or null if not found */ public static QName extractTextValueQName(Element element, String qNameString, boolean unprefixedIsNoNamespace) { return extractTextValueQName(getNamespaceContext(element), qNameString, unprefixedIsNoNamespace); } /** * Extract a QName from a string value, given namespace mappings. Return null if the text is empty. * * @param namespaces prefix -> URI mappings * @param qNameString QName to analyze * @param unprefixedIsNoNamespace if true, an unprefixed value is in no namespace; if false, it is in the default namespace * @return a QName object or null if not found */ public static QName extractTextValueQName(Map<String, String> namespaces, String qNameString, boolean unprefixedIsNoNamespace) { if (qNameString == null) return null; qNameString = StringUtils.trimAllToEmpty(qNameString); if (qNameString.length() == 0) return null; final int colonIndex = qNameString.indexOf(':'); final String prefix; final String localName; final String namespaceURI; if (colonIndex == -1) { prefix = ""; localName = qNameString; if (unprefixedIsNoNamespace) { namespaceURI = ""; } else { final String nsURI = namespaces.get(prefix); namespaceURI = nsURI == null ? "" : nsURI; } } else if (colonIndex == 0) { throw new OXFException("Empty prefix for QName: " + qNameString); } else { prefix = qNameString.substring(0, colonIndex); localName = qNameString.substring(colonIndex + 1); namespaceURI = namespaces.get(prefix); if (namespaceURI == null) { throw new OXFException("No namespace declaration found for prefix: " + prefix); } } return QName.get(localName, Namespace$.MODULE$.apply(prefix, namespaceURI)); } /** * Decode a String containing an exploded QName (also known as a "Clark name") into a QName. */ public static QName explodedQNameToQName(String qName) { int openIndex = qName.indexOf("{"); if (openIndex == -1) return QName.get(qName); String namespaceURI = qName.substring(openIndex + 1, qName.indexOf("}")); String localName = qName.substring(qName.indexOf("}") + 1); return QName.get(localName, Namespace$.MODULE$.apply("p1", namespaceURI)); } // TODO ORBEON: remove uses, just use DocumentFactory /** * Create a copy of a dom4j Node. * * @param source source Node * @return copy of Node */ public static Node createCopy(Node source) { return (source instanceof Element) ? ((Element) source).createCopy() : (Node) source.clone(); } /** * Return a new document with a copy of newRoot as its root. */ public static Document createDocumentCopyElement(final Element newRoot) { return DocumentFactory.createDocument(newRoot.createCopy()); } /** * Return a new document with all parent namespaces copied to the new root element, assuming they are not already * declared on the new root element. The element passed is deep copied. * * @param newRoot element which must become the new root element of the document * @return new document */ public static Document createDocumentCopyParentNamespaces(final Element newRoot) { return createDocumentCopyParentNamespaces(newRoot, false); } /** * Return a new document with all parent namespaces copied to the new root element, assuming they are not already * declared on the new root element. * * @param newRoot element which must become the new root element of the document * @param detach if true the element is detached, otherwise it is deep copied * @return new document */ public static Document createDocumentCopyParentNamespaces(final Element newRoot, boolean detach) { final Element parentElement = newRoot.getParent(); final Document document; { if (detach) { // Detach document = DocumentFactory.createDocument(); document.setRootElement((Element) newRoot.detach()); } else { // Copy document = createDocumentCopyElement(newRoot); } } copyMissingNamespaces(parentElement, document.getRootElement()); return document; } public static void copyMissingNamespaces(Element sourceElement, Element destinationElement) { final Map<String, String> parentNamespaceContext = Dom4jUtils.getNamespaceContext(sourceElement); final Map<String, String> rootElementNamespaceContext = Dom4jUtils.getNamespaceContext(destinationElement); for (final String prefix: parentNamespaceContext.keySet()) { // NOTE: Don't use rootElement.getNamespaceForPrefix() because that will return the element prefix's // namespace even if there are no namespace nodes if (rootElementNamespaceContext.get(prefix) == null) { final String uri = parentNamespaceContext.get(prefix); destinationElement.addNamespace(prefix, uri); } } } /** * Return a new document with a copy of newRoot as its root and all parent namespaces copied to the new root * element, except those with the prefixes appearing in the Map, assuming they are not already declared on the new * root element. */ public static Document createDocumentCopyParentNamespaces(final Element newRoot, Set<String> prefixesToFilter) { final Document document = Dom4jUtils.createDocumentCopyElement(newRoot); final Element rootElement = document.getRootElement(); final Element parentElement = newRoot.getParent(); final Map<String, String> parentNamespaceContext = Dom4jUtils.getNamespaceContext(parentElement); final Map<String, String> rootElementNamespaceContext = Dom4jUtils.getNamespaceContext(rootElement); for (final String prefix: parentNamespaceContext.keySet()) { // NOTE: Don't use rootElement.getNamespaceForPrefix() because that will return the element prefix's // namespace even if there are no namespace nodes if (rootElementNamespaceContext.get(prefix) == null && ! prefixesToFilter.contains(prefix)) { final String uri = parentNamespaceContext.get(prefix); rootElement.addNamespace(prefix, uri); } } return document; } /** * Return a copy of the given element which includes all the namespaces in scope on the element. * * @param sourceElement element to copy * @return copied element */ public static Element copyElementCopyParentNamespaces(final Element sourceElement) { final Element newElement = sourceElement.createCopy(); copyMissingNamespaces(sourceElement.getParent(), newElement); return newElement; } /** * Workaround for Java's lack of an equivalent to C's __FILE__ and __LINE__ macros. Use * carefully as it is not fast. * * Perhaps in 1.5 we will find a better way. * * @return LocationData of caller. */ public static LocationData getLocationData() { return getLocationData(1, false); } public static LocationData getLocationData(final int depth, boolean isDebug) { // Enable this with a property for debugging only, as it is time consuming if (!isDebug && !org.orbeon.oxf.properties.Properties.instance().getPropertySet() .getBoolean("oxf.debug.enable-java-location-data", false)) return null; // Compute stack trace and extract useful information final Exception e = new Exception(); final StackTraceElement[] stkTrc = e.getStackTrace(); final int depthToUse = depth + 1; final String sysID = stkTrc[depthToUse].getFileName(); final int line = stkTrc[depthToUse].getLineNumber(); return new LocationData(sysID, line, -1); } /** * Visit a subtree of a dom4j document. * * @param container element containing the elements to visit * @param visitorListener listener to call back */ public static void visitSubtree(Element container, VisitorListener visitorListener) { visitSubtree(container, visitorListener, false); } /** * Visit a subtree of a dom4j document. * * @param container element containing the elements to visit * @param visitorListener listener to call back * @param mutable whether the source tree can mutate while being visited */ public static void visitSubtree(Element container, VisitorListener visitorListener, boolean mutable) { // If the source tree can mutate, copy the list first, otherwise dom4j might throw exceptions final List<Node> content = mutable ? new ArrayList<Node>(container.content()) : container.content(); // Iterate over the content for (final Node childNode : content) { if (childNode instanceof Element) { final Element childElement = (Element) childNode; visitorListener.startElement(childElement); visitSubtree(childElement, visitorListener, mutable); visitorListener.endElement(childElement); } else if (childNode instanceof Text) { visitorListener.text((Text) childNode); } else { // Ignore as we don't need other node types for now } } } public static String elementToDebugString(Element element) { // Open start tag final StringBuilder sb = new StringBuilder("<"); sb.append(element.getQualifiedName()); // Attributes if any for (Iterator i = element.attributeIterator(); i.hasNext();) { final Attribute currentAttribute = (Attribute) i.next(); sb.append(' '); sb.append(currentAttribute.getQualifiedName()); sb.append("=\""); sb.append(currentAttribute.getValue()); sb.append('\"'); } final boolean isEmptyElement = element.elements().isEmpty() && element.getText().length() == 0; if (isEmptyElement) { // Close empty element sb.append("/>"); } else { // Close start tag sb.append('>'); sb.append("[...]"); // Close element with end tag sb.append("</"); sb.append(element.getQualifiedName()); sb.append('>'); } return sb.toString(); } public static String attributeToDebugString(Attribute attribute) { return attribute.getQualifiedName() + "=\"" + attribute.getValue() + '\"'; } /** * Convert dom4j attributes to SAX attributes. * * @param element dom4j Element * @return SAX Attributes */ public static AttributesImpl getSAXAttributes(Element element) { final AttributesImpl result = new AttributesImpl(); for (Iterator i = element.attributeIterator(); i.hasNext();) { final Attribute attribute = (Attribute) i.next(); result.addAttribute(attribute.getNamespaceURI(), attribute.getName(), attribute.getQualifiedName(), XMLReceiverHelper.CDATA, attribute.getValue()); } return result; } public static Document createDocument(DebugXML debugXML) { final TransformerXMLReceiver identity = TransformerUtils.getIdentityTransformerHandler(); final LocationDocumentResult result = new LocationDocumentResult(); identity.setResult(result); final XMLReceiverHelper helper = new XMLReceiverHelper(new ForwardingXMLReceiver(identity) { @Override public void startDocument() {} @Override public void endDocument() {} }); try { identity.startDocument(); debugXML.toXML(helper); identity.endDocument(); } catch (SAXException e) { throw new OXFException(e); } return result.getDocument(); } /** * Encode a QName to an exploded QName (also known as a "Clark name") String. */ public static String qNameToExplodedQName(QName qName) { return (qName == null) ? null : XMLUtils.buildExplodedQName(qName.getNamespaceURI(), qName.getName()); } // http://www.w3.org/TR/xpath-30/#doc-xpath30-URIQualifiedName public static String buildURIQualifiedName(QName qName) { return XMLUtils.buildURIQualifiedName(qName.getNamespaceURI(), qName.getName()); } public interface VisitorListener { void startElement(Element element); void endElement(Element element); void text(Text text); } public interface DebugXML { void toXML(XMLReceiverHelper helper); } }
package eic.beike.projectx.model; import eic.beike.projectx.network.busdata.SimpleBusCollector; import android.util.Log; import eic.beike.projectx.network.busdata.BusCollector; import eic.beike.projectx.network.busdata.Sensor; import eic.beike.projectx.util.Constants; /** *@author Simon */ public class Count implements ScoreCountApi { /** * The gameModel uses this counter. */ private final Long epochyear = 1444800000000l; private GameModel gameModel; public Count(GameModel game) { this.gameModel = game; } @Override public void count(long t1) { new Thread() { long t1; public void count(long t1) { this.t1 = t1; this.start(); } /** * Runs until a Stop pressed event is found. */ @Override public void run() { try { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Long startTime = System.currentTimeMillis() + Constants.ONE_SECOND_IN_MILLI * 20; BusCollector bus = SimpleBusCollector.getInstance(); Long t2; while(System.currentTimeMillis() < startTime) { t2 = bus.getBusData(t1, Sensor.Stop_Pressed).timestamp; calculatePercent(t1, t2); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { Log.e("Count", e.getMessage()); } } }.count(t1); } public void sum(Button[][] buttons) { gameModel.addBonus(columns(buttons) + rows(buttons)); } /** * @return returns the score from all buttons that are "three of a kind" * it also sets that they are counted so they can be generated again */ private int columns(Button[][] buttons) { int count = 0; for (Button[] button : buttons) { if (button[0].color == button[1].color && button[0].color == button[2].color) { count += button[0].score + button[1].score + button[2].score; button[0].counted = true; button[1].counted = true; button[2].counted = true; } } return count; } /** * @return returns the score fomr all buttons that are "three of a kind" * it also sets that they are counted so they can be generated again */ private int rows(Button[][] buttons) { int count = 0; for (int i = 0; i < buttons.length; i++) { if (buttons[0][i].color == buttons[1][i].color && buttons[1][i].color == buttons[2][i].color) { count += buttons[0][i].score + buttons[1][i].score + buttons[2][i].score; buttons[0][i].counted = true; buttons[1][i].counted = true; buttons[2][i].counted = true; } } return count; } public synchronized void calculatePercent(long t1, long t2) { if (t2 == 0) { gameModel.addScore(0.3); } else if (t1 < t2) { t1 -= epochyear; t2 -= epochyear; gameModel.addScore(Math.abs( ((double) t1 / (double) t2))); } else { t1 -= epochyear; t2 -= epochyear; gameModel.addScore(Math.abs( ( (double) t2 / (double) t1))); } } }
package com.googlecode.ant_deb_task; import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.Tar; import org.apache.tools.ant.types.*; import org.apache.tools.tar.TarOutputStream; import java.io.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import java.security.MessageDigest; import java.net.URL; import java.net.MalformedURLException; /** * Task that creates a Debian package. * * @antTaskName deb */ public class Deb extends Task { private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+"); public static class Description extends ProjectComponent { private String _synopsis; private String _extended = ""; public String getSynopsis () { return _synopsis; } public void setSynopsis (String synopsis) { _synopsis = synopsis.trim (); } public void addText (String text) { _extended += getProject ().replaceProperties (text); } public String getExtended () { return _extended; } public String getExtendedFormatted () { StringBuffer buffer = new StringBuffer (_extended.length ()); String lines[] = _extended.split ("\n"); int start = 0; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim (); if (line.length () > 0) break; start++; } int end = lines.length; for (int i = lines.length - 1; i >= 0; i { String line = lines[i].trim (); if (line.length () > 0) break; end } for (int i = start; i < end; i++) { String line = lines[i].trim (); buffer.append (' '); buffer.append (line.length () == 0 ? "." : line); buffer.append ('\n'); } buffer.deleteCharAt (buffer.length () - 1); return buffer.toString (); } } public static class Version extends ProjectComponent { private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9.+\\-:~]*"); private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+.~]+"); private int _epoch = 0; private String _upstream; private String _debian = "1"; public void setEpoch(int epoch) { _epoch = epoch; } public void setUpstream(String upstream) { _upstream = upstream.trim (); if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ()) throw new BuildException("Invalid upstream version number!"); } public void setDebian(String debian) { _debian = debian.trim (); if (_debian.length() > 0 && !DEBIAN_VERSION_PATTERN.matcher (_debian).matches ()) throw new BuildException("Invalid debian version number!"); } public String toString() { StringBuffer version = new StringBuffer(); if (_epoch > 0) { version.append(_epoch); version.append(':'); } else if (_upstream.indexOf(':') > -1) throw new BuildException("Upstream version can contain colons only if epoch is specified!"); version.append(_upstream); if (_debian.length() > 0) { version.append('-'); version.append(_debian); } else if (_upstream.indexOf('-') > -1) throw new BuildException("Upstream version can contain hyphens only if debian version is specified!"); return version.toString(); } } public static class Maintainer extends ProjectComponent { private String _name; private String _email; public void setName (String name) { _name = name.trim (); } public void setEmail (String email) { _email = email.trim (); } public String toString() { if (_name == null || _name.length () == 0) return _email; StringBuffer buffer = new StringBuffer (_name); buffer.append (" <"); buffer.append (_email); buffer.append (">"); return buffer.toString (); } } public static class Changelog extends ProjectComponent { public static class Format extends EnumeratedAttribute { public String[] getValues () { // XML format will be added when supported return new String[] {"plain" /* , "xml" */}; } } private static final String STANDARD_FILENAME = "changelog.gz"; private static final String DEBIAN_FILENAME = "changelog.Debian.gz"; private String _file; private Changelog.Format _format; private boolean _debian; public Changelog() { _debian = false; _format = new Changelog.Format(); _format.setValue("plain"); } public void setFile (String file) { _file = file.trim (); } public String getFile() { return _file; } public void setFormat (Changelog.Format format) { _format = format; } public Changelog.Format getFormat() { return _format; } public void setDebian (boolean debian) { _debian = debian; } public boolean isDebian () { return _debian; } public String getTargetFilename () { return _debian ? DEBIAN_FILENAME : STANDARD_FILENAME; } } public static class Section extends EnumeratedAttribute { private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"}; private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"}; private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length); public Section () { for (int i = 0; i < PREFIXES.length; i++) { String prefix = PREFIXES[i]; for (int j = 0; j < BASIC_SECTIONS.length; j++) { String basicSection = BASIC_SECTIONS[j]; sections.add (prefix + basicSection); } } } public String[] getValues () { return (String[]) sections.toArray (new String[sections.size()]); } } public static class Priority extends EnumeratedAttribute { public String[] getValues () { return new String[] {"required", "important", "standard", "optional", "extra"}; } } private File _toDir; private String _debFilenameProperty = ""; private String _package; private String _version; private Deb.Version _versionObj; private String _section; private String _priority = "extra"; private String _architecture = "all"; private String _depends; private String _preDepends; private String _recommends; private String _suggests; private String _enhances; private String _conflicts; private String _provides; private String _replaces; private String _maintainer; private URL _homepage; private Deb.Maintainer _maintainerObj; private Deb.Description _description; private Set _conffiles = new HashSet (); private Set _changelogs = new HashSet (); private List _data = new ArrayList(); private File _preinst; private File _postinst; private File _prerm; private File _postrm; private File _config; private File _templates; private File _triggers; private File _tempFolder; private long _installedSize = 0; private SortedSet _dataFolders; private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod (); private static final Tar.TarLongFileMode GNU_LONGFILE_MODE = new Tar.TarLongFileMode (); static { GZIP_COMPRESSION_METHOD.setValue ("gzip"); GNU_LONGFILE_MODE.setValue(Tar.TarLongFileMode.GNU); } public void setToDir (File toDir) { _toDir = toDir; } public void setDebFilenameProperty(String debFilenameProperty) { _debFilenameProperty = debFilenameProperty.trim(); } public void setPackage (String packageName) { if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches()) throw new BuildException("Invalid package name!"); _package = packageName; } public void setVersion (String version) { _version = version; } public void setSection (Section section) { _section = section.getValue(); } public void setPriority (Priority priority) { _priority = priority.getValue(); } public void setArchitecture (String architecture) { _architecture = sanitize(architecture, _architecture); } public void setDepends (String depends) { _depends = sanitize(depends); } public void setPreDepends (String preDepends) { _preDepends = sanitize(preDepends); } public void setRecommends (String recommends) { _recommends = sanitize(recommends); } public void setSuggests (String suggests) { _suggests = sanitize(suggests); } public void setEnhances (String enhances) { _enhances = sanitize(enhances); } public void setConflicts (String conflicts) { _conflicts = sanitize(conflicts); } public void setProvides (String provides) { _provides = sanitize(provides); } public void setReplaces(String replaces) { _replaces = sanitize(replaces); } public void setMaintainer (String maintainer) { _maintainer = sanitize(maintainer); } public void setHomepage (String homepage) { try { _homepage = new URL (homepage); } catch (MalformedURLException e) { throw new BuildException ("Invalid homepage, must be a URL: " + homepage, e); } } public void setPreinst (File preinst) { _preinst = preinst; } public void setPostinst (File postinst) { _postinst = postinst; } public void setPrerm (File prerm) { _prerm = prerm; } public void setPostrm (File postrm) { _postrm = postrm; } public void setConfig (File config) { _config = config; } public void setTemplates (File templates) { _templates = templates; } public void setTriggers(File triggers) { _triggers = triggers; } public void addConfFiles (TarFileSet conffiles) { _conffiles.add (conffiles); _data.add (conffiles); } public void addChangelog(Deb.Changelog changelog) { _changelogs.add (changelog); } public void addDescription (Deb.Description description) { _description = description; } public void add (TarFileSet resourceCollection) { _data.add(resourceCollection); } public void addVersion(Deb.Version version) { _versionObj = version; } public void addMaintainer(Deb.Maintainer maintainer) { _maintainerObj = maintainer; } private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException { log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE); PrintWriter control = new UnixPrintWriter (controlFile); control.print ("Package: "); control.println (_package); control.print ("Version: "); control.println (_version); if (_section != null) { control.print ("Section: "); control.println (_section); } if (_priority != null) { control.print ("Priority: "); control.println (_priority); } control.print ("Architecture: "); control.println (_architecture); if (_depends != null) { control.print ("Depends: "); control.println (_depends); } if (_preDepends != null) { control.print ("Pre-Depends: "); control.println (_preDepends); } if (_recommends != null) { control.print ("Recommends: "); control.println (_recommends); } if (_suggests != null) { control.print ("Suggests: "); control.println (_suggests); } if (_enhances != null) { control.print ("Enhances: "); control.println (_enhances); } if (_conflicts != null) { control.print ("Conflicts: "); control.println (_conflicts); } if (_provides != null) { control.print ("Provides: "); control.println (_provides); } if (_replaces != null) { control.print ("Replaces: "); control.println (_replaces); } if (installedSize > 0) { control.print ("Installed-Size: "); control.println (installedSize / 1024L); } control.print ("Maintainer: "); control.println (_maintainer); if (_homepage != null) { control.print ("Homepage: "); control.println(_homepage.toExternalForm()); } control.print ("Description: "); control.println (_description.getSynopsis ()); control.println (_description.getExtendedFormatted ()); control.close (); } private File createMasterControlFile () throws IOException { File controlFile = new File (_tempFolder, "control"); writeControlFile (controlFile, _installedSize); File md5sumsFile = new File (_tempFolder, "md5sums"); File conffilesFile = new File (_tempFolder, "conffiles"); File masterControlFile = new File (_tempFolder, "control.tar.gz"); Tar controlTar = new Tar (); controlTar.setProject (getProject ()); controlTar.setTaskName (getTaskName ()); controlTar.setDestFile (masterControlFile); controlTar.setCompression (GZIP_COMPRESSION_METHOD); addFileToTar (controlTar, controlFile, "control", "644"); addFileToTar (controlTar, md5sumsFile, "md5sums", "644"); if (conffilesFile.length () > 0) addFileToTar (controlTar, conffilesFile, "conffiles", "644"); if (_preinst != null) addFileToTar (controlTar, _preinst, "preinst", "755"); if (_postinst != null) addFileToTar (controlTar, _postinst, "postinst", "755"); if (_prerm != null) addFileToTar (controlTar, _prerm, "prerm", "755"); if (_postrm != null) addFileToTar (controlTar, _postrm, "postrm", "755"); if (_config != null) addFileToTar (controlTar, _config, "config", "755"); if (_templates != null) addFileToTar (controlTar, _templates, "templates", "644"); if (_triggers != null) addFileToTar (controlTar, _triggers, "triggers", "644"); controlTar.perform (); deleteFileCheck(controlFile); return masterControlFile; } private void addFileToTar(Tar tar, File file, String fullpath, String fileMode) { TarFileSet controlFileSet = tar.createTarFileSet (); controlFileSet.setFile (file); controlFileSet.setFullpath ("./" + fullpath); controlFileSet.setFileMode (fileMode); controlFileSet.setUserName ("root"); controlFileSet.setGroup ("root"); } public void execute () throws BuildException { try { if (_versionObj != null) _version = _versionObj.toString (); if (_maintainerObj != null) _maintainer = _maintainerObj.toString (); _tempFolder = createTempFolder(); processChangelogs (); scanData (); File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb"); File dataFile = createDataFile (); File masterControlFile = createMasterControlFile (); log ("Writing deb file to: " + debFile.getAbsolutePath()); BuildDeb.buildDeb (debFile, masterControlFile, dataFile); if (_debFilenameProperty.length() > 0) getProject().setProperty(_debFilenameProperty, debFile.getAbsolutePath()); deleteFileCheck(masterControlFile); deleteFileCheck(dataFile); deleteFolderCheck(_tempFolder); } catch (IOException e) { throw new BuildException (e); } } private File createDataFile () throws IOException { File dataFile = new File (_tempFolder, "data.tar.gz"); Tar dataTar = new Tar (); dataTar.setProject (getProject ()); dataTar.setTaskName (getTaskName ()); dataTar.setDestFile (dataFile); dataTar.setCompression (GZIP_COMPRESSION_METHOD); dataTar.setLongfile(GNU_LONGFILE_MODE); if ( _data.size () > 0 ) { // add folders for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();) { String targetFolder = (String) dataFoldersIter.next (); TarFileSet targetFolderSet = dataTar.createTarFileSet (); targetFolderSet.setFile (_tempFolder); targetFolderSet.setFullpath (targetFolder); targetFolderSet.setUserName ("root"); targetFolderSet.setGroup ("root"); } // add actual data for (int i = 0; i < _data.size (); i++) { TarFileSet data = (TarFileSet) _data.get (i); if (data.getUserName() == null || data.getUserName().trim().length() == 0) data.setUserName ("root"); if (data.getGroup() == null || data.getGroup().trim().length() == 0) data.setGroup ("root"); dataTar.add (data); } dataTar.execute (); } else { // create an empty data.tar.gz file which is still a valid tar TarOutputStream tarStream = new TarOutputStream( new GZipOutputStream( new BufferedOutputStream(new FileOutputStream(dataFile)), Deflater.BEST_COMPRESSION ) ); tarStream.close(); } return dataFile; } private File createTempFolder() throws IOException { File tempFile = File.createTempFile ("deb", ".dir"); String tempFolderName = tempFile.getAbsolutePath (); deleteFileCheck(tempFile); tempFile = new File (tempFolderName, "removeme"); if (!tempFile.mkdirs ()) throw new IOException("Cannot create folder(s): " + tempFile.getAbsolutePath()); deleteFileCheck(tempFile); log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE); return new File (tempFolderName); } private void scanData() { try { Set existingDirs = new HashSet (); _installedSize = 0; PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums")); PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles")); _dataFolders = new TreeSet (); Iterator filesets = _data.iterator(); while (filesets.hasNext()) { TarFileSet fileset = (TarFileSet) filesets.next(); normalizeTargetFolder(fileset); String fullPath = fileset.getFullpath (getProject ()); String prefix = fileset.getPrefix (getProject ()); String [] fileNames = getFileNames(fileset); for (int i = 0; i < fileNames.length; i++) { String targetName; String fileName = fileNames[i]; File file = new File (fileset.getDir (getProject ()), fileName); if (fullPath.length () > 0) targetName = fullPath; else targetName = prefix + fileName; if (file.isDirectory ()) { log ("existing dir: " + targetName, Project.MSG_DEBUG); existingDirs.add (targetName); } else { // calculate installed size in bytes _installedSize += file.length (); // calculate and collect md5 sums md5sums.print (getFileMd5 (file)); md5sums.print (' '); md5sums.println (targetName.substring(2)); // get target folder names, and collect them (to be added to _data) File targetFile = new File(targetName); File parentFolder = targetFile.getParentFile (); while (parentFolder != null) { String parentFolderPath = parentFolder.getPath (); if (".".equals(parentFolderPath)) parentFolderPath = "./"; parentFolderPath = parentFolderPath.replace('\\', '/'); if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath)) { log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG); _dataFolders.add (parentFolderPath); } parentFolder = parentFolder.getParentFile (); } // write conffiles if (_conffiles.contains (fileset)) { // NOTE: targetName is "./path/file" so substring(1) removes the leading '.' conffiles.println (targetName.substring(1)); } } } } for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();) { String existingDir = (String) iterator.next (); if (_dataFolders.contains (existingDir)) { log ("removing existing dir " + existingDir, Project.MSG_DEBUG); _dataFolders.remove (existingDir); } } md5sums.close (); conffiles.close (); } catch (Exception e) { throw new BuildException (e); } } private void normalizeTargetFolder(TarFileSet fileset) { String fullPath = fileset.getFullpath (getProject ()); String prefix = fileset.getPrefix (getProject ()); if (fullPath.length() > 0) { if (fullPath.startsWith("/")) fullPath = "." + fullPath; else if (!fullPath.startsWith("./")) fullPath = "./" + fullPath; fileset.setFullpath(fullPath.replace('\\', '/')); } if (prefix.length() > 0) { if (!prefix.endsWith ("/")) prefix += '/'; if (prefix.startsWith("/")) prefix = "." + prefix; else if (!prefix.startsWith("./")) prefix = "./" + prefix; fileset.setPrefix(prefix.replace('\\', '/')); } } private String[] getFileNames(FileSet fs) { DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject()); String[] directories = ds.getIncludedDirectories(); String[] filesPerSe = ds.getIncludedFiles(); String[] files = new String [directories.length + filesPerSe.length]; System.arraycopy(directories, 0, files, 0, directories.length); System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length); return files; } private String getFileMd5(File file) { try { MessageDigest md5 = MessageDigest.getInstance ("MD5"); FileInputStream inputStream = new FileInputStream (file); byte[] buffer = new byte[1024]; while (true) { int read = inputStream.read (buffer); if (read == -1) break; md5.update (buffer, 0, read); } inputStream.close(); byte[] md5Bytes = md5.digest (); StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2); for (int i = 0; i < md5Bytes.length; i++) { String hex = Integer.toHexString (md5Bytes[i] & 0x00ff); if (hex.length () == 1) md5Buffer.append ('0'); md5Buffer.append (hex); } return md5Buffer.toString (); } catch (Exception e) { throw new BuildException(e); } } private void processChangelogs() throws IOException { for (Iterator iter = _changelogs.iterator (); iter.hasNext (); ) { processChangelog ((Deb.Changelog) iter.next ()); } } private void processChangelog (Deb.Changelog changelog) throws IOException { // Compress file File file = new File(changelog.getFile ()); File temp = File.createTempFile ("changelog", ".gz"); gzip(file, temp, Deflater.BEST_COMPRESSION, GZipOutputStream.FS_UNIX); // Determine path StringBuffer path = new StringBuffer ("usr/share/doc/"); path.append (_package).append ('/'); path.append (changelog.getTargetFilename ()); // Add file to data TarFileSet fileSet = new TarFileSet (); fileSet.setProject (getProject ()); fileSet.setFullpath (path.toString ()); fileSet.setFile (temp); fileSet.setFileMode ("0644"); _data.add (fileSet); } private static void gzip (File input, File output, int level, byte fileSystem) throws IOException { GZipOutputStream out = null; InputStream in = null; try { out = new GZipOutputStream (new FileOutputStream (output), level); out.setFileSystem (fileSystem); in = new FileInputStream(input); byte[] buffer = new byte[8 * 1024]; int len; while ((len = in.read (buffer, 0, buffer.length)) > 0) { out.write(buffer, 0, len); } out.finish (); } finally { if (in != null) { in.close (); } if (out != null) { out.close (); } } } private boolean deleteFolder(File folder) { if (folder.isDirectory()) { File[] children = folder.listFiles(); for (int i = 0; i < children.length; i++) { if (!deleteFolder(children[i])) return false; } } return folder.delete(); } private void deleteFolderCheck(File folder) throws IOException { if (!deleteFolder(folder)) throw new IOException("Cannot delete file: " + folder.getAbsolutePath()); } private void deleteFileCheck(File file) throws IOException { if (!file.delete ()) throw new IOException("Cannot delete file: " + file.getAbsolutePath()); } private String sanitize(String value) { return sanitize(value, null); } private String sanitize(String value, String defaultValue) { if (value == null) { return defaultValue; } value = value.trim(); return value.length() == 0 ? defaultValue : value; } }
package org.jtransfo; import org.jtransfo.internal.SyntheticField; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Abstract type converter for converting lists with object of specific type. Can only be used as declared converter. */ public abstract class AbstractListTypeConverter implements TypeConverter<List, List>, Named, NeedsJTransfo { private String name; private Class<?> toType; private JTransfo jTransfo; private boolean keepNullList; private boolean alwaysNewList; private boolean sortList; /** * Construct type converter for converting a list, assign given name and use given transfer object type. * * @param name name for type converter, for use in {@link MappedBy#typeConverter()} * @param toType transfer object type */ public AbstractListTypeConverter(String name, Class<?> toType) { this.name = name; this.toType = toType; } @Override public String getName() { return name; } @Override public void setJTransfo(JTransfo jTransfo) { this.jTransfo = jTransfo; } @Override public boolean canConvert(Class<?> realToType, Class<?> realDomainType) { return false; // never use automatically } /** * Do the actual conversion of one object. * * @param jTransfo jTransfo instance in use * @param toObject transfer object * @param domainObjectType domain object type * @return domain object * @throws JTransfoException oops, cannot convert */ public abstract Object doConvertOne(JTransfo jTransfo, Object toObject, Class<?> domainObjectType) throws JTransfoException; @Override public List convert(List toObjects, SyntheticField domainField, Object domainObject) throws JTransfoException { if (null == toObjects) { return getNullList(); } List<Object> res = newList(domainField, domainObject); for (Object to : toObjects) { res.add(doConvertOne(jTransfo, to, jTransfo.getDomainClass(to.getClass()))); } return res; } @Override public List reverse(List domainObjects, SyntheticField toField, Object toObject) throws JTransfoException { if (null == domainObjects) { return getNullList(); } List<Object> res = newList(toField, toObject); for (Object domain : domainObjects) { res.add(jTransfo.convertTo(domain, jTransfo.getToSubType(toType, domain))); } return sort(res); } private List<Object> newList(SyntheticField targetField, Object targetObject) { List<Object> res = null; if (!alwaysNewList && null != targetObject) { try { res = (List<Object>) targetField.get(targetObject); } catch (Exception exception) { res = null; // avoid problems in case of exception } } if (null != res) { res.clear(); } else { res = new ArrayList<Object>(); } return sort(res); } private List<Object> sort(List<Object> list) { if (sortList) { if (null != list && list.size() > 1 && list.get(0) instanceof Comparable) { Collections.sort((List) list); } } return list; } private List getNullList() { return keepNullList ? null : new ArrayList<Object>(); } /** * Set whether null values should be kept (true). When false (which is the default value), an empty list is set. * * @param keepNullList should null be kept as value or replaced by an empty list. */ public void setKeepNullList(boolean keepNullList) { this.keepNullList = keepNullList; } /** * Set whether a new list should be used to as container for the values. When false the list is reused if not null. * * @param alwaysNewList should null be kept as value or replaced by an empty list. */ public void setAlwaysNewList(boolean alwaysNewList) { this.alwaysNewList = alwaysNewList; } /** * Should the list be sorted if the first member is Comparable? * * @param sortList true when list should be sorted */ public void setSortList(boolean sortList) { this.sortList = sortList; } }
package io.branch.rnbranch; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.net.Uri; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.os.Handler; import com.facebook.react.bridge.*; import com.facebook.react.bridge.Promise; import com.facebook.react.modules.core.*; import com.facebook.react.bridge.ReadableMap; import io.branch.referral.*; import io.branch.referral.Branch.BranchLinkCreateListener; import io.branch.referral.util.*; import io.branch.referral.Branch; import io.branch.indexing.*; import org.json.*; import java.lang.ref.WeakReference; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class RNBranchModule extends ReactContextBaseJavaModule { public static final String REACT_CLASS = "RNBranch"; public static final String REACT_MODULE_NAME = "RNBranch"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT = "io.branch.rnbranch.RNBranchModule.onInitSessionFinished"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_BRANCH_UNIVERSAL_OBJECT = "branch_universal_object"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_LINK_PROPERTIES = "link_properties"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS = "params"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR = "error"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_URI = "uri"; private static final String RN_INIT_SESSION_SUCCESS_EVENT = "RNBranch.initSessionSuccess"; private static final String RN_INIT_SESSION_ERROR_EVENT = "RNBranch.initSessionError"; private static final String INIT_SESSION_SUCCESS = "INIT_SESSION_SUCCESS"; private static final String INIT_SESSION_ERROR = "INIT_SESSION_ERROR"; private static final String ADD_TO_CART_EVENT = "ADD_TO_CART_EVENT"; private static final String ADD_TO_WISHLIST_EVENT = "ADD_TO_WISHLIST_EVENT"; private static final String PURCHASED_EVENT = "PURCHASED_EVENT"; private static final String PURCHASE_INITIATED_EVENT = "PURCHASE_INITIATED_EVENT"; private static final String REGISTER_VIEW_EVENT = "REGISTER_VIEW_EVENT"; private static final String SHARE_COMPLETED_EVENT = "SHARE_COMPLETED_EVENT"; private static final String SHARE_INITIATED_EVENT = "SHARE_INITIATED_EVENT"; private static final String IDENT_FIELD_NAME = "ident"; public static final String UNIVERSAL_OBJECT_NOT_FOUND_ERROR_CODE = "RNBranch::Error::BUONotFound"; private static final long AGING_HASH_TTL = 3600000; private static JSONObject initSessionResult = null; private BroadcastReceiver mInitSessionEventReceiver = null; private static WeakReference<Branch.BranchUniversalReferralInitListener> initListener = null; private static Activity mActivity = null; private static boolean mUseDebug = false; private AgingHash<String, BranchUniversalObject> mUniversalObjectMap = new AgingHash<>(AGING_HASH_TTL); public static void initSession(final Uri uri, Activity reactActivity, Branch.BranchUniversalReferralInitListener anInitListener) { initListener = new WeakReference<>(anInitListener); initSession(uri, reactActivity); } public static void initSession(final Uri uri, Activity reactActivity) { Branch branch = Branch.getInstance(reactActivity.getApplicationContext()); if (mUseDebug) branch.setDebug(); mActivity = reactActivity; branch.initSession(new Branch.BranchReferralInitListener(){ private Activity mmActivity = null; @Override public void onInitFinished(JSONObject referringParams, BranchError error) { Log.d(REACT_CLASS, "onInitFinished"); JSONObject result = new JSONObject(); Uri referringUri = null; try{ boolean clickedBranchLink = false; // getXXX throws. It's OK for these to be missing. try { clickedBranchLink = referringParams.getBoolean("+clicked_branch_link"); } catch (JSONException e) { } String referringLink = null; if (clickedBranchLink) { try { referringLink = referringParams.getString("~referring_link"); } catch (JSONException e) { } } else { try { referringLink = referringParams.getString("+non_branch_link"); } catch (JSONException e) { } } if (referringLink != null) referringUri = Uri.parse(referringLink); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS, referringParams); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR, error != null ? error.getMessage() : JSONObject.NULL); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_URI, referringLink != null ? referringLink : JSONObject.NULL); } catch(JSONException ex) { try { result.put("error", "Failed to convert result to JSONObject: " + ex.getMessage()); } catch(JSONException k) {} } initSessionResult = result; BranchUniversalObject branchUniversalObject = BranchUniversalObject.getReferredBranchUniversalObject(); LinkProperties linkProperties = LinkProperties.getReferredLinkProperties(); if (initListener != null) { Branch.BranchUniversalReferralInitListener listener = initListener.get(); if (listener != null) listener.onInitFinished(branchUniversalObject, linkProperties, error); } generateLocalBroadcast(referringParams, referringUri, branchUniversalObject, linkProperties, error); } private Branch.BranchReferralInitListener init(Activity activity) { mmActivity = activity; return this; } private void generateLocalBroadcast(JSONObject referringParams, Uri uri, BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) { Intent broadcastIntent = new Intent(NATIVE_INIT_SESSION_FINISHED_EVENT); if (referringParams != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS, referringParams.toString()); } if (branchUniversalObject != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_BRANCH_UNIVERSAL_OBJECT, branchUniversalObject); } if (linkProperties != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_LINK_PROPERTIES, linkProperties); } if (uri != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_URI, uri.toString()); } if (error != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR, error.getMessage()); } LocalBroadcastManager.getInstance(mmActivity).sendBroadcast(broadcastIntent); } }.init(reactActivity), uri, reactActivity); } public static void setDebug() { mUseDebug = true; } public RNBranchModule(ReactApplicationContext reactContext) { super(reactContext); forwardInitSessionFinishedEventToReactNative(reactContext); } @javax.annotation.Nullable @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); // RN events transmitted to JS constants.put(INIT_SESSION_SUCCESS, RN_INIT_SESSION_SUCCESS_EVENT); constants.put(INIT_SESSION_ERROR, RN_INIT_SESSION_ERROR_EVENT); // Constants for use with userCompletedAction constants.put(ADD_TO_CART_EVENT, BranchEvent.ADD_TO_CART); constants.put(ADD_TO_WISHLIST_EVENT, BranchEvent.ADD_TO_WISH_LIST); constants.put(PURCHASED_EVENT, BranchEvent.PURCHASED); constants.put(PURCHASE_INITIATED_EVENT, BranchEvent.PURCHASE_STARTED); constants.put(REGISTER_VIEW_EVENT, BranchEvent.VIEW); constants.put(SHARE_COMPLETED_EVENT, BranchEvent.SHARE_COMPLETED); constants.put(SHARE_INITIATED_EVENT, BranchEvent.SHARE_STARTED); return constants; } private void forwardInitSessionFinishedEventToReactNative(ReactApplicationContext reactContext) { mInitSessionEventReceiver = new BroadcastReceiver() { RNBranchModule mBranchModule; @Override public void onReceive(Context context, Intent intent) { final String eventName = initSessionResult.has("error") ? RN_INIT_SESSION_ERROR_EVENT : RN_INIT_SESSION_SUCCESS_EVENT; mBranchModule.sendRNEvent(eventName, convertJsonToMap(initSessionResult)); } private BroadcastReceiver init(RNBranchModule branchModule) { mBranchModule = branchModule; return this; } }.init(this); LocalBroadcastManager.getInstance(reactContext).registerReceiver(mInitSessionEventReceiver, new IntentFilter(NATIVE_INIT_SESSION_FINISHED_EVENT)); } @Override public void onCatalystInstanceDestroy() { LocalBroadcastManager.getInstance(getReactApplicationContext()).unregisterReceiver(mInitSessionEventReceiver); } @Override public String getName() { return REACT_MODULE_NAME; } @ReactMethod public void createUniversalObject(ReadableMap universalObjectMap, Promise promise) { String ident = UUID.randomUUID().toString(); BranchUniversalObject universalObject = createBranchUniversalObject(universalObjectMap); mUniversalObjectMap.put(ident, universalObject); WritableMap response = new WritableNativeMap(); response.putString(IDENT_FIELD_NAME, ident); promise.resolve(response); } @ReactMethod public void releaseUniversalObject(String ident) { mUniversalObjectMap.remove(ident); } @ReactMethod public void redeemInitSessionResult(Promise promise) { promise.resolve(convertJsonToMap(initSessionResult)); } @ReactMethod public void getLatestReferringParams(Promise promise) { Branch branch = Branch.getInstance(); promise.resolve(convertJsonToMap(branch.getLatestReferringParams())); } @ReactMethod public void getFirstReferringParams(Promise promise) { Branch branch = Branch.getInstance(); promise.resolve(convertJsonToMap(branch.getFirstReferringParams())); } @ReactMethod public void setIdentity(String identity) { Branch branch = Branch.getInstance(); branch.setIdentity(identity); } @ReactMethod public void logout() { Branch branch = Branch.getInstance(); branch.logout(); } @ReactMethod public void userCompletedAction(String event, ReadableMap appState) throws JSONException { Branch branch = Branch.getInstance(); branch.userCompletedAction(event, convertMapToJson(appState)); } @ReactMethod public void userCompletedActionOnUniversalObject(String ident, String event, ReadableMap state, Promise promise) { BranchUniversalObject universalObject = findUniversalObjectOrReject(ident, promise); if (universalObject == null) return; universalObject.userCompletedAction(event, convertMapToParams(state)); promise.resolve(null); } @ReactMethod public void showShareSheet(String ident, ReadableMap shareOptionsMap, ReadableMap linkPropertiesMap, ReadableMap controlParamsMap, Promise promise) { Context context = getReactApplicationContext(); Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() { Promise mPm; Context mContext; ReadableMap shareOptionsMap, linkPropertiesMap, controlParamsMap; String ident; private Runnable init(ReadableMap _shareOptionsMap, String _ident, ReadableMap _linkPropertiesMap, ReadableMap _controlParamsMap, Promise promise, Context context) { mPm = promise; mContext = context; shareOptionsMap = _shareOptionsMap; ident = _ident; linkPropertiesMap = _linkPropertiesMap; controlParamsMap = _controlParamsMap; return this; } @Override public void run() { String messageHeader = shareOptionsMap.hasKey("messageHeader") ? shareOptionsMap.getString("messageHeader") : ""; String messageBody = shareOptionsMap.hasKey("messageBody") ? shareOptionsMap.getString("messageBody") : ""; ShareSheetStyle shareSheetStyle = new ShareSheetStyle(mContext, messageHeader, messageBody) .setCopyUrlStyle(mContext.getResources().getDrawable(android.R.drawable.ic_menu_send), "Copy", "Added to clipboard") .setMoreOptionStyle(mContext.getResources().getDrawable(android.R.drawable.ic_menu_search), "Show more") .addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL) .addPreferredSharingOption(SharingHelper.SHARE_WITH.TWITTER) .addPreferredSharingOption(SharingHelper.SHARE_WITH.MESSAGE) .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK); BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, mPm); if (branchUniversalObject == null) { return; } LinkProperties linkProperties = createLinkProperties(linkPropertiesMap, controlParamsMap); branchUniversalObject.showShareSheet( getCurrentActivity(), linkProperties, shareSheetStyle, new Branch.BranchLinkShareListener() { private Promise mPromise = null; @Override public void onShareLinkDialogLaunched() { } @Override public void onShareLinkDialogDismissed() { if(mPromise == null) { return; } WritableMap map = new WritableNativeMap(); map.putString("channel", null); map.putBoolean("completed", false); map.putString("error", null); mPromise.resolve(map); mPromise = null; } @Override public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) { if(mPromise == null) { return; } WritableMap map = new WritableNativeMap(); map.putString("channel", sharedChannel); map.putBoolean("completed", true); map.putString("error", (error != null ? error.getMessage() : null)); mPromise.resolve(map); mPromise = null; } @Override public void onChannelSelected(String channelName) { } private Branch.BranchLinkShareListener init(Promise promise) { mPromise = promise; return this; } }.init(mPm)); } }.init(shareOptionsMap, ident, linkPropertiesMap, controlParamsMap, promise, context); mainHandler.post(myRunnable); } @ReactMethod public void registerView(String ident, Promise promise) { BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, promise); if (branchUniversalObject == null) { return; } branchUniversalObject.registerView(); promise.resolve(null); } @ReactMethod public void generateShortUrl(String ident, ReadableMap linkPropertiesMap, ReadableMap controlParamsMap, final Promise promise) { LinkProperties linkProperties = createLinkProperties(linkPropertiesMap, controlParamsMap); BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, promise); if (branchUniversalObject == null) { return; } branchUniversalObject.generateShortUrl(mActivity, linkProperties, new BranchLinkCreateListener() { @Override public void onLinkCreate(String url, BranchError error) { Log.d(REACT_CLASS, "onLinkCreate " + url); WritableMap map = new WritableNativeMap(); map.putString("url", url); if (error != null) { map.putString("error", error.toString()); } promise.resolve(map); } }); } public static LinkProperties createLinkProperties(ReadableMap linkPropertiesMap, @Nullable ReadableMap controlParams){ LinkProperties linkProperties = new LinkProperties(); if (linkPropertiesMap.hasKey("alias")) linkProperties.setAlias(linkPropertiesMap.getString("alias")); if (linkPropertiesMap.hasKey("campaign")) linkProperties.setCampaign(linkPropertiesMap.getString("campaign")); if (linkPropertiesMap.hasKey("channel")) linkProperties.setChannel(linkPropertiesMap.getString("channel")); if (linkPropertiesMap.hasKey("feature")) linkProperties.setFeature(linkPropertiesMap.getString("feature")); if (linkPropertiesMap.hasKey("stage")) linkProperties.setStage(linkPropertiesMap.getString("stage")); if (linkPropertiesMap.hasKey("tags")) { ReadableArray tags = linkPropertiesMap.getArray("tags"); for (int i=0; i<tags.size(); ++i) { String tag = tags.getString(i); linkProperties.addTag(tag); } } if (controlParams != null) { ReadableMapKeySetIterator iterator = controlParams.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); Object value = getReadableMapObjectForKey(controlParams, key); linkProperties.addControlParameter(key, value.toString()); } } return linkProperties; } private BranchUniversalObject findUniversalObjectOrReject(final String ident, final Promise promise) { BranchUniversalObject universalObject = mUniversalObjectMap.get(ident); if (universalObject == null) { final String errorMessage = "BranchUniversalObject not found for ident " + ident + "."; promise.reject(UNIVERSAL_OBJECT_NOT_FOUND_ERROR_CODE, errorMessage); } return universalObject; } public BranchUniversalObject createBranchUniversalObject(ReadableMap branchUniversalObjectMap) { BranchUniversalObject branchUniversalObject = new BranchUniversalObject() .setCanonicalIdentifier(branchUniversalObjectMap.getString("canonicalIdentifier")); if (branchUniversalObjectMap.hasKey("title")) branchUniversalObject.setTitle(branchUniversalObjectMap.getString("title")); if (branchUniversalObjectMap.hasKey("canonicalUrl")) branchUniversalObject.setCanonicalUrl(branchUniversalObjectMap.getString("canonicalUrl")); if (branchUniversalObjectMap.hasKey("contentDescription")) branchUniversalObject.setContentDescription(branchUniversalObjectMap.getString("contentDescription")); if (branchUniversalObjectMap.hasKey("contentImageUrl")) branchUniversalObject.setContentImageUrl(branchUniversalObjectMap.getString("contentImageUrl")); if (branchUniversalObjectMap.hasKey("contentIndexingMode")) { switch (branchUniversalObjectMap.getType("contentIndexingMode")) { case String: String mode = branchUniversalObjectMap.getString("contentIndexingMode"); if (mode.equals("private")) branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); else if (mode.equals("public")) branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC); else Log.w(REACT_CLASS, "Unsupported value for contentIndexingMode: " + mode + ". Supported values are \"public\" and \"private\""); break; default: Log.w(REACT_CLASS, "contentIndexingMode must be a String"); break; } } if (branchUniversalObjectMap.hasKey("currency") && branchUniversalObjectMap.hasKey("price")) { String currencyString = branchUniversalObjectMap.getString("currency"); CurrencyType currency = CurrencyType.valueOf(currencyString); branchUniversalObject.setPrice(branchUniversalObjectMap.getDouble("price"), currency); } if (branchUniversalObjectMap.hasKey("expirationDate")) { String expirationString = branchUniversalObjectMap.getString("expirationDate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date date = format.parse(expirationString); Log.d(REACT_CLASS, "Expiration date is " + date.toString()); branchUniversalObject.setContentExpiration(date); } catch (ParseException e) { Log.w(REACT_CLASS, "Invalid expiration date format. Valid format is YYYY-mm-ddTHH:MM:SS, e.g. 2017-02-01T00:00:00. All times UTC."); } } if (branchUniversalObjectMap.hasKey("keywords")) { ReadableArray keywords = branchUniversalObjectMap.getArray("keywords"); for (int i=0; i<keywords.size(); ++i) { branchUniversalObject.addKeyWord(keywords.getString(i)); } } if(branchUniversalObjectMap.hasKey("metadata")) { ReadableMap metadataMap = branchUniversalObjectMap.getMap("metadata"); ReadableMapKeySetIterator iterator = metadataMap.keySetIterator(); while (iterator.hasNextKey()) { String metadataKey = iterator.nextKey(); Object metadataObject = getReadableMapObjectForKey(metadataMap, metadataKey); branchUniversalObject.addContentMetadata(metadataKey, metadataObject.toString()); } } if (branchUniversalObjectMap.hasKey("type")) branchUniversalObject.setContentType(branchUniversalObjectMap.getString("type")); return branchUniversalObject; } @ReactMethod public void redeemRewards(int value, String bucket, Promise promise) { if (bucket == null) { Branch.getInstance().redeemRewards(value, new RedeemRewardsListener(promise)); } else { Branch.getInstance().redeemRewards(bucket, value, new RedeemRewardsListener(promise)); } } @ReactMethod public void loadRewards(Promise promise) { Branch.getInstance().loadRewards(new LoadRewardsListener(promise)); } @ReactMethod public void getCreditHistory(Promise promise) { Branch.getInstance().getCreditHistory(new CreditHistoryListener(promise)); } protected class CreditHistoryListener implements Branch.BranchListResponseListener { private Promise _promise; // Constructor that takes in a required callbackContext object public CreditHistoryListener(Promise promise) { this._promise = promise; } // Listener that implements BranchListResponseListener for getCreditHistory() @Override public void onReceivingResponse(JSONArray list, BranchError error) { ArrayList<String> errors = new ArrayList<String>(); if (error == null) { try { ReadableArray result = convertJsonToArray(list); this._promise.resolve(result); } catch (JSONException err) { this._promise.reject(err.getMessage()); } } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } protected class RedeemRewardsListener implements Branch.BranchReferralStateChangedListener { private Promise _promise; public RedeemRewardsListener(Promise promise) { this._promise = promise; } @Override public void onStateChanged(boolean changed, BranchError error) { if (error == null) { WritableMap map = new WritableNativeMap(); map.putBoolean("changed", changed); this._promise.resolve(map); } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } protected class LoadRewardsListener implements Branch.BranchReferralStateChangedListener { private Promise _promise; public LoadRewardsListener(Promise promise) { this._promise = promise; } @Override public void onStateChanged(boolean changed, BranchError error) { if (error == null) { int credits = Branch.getInstance().getCredits(); WritableMap map = new WritableNativeMap(); map.putInt("credits", credits); this._promise.resolve(map); } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } public void sendRNEvent(String eventName, @Nullable WritableMap params) { // This should avoid the crash in getJSModule() at startup ReactApplicationContext context = getReactApplicationContext(); Handler mainHandler = new Handler(context.getMainLooper()); Runnable poller = new Runnable() { private Runnable init(ReactApplicationContext _context, Handler _mainHandler, String _eventName, WritableMap _params) { mMainHandler = _mainHandler; mEventName = _eventName; mContext = _context; mParams = _params; return this; } final int pollDelayInMs = 100; final int maxTries = 300; int tries = 1; String mEventName; WritableMap mParams; Handler mMainHandler; ReactApplicationContext mContext; @Override public void run() { try { Log.d(REACT_CLASS, "Catalyst instance poller try " + Integer.toString(tries)); if (mContext.hasActiveCatalystInstance()) { Log.d(REACT_CLASS, "Catalyst instance active"); mContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(mEventName, mParams); } else { tries++; if (tries <= maxTries) { mMainHandler.postDelayed(this, pollDelayInMs); } else { Log.e(REACT_CLASS, "Could not get Catalyst instance"); } } } catch (Exception e) { e.printStackTrace(); } } }.init(context, mainHandler, eventName, params); Log.d(REACT_CLASS, "sendRNEvent"); mainHandler.post(poller); } private static Object getReadableMapObjectForKey(ReadableMap readableMap, String key) { switch(readableMap.getType(key)) { case Null: return "Null"; case Boolean: return readableMap.getBoolean(key); case Number: return readableMap.getDouble(key); case String: return readableMap.getString(key); default: return "Unsupported Type"; } } private static JSONObject convertMapToJson(ReadableMap readableMap) throws JSONException { JSONObject object = new JSONObject(); ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); switch (readableMap.getType(key)) { case Null: object.put(key, JSONObject.NULL); break; case Boolean: object.put(key, readableMap.getBoolean(key)); break; case Number: object.put(key, readableMap.getDouble(key)); break; case String: object.put(key, readableMap.getString(key)); break; case Map: object.put(key, convertMapToJson(readableMap.getMap(key))); break; case Array: object.put(key, convertArrayToJson(readableMap.getArray(key))); break; } } return object; } private static JSONArray convertArrayToJson(ReadableArray readableArray) throws JSONException { JSONArray array = new JSONArray(); for (int i = 0; i < readableArray.size(); i++) { switch (readableArray.getType(i)) { case Null: break; case Boolean: array.put(readableArray.getBoolean(i)); break; case Number: array.put(readableArray.getDouble(i)); break; case String: array.put(readableArray.getString(i)); break; case Map: array.put(convertMapToJson(readableArray.getMap(i))); break; case Array: array.put(convertArrayToJson(readableArray.getArray(i))); break; } } return array; } private static WritableMap convertJsonToMap(JSONObject jsonObject) { if(jsonObject == null) { return null; } WritableMap map = new WritableNativeMap(); try { Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); if (value instanceof JSONObject) { map.putMap(key, convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { map.putArray(key, convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { map.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { map.putInt(key, (Integer) value); } else if (value instanceof Double) { map.putDouble(key, (Double) value); } else if (value instanceof String) { map.putString(key, (String) value); } else if (value == null || value == JSONObject.NULL) { map.putNull(key); } else { map.putString(key, value.toString()); } } } catch(JSONException ex) { map.putString("error", "Failed to convert JSONObject to WriteableMap: " + ex.getMessage()); } return map; } private static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException { WritableArray array = new WritableNativeArray(); for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); if (value instanceof JSONObject) { array.pushMap(convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { array.pushArray(convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { array.pushBoolean((Boolean) value); } else if (value instanceof Integer) { array.pushInt((Integer) value); } else if (value instanceof Double) { array.pushDouble((Double) value); } else if (value instanceof String) { array.pushString((String) value); } else { array.pushString(value.toString()); } } return array; } // Convert an arbitrary ReadableMap to a string-string hash of custom params for userCompletedAction. private static HashMap<String, String> convertMapToParams(ReadableMap map) { if (map == null) return null; HashMap<String, String> hash = new HashMap<>(); ReadableMapKeySetIterator iterator = map.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); switch (map.getType(key)) { case String: hash.put(key, map.getString(key)); case Boolean: hash.put(key, "" + map.getBoolean(key)); case Number: hash.put(key, "" + map.getDouble(key)); default: Log.w(REACT_CLASS, "Unsupported data type in params, ignoring"); } } return hash; } }
package com.jme.animation; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.jme.scene.Controller; import com.jme.scene.Spatial; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; /** * BoneAnimation defines a component that manipulates the position of a * skeletal system based on a collection of keyframes. * In the simplest case, BoneAnimation directly affects a single * bone, and the skeletal system is a tree (skeleton) of these BoneAnimations. * The BoneAnimation is defined with an array of keyframe times and a * BoneTransform for each bone directly controlled. * The animations can have a heirarchical composition, and at any level the * animation may not control a bone, but simply control sub-animations. * * In a typical application, the skeletal tree described above is collapsed * down so that only one BoneAnimation object is used at display-time. * * Though it implements no interface, the intention is that an update method * of this class should be called by a Controller. * * @see #optimize * @see BoneTransform * @see Controller * @see #update */ public class BoneAnimation implements Serializable, Savable { /* TODO: Rename the private field name which have names which indicate * the wrong plurality. E.g. "keyframeTime" does not hold a time, it * holds a list of times, and should therefore be named "keyframeTimes", * analogously to the public methods for this same item. * ARG: Looks like at least one of these misleading field names is * persisted, so probably neeed to retain the persisted name for backward * compatibility, even though it is misleading. We can, nevertheless, * correct the variable names. */ private static final Logger logger = Logger.getLogger(BoneAnimation.class .getName()); private static final float DEFAULT_RATE = 1f / 20f; public static final int LINEAR = 0; public static final int BEZIER = 1; private static final long serialVersionUID = 1L; // values defining how the controller will interact with the bone private String name; private float[] keyframeTime = null; private int[] interpolationType = null; private ArrayList<BoneTransform> boneTransforms; // values defining start and end frames, and where we currently are // in the animation. private float currentTime; private int currentFrame = 1; private int prevFrame = 0; private int endFrame; private int startFrame; private int lastEventFrame; private float interpolationRate = DEFAULT_RATE; private float lastTime; private int cycleMode = 1; // children animations of this animation private ArrayList<BoneAnimation> children; private HashMap<String, int[]> syncTags; // used if this animation allows the root bone to update the translation of // the model node. private Bone sourceBone; private Spatial destSpatial; private AnimationProperties props; public BoneAnimation() { } /** * Contructor creates a new animation. The name is the name of the * animation. * * @param name * the name of the animation. */ public BoneAnimation(String name) { this.name = name; } /** * Creates a new, linear-interpolating BoneAnimation with a name, * the bone it will control and the number of keyframes it will have. * * @param name * the name of the animation * @param bone * the bone the animation affects * @param numKeyframes * the number of keyframes the animation has. */ public BoneAnimation(String name, Bone bone, int numKeyframes) { this.name = name; keyframeTime = new float[numKeyframes]; setInterpolate(true); } /** * addBoneAnimation adds a child animation to this animation. This * child's update will be called with the parent's. * * @param ba * the child animation to add to this animation. */ public void addBoneAnimation(BoneAnimation ba) { if (children == null) { children = new ArrayList<BoneAnimation>(); } children.add(ba); } /** * adds an AnimationEvent to this animation for a specified frame. * * @param frame * the frame number to trigger the event. * @param event * the event to trigger. */ public void addEvent(int frame, AnimationEvent event) { AnimationEventManager.getInstance().addAnimationEvent(this, frame, event); } /** * add a sync tag to this animation. * * @param name * the name of the sync tag. * @param frames * the frames that are tied to this sync tag. */ public void addSync(String name, int[] frames) { if (syncTags == null) { syncTags = new HashMap<String, int[]>(); } syncTags.put(name, frames); } public int[] getSyncFrames(String name) { if (syncTags != null) { return syncTags.get(name); } return null; } public boolean containsSyncTags() { if (syncTags == null) { return false; } return (syncTags.keySet().size() > 0); } public Set<String> getAllSyncTags() { if (syncTags == null) { return null; } return syncTags.keySet(); } public ArrayList<String> getSyncNames(int frame) { if (syncTags != null) { Set<String> names = syncTags.keySet(); int[] frames = null; ArrayList<String> nameList = new ArrayList<String>(); for (String name : names) { frames = syncTags.get(name); if (frames != null) { if (Arrays.binarySearch(frames, frame) > 0) { nameList.add(name); } } } return nameList; } return null; } public void setInitialFrame(int frame) { if (frame >= endFrame) { currentFrame = frame; prevFrame = currentFrame - 1; } else { prevFrame = frame; currentFrame = prevFrame + 1; } currentTime = keyframeTime[currentFrame]; // call the children of this animation if any if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).setInitialFrame(frame); } } } /** * setCurrentFrame will set the current position of the animation to the * supplied frame. If the frame is outside of the start/end frame subset, * the frame will work towards the start frame. * * @param frame * the frame to set the current animation frame to. */ public void setCurrentFrame(int frame) { if (prevFrame == frame) { return; } if (keyframeTime != null) { if (frame >= keyframeTime.length + 1 || frame < 0) { logger.log(Level.SEVERE, "{0}: Invalid frame index {1}. " + "Intialized to only " + "have: {2} keyframes." , new Object[] {name, frame, keyframeTime.length}); return; } // because we interpolate we are working towards the current frame. prevFrame = frame; if (prevFrame < keyframeTime.length - 1) { currentFrame = prevFrame + 1; } else { currentFrame = startFrame; } currentTime = keyframeTime[prevFrame]; // set the bone to the current frame if (boneTransforms != null) { for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).setCurrentFrame(currentFrame); } } } changeFrame(currentFrame); // call the children of this animation if any if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).setCurrentFrame(frame); } } } /** * change frame determines if a new frame is selected and performs any * triggers that might be assigned to this frame. * * @param frame * the current frame. */ private void changeFrame(int frame) { if(frame == 0 ) { logger.finest("0"); } if (frame != lastEventFrame) { ArrayList<AnimationEvent> eventList = AnimationEventManager .getInstance().getAnimationEventList(this, frame); if (eventList != null) { for (int i = 0, max = eventList.size(); i < max; i++) { eventList.get(i).performAction(); } } lastEventFrame = frame; } } /** * addBoneTransform adds a bone transform array pair that this bone * animation uses to update. This BoneTransform is added to the * list of bone transforms currently in place. * * @param bt * the BoneTransform to add to this list. */ public void addBoneTransforms(BoneTransform bt) { if (boneTransforms == null) { boneTransforms = new ArrayList<BoneTransform>(); } this.boneTransforms.add(bt); } /** * update is called during the update phase of the game cycle. * If this animation is not active, this method immediately * returns. The update of the bone is dependent on the repeat type * (see 'repeat' param below). * This version of update() does not support Blending. * * @param time * The time * supplied is the time between frames (normally) and this is used to define * what frame of animation we should be at and how to interpolate between * frames. * @param repeat * <code>Controller.RT_CLAMP</code> * will cause the bones to animate through a single cycle and stop. * <code>Controller.RT_CYCLE</code> * will cause the animation to reverse when it reaches one of the ends * of the cycle. * <code>Controller.RT_WRAP</code> * will start the animation over from the beginning. * * @see update(float, int, float, float) * @see Controller */ public void update(float time, int repeat, float speed) { if (boneTransforms != null && keyframeTime != null) { if (endFrame >= keyframeTime.length) { endFrame = keyframeTime.length - 1; } int oldFrame = currentFrame; if (updateCurrentTime(time, repeat, speed)) { if (interpolationType != null) { lastTime += time; if (lastTime >= interpolationRate) { if (interpolationRate > 0) { lastTime = lastTime % interpolationRate; } else { lastTime = 0.0f; } float result = (currentTime - keyframeTime[prevFrame]) / (keyframeTime[currentFrame] - keyframeTime[prevFrame]); for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).update(prevFrame, currentFrame, interpolationType[prevFrame], result); } } } else if (oldFrame != currentFrame) { if(props == null || !props.isAllowTranslation()) { for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).setCurrentFrame(currentFrame); } } else { for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).setCurrentFrame(currentFrame, sourceBone, destSpatial, estimateCallsPerFrame(time), props); } } } } } changeFrame(currentFrame); // update the children! if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).update(time, repeat, speed); } } } private float estimateCallsPerFrame(float time) { return (keyframeTime[currentFrame] - keyframeTime[prevFrame]) / time; } /** * This method of update() supports Blending. * * @see #update(float, int, float) */ public void update(float time, int repeat, float speed, float blendRate) { if (boneTransforms != null && keyframeTime != null) { if (endFrame >= keyframeTime.length) { endFrame = keyframeTime.length - 1; } if (updateCurrentTime(time, repeat, speed)) { if (interpolationType != null) { lastTime += time; if (lastTime >= interpolationRate) { if (interpolationRate > 0) { lastTime = lastTime % interpolationRate; } else { lastTime = 0.0f; } float result = (currentTime - keyframeTime[prevFrame]) / (keyframeTime[currentFrame] - keyframeTime[prevFrame]); for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).update(prevFrame, currentFrame, interpolationType[prevFrame], result, blendRate); } } } else { if(props == null || !props.isAllowTranslation()) { for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).setCurrentFrame(currentFrame, blendRate); } } else { for (int i = 0; i < boneTransforms.size(); i++) { boneTransforms.get(i).setCurrentFrame(currentFrame, blendRate, sourceBone, destSpatial, estimateCallsPerFrame(time), props); } } } } } changeFrame(currentFrame); // update the children! if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).update(time, repeat, speed, blendRate); } } } private boolean updateCurrentTime(float time, int repeat, float speed) { switch (repeat) { case Controller.RT_CLAMP: { if (currentFrame > endFrame) return false; // Use currentFrame of endFrame + 1 to indicated animation DONE currentTime += time * speed; if (currentTime > keyframeTime[endFrame]) { currentFrame = endFrame + 1; currentTime = 0; return false; } while (currentTime >= keyframeTime[currentFrame]) { currentFrame++; prevFrame++; } break; } case Controller.RT_CYCLE: { currentTime += time * speed * cycleMode; if (currentTime > keyframeTime[endFrame]) { cycleMode = -1; currentTime -= 2 * (currentTime - keyframeTime[endFrame]); // Hoping that setting the start/end frames this way allows // the while loops below to adjust them correctly currentFrame = endFrame; prevFrame = endFrame + 1; } else if (currentTime < keyframeTime[startFrame]) { cycleMode = 1; currentTime += 2 * (keyframeTime[startFrame] - currentTime); // See comment above about start/end frames. currentFrame = startFrame + 1; prevFrame = startFrame; } if (cycleMode == 1) { while (currentTime > keyframeTime[currentFrame]) { currentFrame += cycleMode; prevFrame += cycleMode; } } else { while (currentTime < keyframeTime[currentFrame]) { currentFrame += cycleMode; prevFrame += cycleMode; } } break; } case Controller.RT_WRAP: { currentTime += time * speed; if (currentFrame >= endFrame) { currentTime += keyframeTime[startFrame] - keyframeTime[endFrame]; currentFrame = startFrame + 1; prevFrame = startFrame; return true; } while (currentTime > keyframeTime[currentFrame] && currentFrame < endFrame) { currentFrame++; prevFrame++; } break; } } return true; } /** * returns true if this animation is valid (i.e. contains valid information) * * @return */ public boolean isValid() { // TODO: Check *.length == *.length for the per-frame array fields. if (keyframeTime != null) return false; if (boneTransforms != null) return false; if (interpolationType == null) return true; // TODO: Consider iterating through all boneTransofrms and checking // length so the rotation and translation arrays of each. // These should match our keyframeTime.length return interpolationType.length == keyframeTime.length; } /** * returns the number of children animations that are attached to this * animation. * * @return the number of children animations this bone animation * is responsible for. */ public int subanimationCount() { if (children != null) { return children.size(); } else { return 0; } } /** * returns a child animation from a given index. If the index is * invalid, null is returned. * * @param i the index to obtain the animation. * @return the animation at a given index, null if the index is invalid. */ public BoneAnimation getSubanimation(int i) { if (children == null) { return null; } if (i >= children.size() || i < 0) { return null; } return children.get(i); } /** * Sets the times array for the keyframes. This array should be the same * size as the transforms array and the types array. This is left to the * user to insure, if they are not the same, an ArrayIndexOutOfBounds * exception will be thrown during update. * * @param times * the times to set. */ public void setTimes(float[] times) { this.keyframeTime = times; } /** * Sets the interpolation types array for the keyframes. This array should * be the same size as the transforms array and the types array. This is * left to the user to insure, if they are not the same, an * ArrayIndexOutOfBounds exception will be thrown during update. * <P> * If the interpolation type array is null, interpolation work will be * skipped (performance benefit if interpolation not required). * </P> * * @param types * the interpolation types to set, or null for no interpolation. */ public void setInterpolationTypes(int[] types) { this.interpolationType = types; } /** * returns the name of this animation. * * @return the name of this animation */ public String getName() { return name; } /** * sets the name of this animation. * * @param name * the name of this animation. */ public void setName(String name) { this.name = name; } /** * returns the current frame that animation is currently working towards or * set to. * * @return the current frame of this animation. */ public int getCurrentFrame() { return currentFrame; } /** * returns the current time of the animation. * * @return the current time of this animation. */ public float getCurrentTime() { return currentTime; } /** * retrieves the end frame of the animation. The end frame defines where the * animation will "stop". * * @return the end frame of the animation. */ public int getEndFrame() { return endFrame; } /** * sets the end frame of the animation. The end frame defines where the * animation will "stop". * * @param endFrame * the end frame of the animation. */ public void setEndFrame(int endFrame) { if (endFrame >= keyframeTime.length || endFrame < 0) { logger.log(Level.SEVERE, "Invalid endframe index {0}" + ". Intialized to only " + "have: {1}" + " keyframes.", new Integer[]{endFrame,keyframeTime.length} ); return; } this.endFrame = endFrame; if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).setEndFrame(endFrame); } } } /** * retrieves the start frame of the animation. The start frame defines where * the animation will "start". * * @return the start frame of the animation. */ public int getStartFrame() { return startFrame; } /** * sets the start frame of the animation. The start frame defines where the * animation will "start". * * @param startFrame * the start frame of the animation. */ public void setStartFrame(int startFrame) { if (startFrame >= keyframeTime.length || startFrame < 0) { logger.log(Level.SEVERE, "Invalid endframe index {0}" + ". Intialized to only " + "have: {1}" + " keyframes.", new Integer[]{startFrame, keyframeTime.length}); return; } this.startFrame = startFrame; if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).setStartFrame(startFrame); } } } /** * returns true if this animation should interpolate between keyframes, * false otherwise. * * @return true if we will interpolation between frames. */ public boolean isInterpolate() { return interpolationType != null; } /** * sets whether this animation should interpolate between frames. It also * sets the children of this animation to the interpolation value. True will * interpolate between frames, false will not. * * @param interpolate true to interpolate, false otherwise. */ public void setInterpolate(boolean interpolate) { if (interpolate == true && keyframeTime == null) { throw new IllegalStateException( "Can't call setInterpolate() before the keyframeTimes are set"); } setInterpolationTypes( interpolate ? new int[keyframeTime.length] : null); // Due to the fact that the array instantiator instantiates to 0's, // and our constant for linear type == 0, this sets our instance to // interpolate linearly. if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).setInterpolate(interpolate); } } } /** * retrieves the rate at which interpolation occurs, this is in unit * seconds. Therefore, 0.25 would be a quater of a second. * * @return the interpolation rate. */ public float getInterpolationRate() { return interpolationRate; } /** * sets the rate at which interpolation occurs, this is in unit seconds. * Therefore, 0.25 would be a quater of a second. * * @param interpolationRate * the interpolation rate. */ public void setInterpolationRate(float interpolationRate) { this.interpolationRate = interpolationRate; } /** * hasChildren returns true if this BoneAnimation has child * BoneAnimations, false otherwise. * * @return true if this animation has child animations, false otherwise. */ public boolean hasChildren() { return (children != null); } /** * returns the list of keyframe times for this animation. * * @return the list of keyframe times for this animation. */ public float[] getKeyFrameTimes() { return this.keyframeTime; } /** * returns the list of BoneTransforms for this animation. * * @return the list of BoneTransforms for this animation. */ public ArrayList<BoneTransform> getBoneTransforms() { return boneTransforms; } /** * optimize will attempt to condense the BoneAnimation into as few * children as possible. This allows the proper sharing of keyframe times * and calculation of current time and current frame. If a child animation * has no children of its own, and its keyframes are equal to this * animation, the BoneTransforms are assimilated into this animation and * the child is deleted. */ public void optimize(boolean removeChildren) { if (children == null) { return; } for (int i = 0; i < children.size(); i++) { // check if the child has children, if so, optimize this child if (children.get(i).hasChildren()) { children.get(i).optimize(removeChildren); } else { // make sure the keyframes are equal, if we don't have keyframes // set it to the first one. if (this.keyframeTime == null) { if (boneTransforms == null) { boneTransforms = new ArrayList<BoneTransform>(); } this.keyframeTime = children.get(i).getKeyFrameTimes(); this.interpolationType = children.get(i) .getInterpolationType(); this.startFrame = children.get(i).getStartFrame(); this.endFrame = children.get(i).getEndFrame(); if (children.get(i).getBoneTransforms() != null) { for (int j = 0; j < children.get(i).getBoneTransforms() .size(); j++) { BoneTransform bt = children.get(i) .getBoneTransforms().get(j); if (bt != null && bt.getRotations() != null && bt.getRotations().length > 0) { boneTransforms.add(children.get(i) .getBoneTransforms().get(j)); } } } // we've copied this child's data, get rid of it, and adjust // the count // accordingly. children.remove(i); i } else { boolean same = true; if (this.keyframeTime.length == children.get(i) .getKeyFrameTimes().length) { for (int j = 0; j < keyframeTime.length; j++) { if (keyframeTime[j] != children.get(i) .getKeyFrameTimes()[j]) { same = false; break; } } if (same) { if (children.get(i).getBoneTransforms() != null) { for (int j = 0; j < children.get(i) .getBoneTransforms().size(); j++) { BoneTransform bt = children.get(i) .getBoneTransforms().get(j); if (bt.getRotations() != null && bt.getRotations().length > 0) { boneTransforms.add(children.get(i) .getBoneTransforms().get(j)); } } } // we've copied this child's data, get rid of it, // and adjust the count // accordingly. children.remove(i); i } } } } } if (removeChildren) { children.clear(); children = null; } } /** * return the list of interpolation types assigned to this animation, * or null if this animation does not interpolate. * * @return the list of interpolation types assigned to this animation. */ private int[] getInterpolationType() { return interpolationType; } /** * returns the string representation of this animation. */ public String toString() { return name; } /** * Assigns this animation to a provided skeleton. The skeleton bones are * examined to assign transforms as needed. If no bones are properly * assigned to a transform, false is returned. If the assignment is * successful, true is returned. * * @param b * the skeleton to assign. * @return true if this was successful, false otherwise. */ public boolean assignSkeleton(Bone b) { boolean ok = true; if (boneTransforms != null) { for (int i = 0; i < boneTransforms.size(); i++) { if (!boneTransforms.get(i).findBone(b)) { ok = false; } } } if (children != null) { for (int i = 0; i < children.size(); i++) { if (!children.get(i).assignSkeleton(b)) { ok = false; } } } return ok; } public void write(JMEExporter e) throws IOException { OutputCapsule cap = e.getCapsule(this); cap.write(name, "name", null); cap.write(keyframeTime, "keyframeTime", null); cap.write(interpolationType, "interpolationType", null); cap.writeSavableArrayList(boneTransforms, "boneTransforms", null); cap.write(currentTime, "currentTime", 0); cap.write(currentFrame, "currentFrame", 1); cap.write(prevFrame, "prevFrame", 0); cap.write(endFrame, "endFrame", 0); cap.write(startFrame, "startFrame", 0); cap.write(interpolationRate, "interpolationRate", DEFAULT_RATE); cap.write(lastTime, "lastTime", 0); cap.write(cycleMode, "cycleMode", 1); // cap.write(interpolate, "interpolate", true); // N.b. the interpolationType above stores everthing we need. cap.writeSavableArrayList(children, "children", null); Integer[] frames = AnimationEventManager.getInstance().getFrames(this); if (frames != null) { int[] saveFrames = new int[frames.length]; for (int i = 0; i < frames.length; i++) { saveFrames[i] = frames[i]; } cap.write(saveFrames, "eventFrames", null); for (int i = 0; i < frames.length; i++) { cap.writeSavableArrayList(AnimationEventManager.getInstance() .getEvents(this, frames[i]), "event" + frames[i], null); } } } @SuppressWarnings("unchecked") public void read(JMEImporter e) throws IOException { InputCapsule cap = e.getCapsule(this); name = cap.readString("name", null); keyframeTime = cap.readFloatArray("keyframeTime", null); interpolationType = cap.readIntArray("interpolationType", null); boneTransforms = cap.readSavableArrayList("boneTransforms", null); currentTime = cap.readFloat("currentTime", 0); currentFrame = cap.readInt("currentFrame", 1); prevFrame = cap.readInt("prevFrame", 0); endFrame = cap.readInt("endFrame", 0); startFrame = cap.readInt("startFrame", 0); interpolationRate = cap.readFloat("interpolationRate", DEFAULT_RATE); lastTime = cap.readFloat("lastTime", 0); cycleMode = cap.readInt("cycleMode", 1); // interpolate = cap.readBoolean("interpolate", true); // We ignore the "interpolate" setting, since it is entirely // superfluous to the interpolationType field. // Leave this comment in place, because old versions of JME persisted // this setting, and people may look here and wonder why it is not // being read. children = cap.readSavableArrayList("children", null); int[] frames = cap.readIntArray("eventFrames", null); if (frames != null) { for (int i = 0; i < frames.length; i++) { ArrayList<Savable> events = cap.readSavableArrayList("event" + frames[i], null); for (int j = 0; j < events.size(); j++) { AnimationEventManager.getInstance().addAnimationEvent(this, frames[i], (AnimationEvent) events.get(i)); } } } // TODO: Update this check to permit BEZIER if that really works. if (interpolationType != null) { // This is only a warning check. No effect to behavior. int iType = BoneAnimation.LINEAR; for (int i = 0; i < keyframeTime.length; i++) { if (interpolationType[i] != BoneAnimation.LINEAR) { iType = interpolationType[i]; break; } } if (iType != BoneAnimation.LINEAR) { logger.log(Level.WARNING, "Unsupported interpolation type specified for " + "at least one frame: {0}. Continuing with specified type.", iType); } } } public Class getClassTag() { return this.getClass(); } public void resetCurrentTime() { currentTime = 0; lastTime = 0; } public void reset() { currentFrame = startFrame + 1; prevFrame = startFrame; currentTime = keyframeTime[startFrame]; } /** * Ensures that an animation can continue running if you start updating * it again. */ public void reactivate(int repeatType) { if (repeatType == Controller.RT_CLAMP) { if (currentFrame > endFrame) reset(); } } public Spatial getDestSpatial() { return destSpatial; } public void setDestSpatial(Spatial destSpatial) { this.destSpatial = destSpatial; } public Bone getSourceBone() { return sourceBone; } public void setSourceBone(Bone sourceBone) { this.sourceBone = sourceBone; } public AnimationProperties getAnimationProperties() { return props; } public void setAnimationProperties(AnimationProperties props) { this.props = props; } }
package io.crate.planner.symbol; import io.crate.metadata.FunctionInfo; import org.cratedb.DataType; import org.elasticsearch.common.Preconditions; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Function extends ValueSymbol { public static final SymbolFactory<Function> FACTORY = new SymbolFactory<Function>() { @Override public Function newInstance() { return new Function(); } }; private List<ValueSymbol> arguments; private FunctionInfo info; public Function(FunctionInfo info, List<ValueSymbol> arguments) { Preconditions.checkArgument(arguments.size() == info.ident().argumentTypes().size()); this.info = info; this.arguments = arguments; } public Function() { } public List<ValueSymbol> arguments() { return arguments; } @Override public DataType valueType() { return info.returnType(); } @Override public SymbolType symbolType() { return SymbolType.FUNCTION; } @Override public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) { return visitor.visitFunction(this, context); } @Override public void readFrom(StreamInput in) throws IOException { info = new FunctionInfo(); info.readFrom(in); int numArguments = in.readVInt(); arguments = new ArrayList<>(numArguments); for (int i = 0; i < numArguments; i++) { arguments.add((ValueSymbol)Symbol.fromStream(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { info.writeTo(out); out.writeVInt(arguments.size()); for (ValueSymbol argument : arguments) { Symbol.toStream(argument, out); } } }
package io.branch.rnbranch; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.net.Uri; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.os.Handler; import com.facebook.react.bridge.*; import com.facebook.react.bridge.Promise; import com.facebook.react.modules.core.*; import com.facebook.react.bridge.ReadableMap; import io.branch.referral.*; import io.branch.referral.Branch.BranchLinkCreateListener; import io.branch.referral.BuildConfig; import io.branch.referral.util.*; import io.branch.referral.Branch; import io.branch.indexing.*; import org.json.*; import java.lang.ref.WeakReference; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class RNBranchModule extends ReactContextBaseJavaModule { public static final String REACT_CLASS = "RNBranch"; public static final String REACT_MODULE_NAME = "RNBranch"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT = "io.branch.rnbranch.RNBranchModule.onInitSessionFinished"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_BRANCH_UNIVERSAL_OBJECT = "branch_universal_object"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_LINK_PROPERTIES = "link_properties"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS = "params"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR = "error"; public static final String NATIVE_INIT_SESSION_FINISHED_EVENT_URI = "uri"; private static final String RN_INIT_SESSION_SUCCESS_EVENT = "RNBranch.initSessionSuccess"; private static final String RN_INIT_SESSION_ERROR_EVENT = "RNBranch.initSessionError"; private static final String INIT_SESSION_SUCCESS = "INIT_SESSION_SUCCESS"; private static final String INIT_SESSION_ERROR = "INIT_SESSION_ERROR"; private static final String ADD_TO_CART_EVENT = "ADD_TO_CART_EVENT"; private static final String ADD_TO_WISHLIST_EVENT = "ADD_TO_WISHLIST_EVENT"; private static final String PURCHASED_EVENT = "PURCHASED_EVENT"; private static final String PURCHASE_INITIATED_EVENT = "PURCHASE_INITIATED_EVENT"; private static final String REGISTER_VIEW_EVENT = "REGISTER_VIEW_EVENT"; private static final String SHARE_COMPLETED_EVENT = "SHARE_COMPLETED_EVENT"; private static final String SHARE_INITIATED_EVENT = "SHARE_INITIATED_EVENT"; private static final String STANDARD_EVENT_ADD_TO_CART = "STANDARD_EVENT_ADD_TO_CART"; private static final String STANDARD_EVENT_ADD_TO_WISHLIST = "STANDARD_EVENT_ADD_TO_WISHLIST"; private static final String STANDARD_EVENT_VIEW_CART = "STANDARD_EVENT_VIEW_CART"; private static final String STANDARD_EVENT_INITIATE_PURCHASE = "STANDARD_EVENT_INITIATE_PURCHASE"; private static final String STANDARD_EVENT_ADD_PAYMENT_INFO = "STANDARD_EVENT_ADD_PAYMENT_INFO"; private static final String STANDARD_EVENT_PURCHASE = "STANDARD_EVENT_PURCHASE"; private static final String STANDARD_EVENT_SPEND_CREDITS = "STANDARD_EVENT_SPEND_CREDITS"; private static final String STANDARD_EVENT_SEARCH = "STANDARD_EVENT_SEARCH"; private static final String STANDARD_EVENT_VIEW_ITEM = "STANDARD_EVENT_VIEW_ITEM"; private static final String STANDARD_EVENT_VIEW_ITEMS = "STANDARD_EVENT_VIEW_ITEMS"; private static final String STANDARD_EVENT_RATE = "STANDARD_EVENT_RATE"; private static final String STANDARD_EVENT_SHARE = "STANDARD_EVENT_SHARE"; private static final String STANDARD_EVENT_COMPLETE_REGISTRATION = "STANDARD_EVENT_COMPLETE_REGISTRATION"; private static final String STANDARD_EVENT_COMPLETE_TUTORIAL = "STANDARD_EVENT_COMPLETE_TUTORIAL"; private static final String STANDARD_EVENT_ACHIEVE_LEVEL = "STANDARD_EVENT_ACHIEVE_LEVEL"; private static final String STANDARD_EVENT_UNLOCK_ACHIEVEMENT = "STANDARD_EVENT_UNLOCK_ACHIEVEMENT"; private static final String IDENT_FIELD_NAME = "ident"; public static final String UNIVERSAL_OBJECT_NOT_FOUND_ERROR_CODE = "RNBranch::Error::BUONotFound"; private static final long AGING_HASH_TTL = 3600000; private static JSONObject initSessionResult = null; private BroadcastReceiver mInitSessionEventReceiver = null; private static Branch.BranchUniversalReferralInitListener initListener = null; private static Activity mActivity = null; private static boolean mUseDebug = false; private static boolean mInitialized = false; private static JSONObject mRequestMetadata = new JSONObject(); private AgingHash<String, BranchUniversalObject> mUniversalObjectMap = new AgingHash<>(AGING_HASH_TTL); public static void initSession(final Uri uri, Activity reactActivity, Branch.BranchUniversalReferralInitListener anInitListener) { initListener = anInitListener; initSession(uri, reactActivity); } public static void initSession(final Uri uri, Activity reactActivity) { Branch branch = setupBranch(reactActivity.getApplicationContext()); mActivity = reactActivity; branch.initSession(new Branch.BranchReferralInitListener(){ private Activity mmActivity = null; @Override public void onInitFinished(JSONObject referringParams, BranchError error) { Log.d(REACT_CLASS, "onInitFinished"); JSONObject result = new JSONObject(); Uri referringUri = null; try{ boolean clickedBranchLink = false; // getXXX throws. It's OK for these to be missing. try { clickedBranchLink = referringParams.getBoolean("+clicked_branch_link"); } catch (JSONException e) { } String referringLink = null; if (clickedBranchLink) { try { referringLink = referringParams.getString("~referring_link"); } catch (JSONException e) { } } else { try { referringLink = referringParams.getString("+non_branch_link"); } catch (JSONException e) { } } if (referringLink != null) referringUri = Uri.parse(referringLink); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS, referringParams); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR, error != null ? error.getMessage() : JSONObject.NULL); result.put(NATIVE_INIT_SESSION_FINISHED_EVENT_URI, referringLink != null ? referringLink : JSONObject.NULL); } catch(JSONException ex) { try { result.put("error", "Failed to convert result to JSONObject: " + ex.getMessage()); } catch(JSONException k) {} } initSessionResult = result; BranchUniversalObject branchUniversalObject = BranchUniversalObject.getReferredBranchUniversalObject(); LinkProperties linkProperties = LinkProperties.getReferredLinkProperties(); if (initListener != null) { initListener.onInitFinished(branchUniversalObject, linkProperties, error); } generateLocalBroadcast(referringParams, referringUri, branchUniversalObject, linkProperties, error); } private Branch.BranchReferralInitListener init(Activity activity) { mmActivity = activity; return this; } private void generateLocalBroadcast(JSONObject referringParams, Uri uri, BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) { Intent broadcastIntent = new Intent(NATIVE_INIT_SESSION_FINISHED_EVENT); if (referringParams != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_PARAMS, referringParams.toString()); } if (branchUniversalObject != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_BRANCH_UNIVERSAL_OBJECT, branchUniversalObject); } if (linkProperties != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_LINK_PROPERTIES, linkProperties); } if (uri != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_URI, uri.toString()); } if (error != null) { broadcastIntent.putExtra(NATIVE_INIT_SESSION_FINISHED_EVENT_ERROR, error.getMessage()); } LocalBroadcastManager.getInstance(mmActivity).sendBroadcast(broadcastIntent); } }.init(reactActivity), uri, reactActivity); } public static void setDebug() { mUseDebug = true; } public static void setRequestMetadata(String key, String val) { if (key == null) { return; } if (mRequestMetadata.has(key) && val == null) { mRequestMetadata.remove(key); } try { mRequestMetadata.put(key, val); } catch (JSONException e) { // no-op } } public RNBranchModule(ReactApplicationContext reactContext) { super(reactContext); forwardInitSessionFinishedEventToReactNative(reactContext); } @javax.annotation.Nullable @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); // RN events transmitted to JS constants.put(INIT_SESSION_SUCCESS, RN_INIT_SESSION_SUCCESS_EVENT); constants.put(INIT_SESSION_ERROR, RN_INIT_SESSION_ERROR_EVENT); // Constants for use with userCompletedAction (deprecated) constants.put(ADD_TO_CART_EVENT, BranchEvent.ADD_TO_CART); constants.put(ADD_TO_WISHLIST_EVENT, BranchEvent.ADD_TO_WISH_LIST); constants.put(PURCHASED_EVENT, BranchEvent.PURCHASED); constants.put(PURCHASE_INITIATED_EVENT, BranchEvent.PURCHASE_STARTED); constants.put(REGISTER_VIEW_EVENT, BranchEvent.VIEW); constants.put(SHARE_COMPLETED_EVENT, BranchEvent.SHARE_COMPLETED); constants.put(SHARE_INITIATED_EVENT, BranchEvent.SHARE_STARTED); // constants for use with BranchEvent // Commerce events constants.put(STANDARD_EVENT_ADD_TO_CART, BRANCH_STANDARD_EVENT.ADD_TO_CART.getName()); constants.put(STANDARD_EVENT_ADD_TO_WISHLIST, BRANCH_STANDARD_EVENT.ADD_TO_WISHLIST.getName()); constants.put(STANDARD_EVENT_VIEW_CART, BRANCH_STANDARD_EVENT.VIEW_CART.getName()); constants.put(STANDARD_EVENT_INITIATE_PURCHASE, BRANCH_STANDARD_EVENT.INITIATE_PURCHASE.getName()); constants.put(STANDARD_EVENT_ADD_PAYMENT_INFO, BRANCH_STANDARD_EVENT.ADD_PAYMENT_INFO.getName()); constants.put(STANDARD_EVENT_PURCHASE, BRANCH_STANDARD_EVENT.PURCHASE.getName()); constants.put(STANDARD_EVENT_SPEND_CREDITS, BRANCH_STANDARD_EVENT.SPEND_CREDITS.getName()); // Content Events constants.put(STANDARD_EVENT_SEARCH, BRANCH_STANDARD_EVENT.SEARCH.getName()); constants.put(STANDARD_EVENT_VIEW_ITEM, BRANCH_STANDARD_EVENT.VIEW_ITEM.getName()); constants.put(STANDARD_EVENT_VIEW_ITEMS , BRANCH_STANDARD_EVENT.VIEW_ITEMS.getName()); constants.put(STANDARD_EVENT_RATE, BRANCH_STANDARD_EVENT.RATE.getName()); constants.put(STANDARD_EVENT_SHARE, BRANCH_STANDARD_EVENT.SHARE.getName()); // User Lifecycle Events constants.put(STANDARD_EVENT_COMPLETE_REGISTRATION, BRANCH_STANDARD_EVENT.COMPLETE_REGISTRATION.getName()); constants.put(STANDARD_EVENT_COMPLETE_TUTORIAL , BRANCH_STANDARD_EVENT.COMPLETE_TUTORIAL.getName()); constants.put(STANDARD_EVENT_ACHIEVE_LEVEL, BRANCH_STANDARD_EVENT.ACHIEVE_LEVEL.getName()); constants.put(STANDARD_EVENT_UNLOCK_ACHIEVEMENT, BRANCH_STANDARD_EVENT.UNLOCK_ACHIEVEMENT.getName()); return constants; } private void forwardInitSessionFinishedEventToReactNative(ReactApplicationContext reactContext) { mInitSessionEventReceiver = new BroadcastReceiver() { RNBranchModule mBranchModule; @Override public void onReceive(Context context, Intent intent) { final boolean hasError = (initSessionResult.has("error") && !initSessionResult.isNull("error")); final String eventName = hasError ? RN_INIT_SESSION_ERROR_EVENT : RN_INIT_SESSION_SUCCESS_EVENT; mBranchModule.sendRNEvent(eventName, convertJsonToMap(initSessionResult)); } private BroadcastReceiver init(RNBranchModule branchModule) { mBranchModule = branchModule; return this; } }.init(this); LocalBroadcastManager.getInstance(reactContext).registerReceiver(mInitSessionEventReceiver, new IntentFilter(NATIVE_INIT_SESSION_FINISHED_EVENT)); } @Override public void onCatalystInstanceDestroy() { LocalBroadcastManager.getInstance(getReactApplicationContext()).unregisterReceiver(mInitSessionEventReceiver); } @Override public String getName() { return REACT_MODULE_NAME; } @ReactMethod public void disableTracking(boolean disable) { Branch branch = Branch.getInstance(); branch.disableTracking(disable); } @ReactMethod public void isTrackingDisabled(Promise promise) { Branch branch = Branch.getInstance(); promise.resolve(branch.isTrackingDisabled()); } @ReactMethod public void createUniversalObject(ReadableMap universalObjectMap, Promise promise) { String ident = UUID.randomUUID().toString(); BranchUniversalObject universalObject = createBranchUniversalObject(universalObjectMap); mUniversalObjectMap.put(ident, universalObject); WritableMap response = new WritableNativeMap(); response.putString(IDENT_FIELD_NAME, ident); promise.resolve(response); } @ReactMethod public void releaseUniversalObject(String ident) { mUniversalObjectMap.remove(ident); } @ReactMethod public void redeemInitSessionResult(Promise promise) { promise.resolve(convertJsonToMap(initSessionResult)); } @ReactMethod public void getLatestReferringParams(Promise promise) { Branch branch = Branch.getInstance(); promise.resolve(convertJsonToMap(branch.getLatestReferringParams())); } @ReactMethod public void getFirstReferringParams(Promise promise) { Branch branch = Branch.getInstance(); promise.resolve(convertJsonToMap(branch.getFirstReferringParams())); } @ReactMethod public void setIdentity(String identity) { Branch branch = Branch.getInstance(); branch.setIdentity(identity); } @ReactMethod public void logout() { Branch branch = Branch.getInstance(); branch.logout(); } @ReactMethod public void logEvent(ReadableArray contentItems, String eventName, ReadableMap params, Promise promise) { List<BranchUniversalObject> buos = new ArrayList<>(); for (int i = 0; i < contentItems.size(); ++ i) { String ident = contentItems.getString(i); BranchUniversalObject universalObject = findUniversalObjectOrReject(ident, promise); if (universalObject == null) return; buos.add(universalObject); } BranchEvent event = createBranchEvent(eventName, params); event.addContentItems(buos); event.logEvent(mActivity); promise.resolve(null); } @ReactMethod public void userCompletedAction(String event, ReadableMap appState) throws JSONException { Branch branch = Branch.getInstance(); branch.userCompletedAction(event, convertMapToJson(appState)); } @ReactMethod public void userCompletedActionOnUniversalObject(String ident, String event, ReadableMap state, Promise promise) { BranchUniversalObject universalObject = findUniversalObjectOrReject(ident, promise); if (universalObject == null) return; universalObject.userCompletedAction(event, convertMapToParams(state)); promise.resolve(null); } @ReactMethod public void sendCommerceEvent(String revenue, ReadableMap metadata, final Promise promise) throws JSONException { Branch branch = Branch.getInstance(); CommerceEvent commerceEvent = new CommerceEvent(); commerceEvent.setRevenue(Double.parseDouble(revenue)); JSONObject jsonMetadata = null; if (metadata != null) { jsonMetadata = convertMapToJson(metadata); } branch.sendCommerceEvent(commerceEvent, jsonMetadata, null); promise.resolve(null); } @ReactMethod public void showShareSheet(String ident, ReadableMap shareOptionsMap, ReadableMap linkPropertiesMap, ReadableMap controlParamsMap, Promise promise) { Context context = getReactApplicationContext(); Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() { Promise mPm; Context mContext; ReadableMap shareOptionsMap, linkPropertiesMap, controlParamsMap; String ident; private Runnable init(ReadableMap _shareOptionsMap, String _ident, ReadableMap _linkPropertiesMap, ReadableMap _controlParamsMap, Promise promise, Context context) { mPm = promise; mContext = context; shareOptionsMap = _shareOptionsMap; ident = _ident; linkPropertiesMap = _linkPropertiesMap; controlParamsMap = _controlParamsMap; return this; } @Override public void run() { String messageHeader = shareOptionsMap.hasKey("messageHeader") ? shareOptionsMap.getString("messageHeader") : ""; String messageBody = shareOptionsMap.hasKey("messageBody") ? shareOptionsMap.getString("messageBody") : ""; ShareSheetStyle shareSheetStyle = new ShareSheetStyle(mContext, messageHeader, messageBody) .setCopyUrlStyle(mContext.getResources().getDrawable(android.R.drawable.ic_menu_send), "Copy", "Added to clipboard") .setMoreOptionStyle(mContext.getResources().getDrawable(android.R.drawable.ic_menu_search), "Show more") .addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL) .addPreferredSharingOption(SharingHelper.SHARE_WITH.TWITTER) .addPreferredSharingOption(SharingHelper.SHARE_WITH.MESSAGE) .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK); BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, mPm); if (branchUniversalObject == null) { return; } LinkProperties linkProperties = createLinkProperties(linkPropertiesMap, controlParamsMap); branchUniversalObject.showShareSheet( getCurrentActivity(), linkProperties, shareSheetStyle, new Branch.BranchLinkShareListener() { private Promise mPromise = null; @Override public void onShareLinkDialogLaunched() { } @Override public void onShareLinkDialogDismissed() { if(mPromise == null) { return; } WritableMap map = new WritableNativeMap(); map.putString("channel", null); map.putBoolean("completed", false); map.putString("error", null); mPromise.resolve(map); mPromise = null; } @Override public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) { if(mPromise == null) { return; } WritableMap map = new WritableNativeMap(); map.putString("channel", sharedChannel); map.putBoolean("completed", true); map.putString("error", (error != null ? error.getMessage() : null)); mPromise.resolve(map); mPromise = null; } @Override public void onChannelSelected(String channelName) { } private Branch.BranchLinkShareListener init(Promise promise) { mPromise = promise; return this; } }.init(mPm)); } }.init(shareOptionsMap, ident, linkPropertiesMap, controlParamsMap, promise, context); mainHandler.post(myRunnable); } @ReactMethod public void registerView(String ident, Promise promise) { BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, promise); if (branchUniversalObject == null) { return; } branchUniversalObject.registerView(); promise.resolve(null); } @ReactMethod public void generateShortUrl(String ident, ReadableMap linkPropertiesMap, ReadableMap controlParamsMap, final Promise promise) { LinkProperties linkProperties = createLinkProperties(linkPropertiesMap, controlParamsMap); BranchUniversalObject branchUniversalObject = findUniversalObjectOrReject(ident, promise); if (branchUniversalObject == null) { return; } branchUniversalObject.generateShortUrl(mActivity, linkProperties, new BranchLinkCreateListener() { @Override public void onLinkCreate(String url, BranchError error) { Log.d(REACT_CLASS, "onLinkCreate " + url); if (error != null) { if (error.getErrorCode() == BranchError.ERR_BRANCH_DUPLICATE_URL) { promise.reject("RNBranch::Error::DuplicateResourceError", error.getMessage()); } else { promise.reject("RNBranch::Error", error.getMessage()); } return; } WritableMap map = new WritableNativeMap(); map.putString("url", url); promise.resolve(map); } }); } @ReactMethod public void openURL(String url, ReadableMap options) { if (mActivity == null) { // initSession is called before JS loads. This probably indicates failure to call initSession // in an activity. Log.e(REACT_CLASS, "Branch native Android SDK not initialized in openURL"); return; } Intent intent = new Intent(mActivity, mActivity.getClass()); intent.putExtra("branch", url); intent.putExtra("branch_force_new_session", true); if (options.hasKey("newActivity") && options.getBoolean("newActivity")) mActivity.finish(); mActivity.startActivity(intent); } public static BranchEvent createBranchEvent(String eventName, ReadableMap params) { BranchEvent event; try { BRANCH_STANDARD_EVENT standardEvent = BRANCH_STANDARD_EVENT.valueOf(eventName); // valueOf on BRANCH_STANDARD_EVENT Enum has succeeded, so this is a standard event. event = new BranchEvent(standardEvent); } catch (IllegalArgumentException e) { // The event name is not found in standard events. // So use custom event mode. event = new BranchEvent(eventName); } if (params.hasKey("currency")) { String currencyString = params.getString("currency"); CurrencyType currency = CurrencyType.getValue(currencyString); if (currency != null) { event.setCurrency(currency); } else { Log.w(REACT_CLASS, "Invalid currency " + currencyString); } } if (params.hasKey("transactionID")) event.setTransactionID(params.getString("transactionID")); if (params.hasKey("revenue")) event.setRevenue(Double.parseDouble(params.getString("revenue"))); if (params.hasKey("shipping")) event.setShipping(Double.parseDouble(params.getString("shipping"))); if (params.hasKey("tax")) event.setTax(Double.parseDouble(params.getString("tax"))); if (params.hasKey("coupon")) event.setCoupon(params.getString("coupon")); if (params.hasKey("affiliation")) event.setAffiliation(params.getString("affiliation")); if (params.hasKey("description")) event.setDescription(params.getString("description")); if (params.hasKey("searchQuery")) event.setSearchQuery(params.getString("searchQuery")); if (params.hasKey("customData")) { ReadableMap customData = params.getMap("customData"); ReadableMapKeySetIterator it = customData.keySetIterator(); while (it.hasNextKey()) { String key = it.nextKey(); event.addCustomDataProperty(key, customData.getString(key)); } } return event; } public static LinkProperties createLinkProperties(ReadableMap linkPropertiesMap, @Nullable ReadableMap controlParams){ LinkProperties linkProperties = new LinkProperties(); if (linkPropertiesMap.hasKey("alias")) linkProperties.setAlias(linkPropertiesMap.getString("alias")); if (linkPropertiesMap.hasKey("campaign")) linkProperties.setCampaign(linkPropertiesMap.getString("campaign")); if (linkPropertiesMap.hasKey("channel")) linkProperties.setChannel(linkPropertiesMap.getString("channel")); if (linkPropertiesMap.hasKey("feature")) linkProperties.setFeature(linkPropertiesMap.getString("feature")); if (linkPropertiesMap.hasKey("stage")) linkProperties.setStage(linkPropertiesMap.getString("stage")); if (linkPropertiesMap.hasKey("tags")) { ReadableArray tags = linkPropertiesMap.getArray("tags"); for (int i=0; i<tags.size(); ++i) { String tag = tags.getString(i); linkProperties.addTag(tag); } } if (controlParams != null) { ReadableMapKeySetIterator iterator = controlParams.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); Object value = getReadableMapObjectForKey(controlParams, key); linkProperties.addControlParameter(key, value.toString()); } } return linkProperties; } private static Branch setupBranch(Context context) { Branch branch = Branch.getInstance(context); if (!mInitialized) { Log.i(REACT_CLASS, "Initializing Branch SDK v. " + BuildConfig.VERSION_NAME); RNBranchConfig config = new RNBranchConfig(context); if (mUseDebug || config.getDebugMode()) branch.setDebug(); if (mRequestMetadata != null) { Iterator keys = mRequestMetadata.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { branch.setRequestMetadata(key, mRequestMetadata.getString(key)); } catch (JSONException e) { // no-op } } } mInitialized = true; } return branch; } private BranchUniversalObject findUniversalObjectOrReject(final String ident, final Promise promise) { BranchUniversalObject universalObject = mUniversalObjectMap.get(ident); if (universalObject == null) { final String errorMessage = "BranchUniversalObject not found for ident " + ident + "."; promise.reject(UNIVERSAL_OBJECT_NOT_FOUND_ERROR_CODE, errorMessage); } return universalObject; } public ContentMetadata createContentMetadata(ReadableMap map) { ContentMetadata metadata = new ContentMetadata(); if (map.hasKey("contentSchema")) { BranchContentSchema schema = BranchContentSchema.valueOf(map.getString("contentSchema")); metadata.setContentSchema(schema); } if (map.hasKey("quantity")) { metadata.setQuantity(map.getDouble("quantity")); } if (map.hasKey("price")) { double price = Double.parseDouble(map.getString("price")); CurrencyType currency = null; if (map.hasKey("currency")) currency = CurrencyType.valueOf(map.getString("currency")); metadata.setPrice(price, currency); } if (map.hasKey("sku")) { metadata.setSku(map.getString("sku")); } if (map.hasKey("productName")) { metadata.setProductName(map.getString("productName")); } if (map.hasKey("productBrand")) { metadata.setProductBrand(map.getString("productBrand")); } if (map.hasKey("productCategory")) { ProductCategory category = getProductCategory(map.getString("productCategory")); if (category != null) metadata.setProductCategory(category); } if (map.hasKey("productVariant")) { metadata.setProductVariant(map.getString("productVariant")); } if (map.hasKey("condition")) { ContentMetadata.CONDITION condition = ContentMetadata.CONDITION.valueOf(map.getString("condition")); metadata.setProductCondition(condition); } if (map.hasKey("ratingAverage") || map.hasKey("ratingMax") || map.hasKey("ratingCount")) { Double average = null, max = null; Integer count = null; if (map.hasKey("ratingAverage")) average = map.getDouble("ratingAverage"); if (map.hasKey("ratingCount")) count = map.getInt("ratingCount"); if (map.hasKey("ratingMax")) max = map.getDouble("ratingMax"); metadata.setRating(average, max, count); } if (map.hasKey("addressStreet") || map.hasKey("addressCity") || map.hasKey("addressRegion") || map.hasKey("addressCountry") || map.hasKey("addressPostalCode")) { String street = null, city = null, region = null, country = null, postalCode = null; if (map.hasKey("addressStreet")) street = map.getString("addressStreet"); if (map.hasKey("addressCity")) street = map.getString("addressCity"); if (map.hasKey("addressRegion")) street = map.getString("addressRegion"); if (map.hasKey("addressCountry")) street = map.getString("addressCountry"); if (map.hasKey("addressPostalCode")) street = map.getString("addressPostalCode"); metadata.setAddress(street, city, region, country, postalCode); } if (map.hasKey("latitude") || map.hasKey("longitude")) { Double latitude = null, longitude = null; if (map.hasKey("latitude")) latitude = map.getDouble("latitude"); if (map.hasKey("longitude")) longitude = map.getDouble("longitude"); metadata.setLocation(latitude, longitude); } if (map.hasKey("imageCaptions")) { ReadableArray captions = map.getArray("imageCaptions"); for (int j=0; j < captions.size(); ++j) { metadata.addImageCaptions(captions.getString(j)); } } if (map.hasKey("customMetadata")) { ReadableMap customMetadata = map.getMap("customMetadata"); ReadableMapKeySetIterator it = customMetadata.keySetIterator(); while (it.hasNextKey()) { String key = it.nextKey(); metadata.addCustomMetadata(key, customMetadata.getString(key)); } } return metadata; } public BranchUniversalObject createBranchUniversalObject(ReadableMap branchUniversalObjectMap) { BranchUniversalObject branchUniversalObject = new BranchUniversalObject() .setCanonicalIdentifier(branchUniversalObjectMap.getString("canonicalIdentifier")); if (branchUniversalObjectMap.hasKey("title")) branchUniversalObject.setTitle(branchUniversalObjectMap.getString("title")); if (branchUniversalObjectMap.hasKey("canonicalUrl")) branchUniversalObject.setCanonicalUrl(branchUniversalObjectMap.getString("canonicalUrl")); if (branchUniversalObjectMap.hasKey("contentDescription")) branchUniversalObject.setContentDescription(branchUniversalObjectMap.getString("contentDescription")); if (branchUniversalObjectMap.hasKey("contentImageUrl")) branchUniversalObject.setContentImageUrl(branchUniversalObjectMap.getString("contentImageUrl")); if (branchUniversalObjectMap.hasKey("locallyIndex")) { if (branchUniversalObjectMap.getBoolean("locallyIndex")) { branchUniversalObject.setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC); } else { branchUniversalObject.setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); } } if (branchUniversalObjectMap.hasKey("publiclyIndex")) { if (branchUniversalObjectMap.getBoolean("publiclyIndex")) { branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC); } else { branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); } } if (branchUniversalObjectMap.hasKey("contentIndexingMode")) { switch (branchUniversalObjectMap.getType("contentIndexingMode")) { case String: String mode = branchUniversalObjectMap.getString("contentIndexingMode"); if (mode.equals("private")) branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); else if (mode.equals("public")) branchUniversalObject.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC); else Log.w(REACT_CLASS, "Unsupported value for contentIndexingMode: " + mode + ". Supported values are \"public\" and \"private\""); break; default: Log.w(REACT_CLASS, "contentIndexingMode must be a String"); break; } } if (branchUniversalObjectMap.hasKey("currency") && branchUniversalObjectMap.hasKey("price")) { String currencyString = branchUniversalObjectMap.getString("currency"); CurrencyType currency = CurrencyType.valueOf(currencyString); branchUniversalObject.setPrice(branchUniversalObjectMap.getDouble("price"), currency); } if (branchUniversalObjectMap.hasKey("expirationDate")) { String expirationString = branchUniversalObjectMap.getString("expirationDate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date date = format.parse(expirationString); Log.d(REACT_CLASS, "Expiration date is " + date.toString()); branchUniversalObject.setContentExpiration(date); } catch (ParseException e) { Log.w(REACT_CLASS, "Invalid expiration date format. Valid format is YYYY-mm-ddTHH:MM:SS, e.g. 2017-02-01T00:00:00. All times UTC."); } } if (branchUniversalObjectMap.hasKey("keywords")) { ReadableArray keywords = branchUniversalObjectMap.getArray("keywords"); for (int i=0; i<keywords.size(); ++i) { branchUniversalObject.addKeyWord(keywords.getString(i)); } } if(branchUniversalObjectMap.hasKey("metadata")) { ReadableMap metadataMap = branchUniversalObjectMap.getMap("metadata"); ReadableMapKeySetIterator iterator = metadataMap.keySetIterator(); while (iterator.hasNextKey()) { String metadataKey = iterator.nextKey(); Object metadataObject = getReadableMapObjectForKey(metadataMap, metadataKey); branchUniversalObject.addContentMetadata(metadataKey, metadataObject.toString()); HashMap<String, String> metadata = branchUniversalObject.getMetadata(); } } if (branchUniversalObjectMap.hasKey("type")) branchUniversalObject.setContentType(branchUniversalObjectMap.getString("type")); if (branchUniversalObjectMap.hasKey("contentMetadata")) { branchUniversalObject.setContentMetadata(createContentMetadata(branchUniversalObjectMap.getMap("contentMetadata"))); } return branchUniversalObject; } @Nullable public ProductCategory getProductCategory(final String stringValue) { ProductCategory[] possibleValues = ProductCategory.class.getEnumConstants(); for (ProductCategory value: possibleValues) { if (stringValue.equals(value.getName())) { return value; } } Log.w(REACT_CLASS, "Could not find product category " + stringValue); return null; } @ReactMethod public void redeemRewards(int value, String bucket, Promise promise) { if (bucket == null) { Branch.getInstance().redeemRewards(value, new RedeemRewardsListener(promise)); } else { Branch.getInstance().redeemRewards(bucket, value, new RedeemRewardsListener(promise)); } } @ReactMethod public void loadRewards(String bucket, Promise promise) { Branch.getInstance().loadRewards(new LoadRewardsListener(bucket, promise)); } @ReactMethod public void getCreditHistory(Promise promise) { Branch.getInstance().getCreditHistory(new CreditHistoryListener(promise)); } protected class CreditHistoryListener implements Branch.BranchListResponseListener { private Promise _promise; // Constructor that takes in a required callbackContext object public CreditHistoryListener(Promise promise) { this._promise = promise; } // Listener that implements BranchListResponseListener for getCreditHistory() @Override public void onReceivingResponse(JSONArray list, BranchError error) { ArrayList<String> errors = new ArrayList<String>(); if (error == null) { try { ReadableArray result = convertJsonToArray(list); this._promise.resolve(result); } catch (JSONException err) { this._promise.reject(err.getMessage()); } } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } protected class RedeemRewardsListener implements Branch.BranchReferralStateChangedListener { private Promise _promise; public RedeemRewardsListener(Promise promise) { this._promise = promise; } @Override public void onStateChanged(boolean changed, BranchError error) { if (error == null) { WritableMap map = new WritableNativeMap(); map.putBoolean("changed", changed); this._promise.resolve(map); } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } protected class LoadRewardsListener implements Branch.BranchReferralStateChangedListener { private String _bucket; private Promise _promise; public LoadRewardsListener(String bucket, Promise promise) { this._bucket = bucket; this._promise = promise; } @Override public void onStateChanged(boolean changed, BranchError error) { if (error == null) { int credits = 0; if (this._bucket == null) { credits = Branch.getInstance().getCredits(); } else { credits = Branch.getInstance().getCreditsForBucket(this._bucket); } WritableMap map = new WritableNativeMap(); map.putInt("credits", credits); this._promise.resolve(map); } else { String errorMessage = error.getMessage(); Log.d(REACT_CLASS, errorMessage); this._promise.reject(errorMessage); } } } public void sendRNEvent(String eventName, @Nullable WritableMap params) { // This should avoid the crash in getJSModule() at startup ReactApplicationContext context = getReactApplicationContext(); Handler mainHandler = new Handler(context.getMainLooper()); Runnable poller = new Runnable() { private Runnable init(ReactApplicationContext _context, Handler _mainHandler, String _eventName, WritableMap _params) { mMainHandler = _mainHandler; mEventName = _eventName; mContext = _context; mParams = _params; return this; } final int pollDelayInMs = 100; final int maxTries = 300; int tries = 1; String mEventName; WritableMap mParams; Handler mMainHandler; ReactApplicationContext mContext; @Override public void run() { try { Log.d(REACT_CLASS, "Catalyst instance poller try " + Integer.toString(tries)); if (mContext.hasActiveCatalystInstance()) { Log.d(REACT_CLASS, "Catalyst instance active"); mContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(mEventName, mParams); } else { tries++; if (tries <= maxTries) { mMainHandler.postDelayed(this, pollDelayInMs); } else { Log.e(REACT_CLASS, "Could not get Catalyst instance"); } } } catch (Exception e) { e.printStackTrace(); } } }.init(context, mainHandler, eventName, params); Log.d(REACT_CLASS, "sendRNEvent"); mainHandler.post(poller); } private static Object getReadableMapObjectForKey(ReadableMap readableMap, String key) { switch (readableMap.getType(key)) { case Null: return "Null"; case Boolean: return readableMap.getBoolean(key); case Number: if (readableMap.getDouble(key) % 1 == 0) { return readableMap.getInt(key); } else { return readableMap.getDouble(key); } case String: return readableMap.getString(key); default: return "Unsupported Type"; } } private static JSONObject convertMapToJson(ReadableMap readableMap) throws JSONException { JSONObject object = new JSONObject(); ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); switch (readableMap.getType(key)) { case Null: object.put(key, JSONObject.NULL); break; case Boolean: object.put(key, readableMap.getBoolean(key)); break; case Number: object.put(key, readableMap.getDouble(key)); break; case String: object.put(key, readableMap.getString(key)); break; case Map: object.put(key, convertMapToJson(readableMap.getMap(key))); break; case Array: object.put(key, convertArrayToJson(readableMap.getArray(key))); break; } } return object; } private static JSONArray convertArrayToJson(ReadableArray readableArray) throws JSONException { JSONArray array = new JSONArray(); for (int i = 0; i < readableArray.size(); i++) { switch (readableArray.getType(i)) { case Null: break; case Boolean: array.put(readableArray.getBoolean(i)); break; case Number: array.put(readableArray.getDouble(i)); break; case String: array.put(readableArray.getString(i)); break; case Map: array.put(convertMapToJson(readableArray.getMap(i))); break; case Array: array.put(convertArrayToJson(readableArray.getArray(i))); break; } } return array; } private static WritableMap convertJsonToMap(JSONObject jsonObject) { if(jsonObject == null) { return null; } WritableMap map = new WritableNativeMap(); try { Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); if (value instanceof JSONObject) { map.putMap(key, convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { map.putArray(key, convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { map.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { map.putInt(key, (Integer) value); } else if (value instanceof Double) { map.putDouble(key, (Double) value); } else if (value instanceof String) { map.putString(key, (String) value); } else if (value == null || value == JSONObject.NULL) { map.putNull(key); } else { map.putString(key, value.toString()); } } } catch(JSONException ex) { map.putString("error", "Failed to convert JSONObject to WriteableMap: " + ex.getMessage()); } return map; } private static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException { WritableArray array = new WritableNativeArray(); for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); if (value instanceof JSONObject) { array.pushMap(convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { array.pushArray(convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { array.pushBoolean((Boolean) value); } else if (value instanceof Integer) { array.pushInt((Integer) value); } else if (value instanceof Double) { array.pushDouble((Double) value); } else if (value instanceof String) { array.pushString((String) value); } else { array.pushString(value.toString()); } } return array; } // Convert an arbitrary ReadableMap to a string-string hash of custom params for userCompletedAction. private static HashMap<String, String> convertMapToParams(ReadableMap map) { if (map == null) return null; HashMap<String, String> hash = new HashMap<>(); ReadableMapKeySetIterator iterator = map.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); switch (map.getType(key)) { case String: hash.put(key, map.getString(key)); case Boolean: hash.put(key, "" + map.getBoolean(key)); case Number: hash.put(key, "" + map.getDouble(key)); default: Log.w(REACT_CLASS, "Unsupported data type in params, ignoring"); } } return hash; } }
package com.stripe.android; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.Executor; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import com.stripe.android.Stripe.TokenCreator; import com.stripe.android.Stripe.TokenRequester; import com.stripe.android.model.Card; import com.stripe.android.model.Token; import com.stripe.exception.AuthenticationException; @RunWith(RobolectricTestRunner.class) public class StripeTest { private static final String DEFAULT_PUBLISHABLE_KEY = "pk_default"; private static final String DEFAULT_SECRET_KEY = "sk_default"; private static final Card DEFAULT_CARD = new Card(null, null, null, null); private static final TokenCallback DEFAULT_TOKEN_CALLBACK = new TokenCallback() { @Override public void onError(Exception error) { } @Override public void onSuccess(Token token) { } }; private static final String DEFAULT_TOKEN_ID = "tok_default"; @Test(expected = AuthenticationException.class) public void constructorShouldFailWithNullPublishableKey() throws AuthenticationException { new Stripe(null); } @Test(expected = AuthenticationException.class) public void constructorShouldFailWithEmptyPublishableKey() throws AuthenticationException { new Stripe(""); } @Test(expected = AuthenticationException.class) public void constructorShouldFailWithSecretKey() throws AuthenticationException { new Stripe(DEFAULT_SECRET_KEY); } @Test(expected = AuthenticationException.class) public void setDefaultPublishableKeyShouldFailWhenNull() throws AuthenticationException { Stripe stripe = new Stripe(); stripe.setDefaultPublishableKey(null); } @Test(expected = AuthenticationException.class) public void setDefaultPublishableKeyShouldFailWhenEmpty() throws AuthenticationException { Stripe stripe = new Stripe(); stripe.setDefaultPublishableKey(""); } @Test(expected = AuthenticationException.class) public void setDefaultPublishableKeyShouldFailWithSecretKey() throws AuthenticationException { Stripe stripe = new Stripe(); stripe.setDefaultPublishableKey(DEFAULT_SECRET_KEY); } @Test(expected = RuntimeException.class) public void requestTokenShouldFailWithNull() { Stripe stripe = new Stripe(); stripe.requestToken(null, null); } @Test(expected = RuntimeException.class) public void requestTokenShouldFailWithNullCard() { Stripe stripe = new Stripe(); stripe.requestToken(null, DEFAULT_TOKEN_CALLBACK); } @Test(expected = RuntimeException.class) public void requestTokenShouldFailWithNullTokencallback() { Stripe stripe = new Stripe(); stripe.requestToken(DEFAULT_TOKEN_ID, null); } @Test public void requestTokenShouldFailWithNullPublishableKey() { Stripe stripe = new Stripe(); stripe.requestToken( DEFAULT_TOKEN_ID, new ErrorTokenCallback(AuthenticationException.class)); } @Test public void requestTokenShouldCallTokenRequester() { final boolean[] tokenRequesterCalled = { false }; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenRequester = new TokenRequester() { @Override public void request(String tokenId, String publishableKey, Executor executor, TokenCallback callback) { tokenRequesterCalled[0] = true; } }; stripe.requestToken(DEFAULT_TOKEN_ID, DEFAULT_TOKEN_CALLBACK); assertTrue(tokenRequesterCalled[0]); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } @Test public void requestTokenShouldUseExecutor() { final Executor expectedExecutor = new Executor() { @Override public void execute(Runnable command) { } }; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenRequester = new TokenRequester() { @Override public void request(String tokenId, String publishableKey, Executor executor, TokenCallback callback) { assertEquals(expectedExecutor, executor); assertEquals(DEFAULT_TOKEN_ID, tokenId); assertEquals(DEFAULT_PUBLISHABLE_KEY, publishableKey); assertEquals(DEFAULT_TOKEN_CALLBACK, callback); } }; stripe.requestToken(DEFAULT_TOKEN_ID, expectedExecutor, DEFAULT_TOKEN_CALLBACK); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } @Test public void requestTokenShouldUseProvidedKey() { final String expectedPublishableKey = "pk_this_one"; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenRequester = new TokenRequester() { @Override public void request(String tokenId, String publishableKey, Executor executor, TokenCallback callback) { assertEquals(expectedPublishableKey, publishableKey); assertEquals(DEFAULT_TOKEN_ID, tokenId); assertNull(executor); assertEquals(DEFAULT_TOKEN_CALLBACK, callback); } }; stripe.requestToken(DEFAULT_TOKEN_ID, expectedPublishableKey, DEFAULT_TOKEN_CALLBACK); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } @Test(expected = RuntimeException.class) public void createTokenShouldFailWithNull() { Stripe stripe = new Stripe(); stripe.createToken(null, null); } @Test(expected = RuntimeException.class) public void createTokenShouldFailWithNullCard() { Stripe stripe = new Stripe(); stripe.createToken(null, DEFAULT_TOKEN_CALLBACK); } @Test(expected = RuntimeException.class) public void createTokenShouldFailWithNullTokencallback() { Stripe stripe = new Stripe(); stripe.createToken(DEFAULT_CARD, null); } @Test public void createTokenShouldFailWithNullPublishableKey() { Stripe stripe = new Stripe(); stripe.createToken(DEFAULT_CARD, new ErrorTokenCallback(AuthenticationException.class)); } @Test public void createTokenShouldCallTokenCreator() { final boolean[] tokenCreatorCalled = { false }; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenCreator = new TokenCreator() { @Override public void create(Card card, String publishableKey, Executor executor, TokenCallback callback) { tokenCreatorCalled[0] = true; } }; stripe.createToken(DEFAULT_CARD, DEFAULT_TOKEN_CALLBACK); assertTrue(tokenCreatorCalled[0]); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } @Test public void createTokenShouldUseExecutor() { final Executor expectedExecutor = new Executor() { @Override public void execute(Runnable command) { } }; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenCreator = new TokenCreator() { @Override public void create(Card card, String publishableKey, Executor executor, TokenCallback callback) { assertEquals(expectedExecutor, executor); assertEquals(DEFAULT_CARD, card); assertEquals(DEFAULT_PUBLISHABLE_KEY, publishableKey); assertEquals(DEFAULT_TOKEN_CALLBACK, callback); } }; stripe.createToken(DEFAULT_CARD, expectedExecutor, DEFAULT_TOKEN_CALLBACK); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } @Test public void createTokenShouldUseProvidedKey() { final String expectedPublishableKey = "pk_this_one"; try { Stripe stripe = new Stripe(DEFAULT_PUBLISHABLE_KEY); stripe.tokenCreator = new TokenCreator() { @Override public void create(Card card, String publishableKey, Executor executor, TokenCallback callback) { assertEquals(expectedPublishableKey, publishableKey); assertEquals(DEFAULT_CARD, card); assertNull(executor); assertEquals(DEFAULT_TOKEN_CALLBACK, callback); } }; stripe.createToken(DEFAULT_CARD, expectedPublishableKey, DEFAULT_TOKEN_CALLBACK); } catch (AuthenticationException e) { fail("Unexpected error: " + e.getMessage()); } } private static class ErrorTokenCallback extends TokenCallback { final Class<?> expectedError; public ErrorTokenCallback(Class<?> expectedError) { this.expectedError = expectedError; } @Override public void onError(Exception error) { assertEquals(expectedError, error.getClass()); } @Override public void onSuccess(Token token) { fail("onSuccess should not be called"); } } }
package org.spongepowered.api.data.key; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3i; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.entity.Banner; import org.spongepowered.api.block.entity.CommandBlock; import org.spongepowered.api.block.entity.EndGateway; import org.spongepowered.api.block.entity.MobSpawner; import org.spongepowered.api.block.entity.Piston; import org.spongepowered.api.block.entity.Sign; import org.spongepowered.api.block.entity.Structure; import org.spongepowered.api.block.entity.BlockEntity; import org.spongepowered.api.block.entity.carrier.Beacon; import org.spongepowered.api.block.entity.carrier.BrewingStand; import org.spongepowered.api.block.entity.carrier.Furnace; import org.spongepowered.api.block.entity.carrier.Hopper; import org.spongepowered.api.block.entity.carrier.BlockEntityCarrier; import org.spongepowered.api.data.meta.PatternLayer; import org.spongepowered.api.data.property.Properties; import org.spongepowered.api.data.type.ArtType; import org.spongepowered.api.data.type.BodyPart; import org.spongepowered.api.data.type.BodyParts; import org.spongepowered.api.data.type.CatType; import org.spongepowered.api.data.type.ChestAttachmentType; import org.spongepowered.api.data.type.ComparatorType; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.data.type.FoxType; import org.spongepowered.api.data.type.HandPreference; import org.spongepowered.api.data.type.Hinge; import org.spongepowered.api.data.type.HorseColor; import org.spongepowered.api.data.type.HorseStyle; import org.spongepowered.api.data.type.InstrumentType; import org.spongepowered.api.data.type.LlamaType; import org.spongepowered.api.data.type.MooshroomType; import org.spongepowered.api.data.type.NotePitch; import org.spongepowered.api.data.type.PandaType; import org.spongepowered.api.data.type.ParrotType; import org.spongepowered.api.data.type.PickupRule; import org.spongepowered.api.data.type.PortionType; import org.spongepowered.api.data.type.Profession; import org.spongepowered.api.data.type.RabbitType; import org.spongepowered.api.data.type.RailDirection; import org.spongepowered.api.data.type.SlabPortion; import org.spongepowered.api.data.type.StairShape; import org.spongepowered.api.data.type.StructureMode; import org.spongepowered.api.data.type.Surface; import org.spongepowered.api.data.type.VillagerType; import org.spongepowered.api.data.type.WireAttachmentType; import org.spongepowered.api.data.type.WoodType; import org.spongepowered.api.data.value.BoundedValue; import org.spongepowered.api.data.value.ListValue; import org.spongepowered.api.data.value.MapValue; import org.spongepowered.api.data.value.OptionalValue; import org.spongepowered.api.data.value.SetValue; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.data.value.WeightedCollectionValue; import org.spongepowered.api.effect.particle.ParticleType; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.effect.potion.PotionEffectType; import org.spongepowered.api.entity.AreaEffectCloud; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityArchetype; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.entity.ExperienceOrb; import org.spongepowered.api.entity.FallingBlock; import org.spongepowered.api.entity.Item; import org.spongepowered.api.entity.living.animal.Chicken; import org.spongepowered.api.entity.living.animal.Dolphin; import org.spongepowered.api.entity.living.animal.PolarBear; import org.spongepowered.api.entity.projectile.ShulkerBullet; import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.entity.explosive.FusedExplosive; import org.spongepowered.api.entity.hanging.ItemFrame; import org.spongepowered.api.entity.hanging.Painting; import org.spongepowered.api.entity.living.Ageable; import org.spongepowered.api.entity.living.Agent; import org.spongepowered.api.entity.living.ArmorStand; import org.spongepowered.api.entity.living.Bat; import org.spongepowered.api.entity.living.Humanoid; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.animal.Animal; import org.spongepowered.api.entity.living.animal.Cat; import org.spongepowered.api.entity.living.animal.Fox; import org.spongepowered.api.entity.living.animal.Horse; import org.spongepowered.api.entity.living.animal.Llama; import org.spongepowered.api.entity.living.animal.Mooshroom; import org.spongepowered.api.entity.living.animal.Ocelot; import org.spongepowered.api.entity.living.animal.Panda; import org.spongepowered.api.entity.living.animal.Parrot; import org.spongepowered.api.entity.living.animal.Pig; import org.spongepowered.api.entity.living.animal.Rabbit; import org.spongepowered.api.entity.living.animal.Sheep; import org.spongepowered.api.entity.living.animal.Wolf; import org.spongepowered.api.entity.living.golem.IronGolem; import org.spongepowered.api.entity.living.monster.Blaze; import org.spongepowered.api.entity.living.monster.Creeper; import org.spongepowered.api.entity.living.monster.Enderman; import org.spongepowered.api.entity.living.monster.Endermite; import org.spongepowered.api.entity.living.monster.Slime; import org.spongepowered.api.entity.living.monster.ZombiePigman; import org.spongepowered.api.entity.living.monster.ZombieVillager; import org.spongepowered.api.entity.living.monster.raider.illager.Vindicator; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.entity.living.player.gamemode.GameMode; import org.spongepowered.api.entity.living.trader.Trader; import org.spongepowered.api.entity.living.trader.Villager; import org.spongepowered.api.entity.projectile.DamagingProjectile; import org.spongepowered.api.entity.projectile.EyeOfEnder; import org.spongepowered.api.entity.projectile.FireworkRocket; import org.spongepowered.api.entity.projectile.arrow.Arrow; import org.spongepowered.api.entity.projectile.explosive.fireball.Fireball; import org.spongepowered.api.entity.vehicle.Boat; import org.spongepowered.api.entity.vehicle.minecart.CommandBlockMinecart; import org.spongepowered.api.entity.vehicle.minecart.Minecart; import org.spongepowered.api.fluid.FluidStackSnapshot; import org.spongepowered.api.item.FireworkEffect; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.enchantment.Enchantment; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.merchant.TradeOffer; import org.spongepowered.api.item.potion.PotionType; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.profile.property.ProfileProperty; import org.spongepowered.api.statistic.Statistic; import org.spongepowered.api.text.Text; import org.spongepowered.api.util.Axis; import org.spongepowered.api.util.Color; import org.spongepowered.api.util.Direction; import org.spongepowered.api.util.RespawnLocation; import org.spongepowered.api.util.generator.dummy.DummyObjectProvider; import org.spongepowered.api.util.rotation.Rotation; import org.spongepowered.api.util.weighted.WeightedSerializableObject; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.weather.Weather; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.UUID; /** * An enumeration of known {@link Key}s used throughout the API. */ @SuppressWarnings({"unused", "WeakerAccess"}) public final class Keys { // SORTFIELDS:ON /** * Represents the {@link Key} for the absorption amount of any * {@link Living} entity. */ public static final Key<Value<Double>> ABSORPTION = DummyObjectProvider.createExtendedFor(Key.class, "ABSORPTION"); /** * Represents the {@link Key} for the item a {@link Living} is using. * For example a player eating a food or blocking with a shield. * * <p>If there is no item, the snapshot will be empty. You can check this * with {@link ItemStackSnapshot#isEmpty()}.</p> */ public static final Key<Value<ItemStackSnapshot>> ACTIVE_ITEM = DummyObjectProvider.createExtendedFor(Key.class, "ACTIVE_ITEM"); /** * Represents the {@link Key} for the "affecting spawning" state of * {@link Player}s. * * <p>A {@link Player} who does not affect spawning will be treated as a * spectator in regards to spawning. A {@link MobSpawner} will not be * activated by his presence and mobs around him may naturally despawn * if there is no other Player around who affects spawning.</p> */ public static final Key<Value<Boolean>> AFFECTS_SPAWNING = DummyObjectProvider.createExtendedFor(Key.class, "AFFECTS_SPAWNING"); /** * Represents the {@link Key} for the age of any {@link Ageable} creature * in ticks. */ public static final Key<BoundedValue<Integer>> AGE = DummyObjectProvider.createExtendedFor(Key.class, "AGE"); /** * Represents the {@link Key} for whether an {@link Agent}s AI is enabled. */ public static final Key<Value<Boolean>> AI_ENABLED = DummyObjectProvider.createExtendedFor(Key.class, "AI_ENABLED"); /** * Represents the {@link Key} for how angry an {@link Entity} is. This * applies mostly to {@link ZombiePigman}. * * <p>Unlike {@link #ANGRY}, the aggressiveness represented by this key may * fade over time and the entity will become peaceful again once its anger * reaches its minimum.</p> */ public static final Key<BoundedValue<Integer>> ANGER = DummyObjectProvider.createExtendedFor(Key.class, "ANGER"); /** * Represents the {@link Key} for whether an {@link Entity} is currently * aggressive. This mostly applies to wolves. */ public static final Key<Value<Boolean>> ANGRY = DummyObjectProvider.createExtendedFor(Key.class, "ANGRY"); public static final Key<BoundedValue<Integer>> AREA_EFFECT_CLOUD_AGE = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_AGE"); public static final Key<Value<Color>> AREA_EFFECT_CLOUD_COLOR = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_COLOR"); public static final Key<BoundedValue<Integer>> AREA_EFFECT_CLOUD_DURATION = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_DURATION"); /** * Represents the {@link Key} for the amount of ticks the duration of an * {@link AreaEffectCloud} is increased or reduced when it applies its * effect. */ public static final Key<BoundedValue<Integer>> AREA_EFFECT_CLOUD_DURATION_ON_USE = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_DURATION_ON_USE"); public static final Key<Value<ParticleType>> AREA_EFFECT_CLOUD_PARTICLE_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_PARTICLE_TYPE"); /** * Represents the {@link Key} for the radius of an {@link AreaEffectCloud}. */ public static final Key<BoundedValue<Double>> AREA_EFFECT_CLOUD_RADIUS = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_RADIUS"); /** * Represents the {@link Key} for the amount the radius of an * {@link AreaEffectCloud} grows or shrinks each time it applies its * effect. */ public static final Key<BoundedValue<Double>> AREA_EFFECT_CLOUD_RADIUS_ON_USE = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_RADIUS_ON_USE"); /** * Represents the {@link Key} for the amount the radius of an * {@link AreaEffectCloud} grows or shrinks per tick. */ public static final Key<BoundedValue<Double>> AREA_EFFECT_CLOUD_RADIUS_PER_TICK = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_RADIUS_PER_TICK"); /** * Represents the {@link Key} for the delay (in ticks) after which an * {@link AreaEffectCloud} will reapply its effect on a previously * affected {@link Entity}. */ public static final Key<BoundedValue<Integer>> AREA_EFFECT_CLOUD_REAPPLICATION_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_REAPPLICATION_DELAY"); /** * Represents the {@link Key} for the duration in ticks after which an * {@link AreaEffectCloud} will begin to apply its effect to entities. */ public static final Key<BoundedValue<Integer>> AREA_EFFECT_CLOUD_WAIT_TIME = DummyObjectProvider.createExtendedFor(Key.class, "AREA_EFFECT_CLOUD_WAIT_TIME"); /** * Represents the {@link Key} for whether an {@link ArmorStand}'s arms are * visible. */ public static final Key<Value<Boolean>> ARMOR_STAND_HAS_ARMS = DummyObjectProvider.createExtendedFor(Key.class, "ARMOR_STAND_HAS_ARMS"); /** * Represents the {@link Key} for whether an {@link ArmorStand} has a * visible base plate. */ public static final Key<Value<Boolean>> ARMOR_STAND_HAS_BASE_PLATE = DummyObjectProvider.createExtendedFor(Key.class, "ARMOR_STAND_HAS_BASE_PLATE"); /** * Represents the {@link Key} for whether an {@link ArmorStand} is small. */ public static final Key<Value<Boolean>> ARMOR_STAND_IS_SMALL = DummyObjectProvider.createExtendedFor(Key.class, "ARMOR_STAND_IS_SMALL"); /** * Represents the {@link Key} for whether an {@link ArmorStand} has a * significantly smaller collision box in order to act as a marker. */ public static final Key<Value<Boolean>> ARMOR_STAND_MARKER = DummyObjectProvider.createExtendedFor(Key.class, "ARMOR_STAND_MARKER"); /** * Represents the {@link Key} for the type of {@link ArtType} shown by * (usually) a {@link Painting}. */ public static final Key<Value<ArtType>> ART = DummyObjectProvider.createExtendedFor(Key.class, "ART"); /** * Represents the {@link Key} for representing whether a {@link BlockState} * is "attached" to another block. */ public static final Key<Value<Boolean>> ATTACHED = DummyObjectProvider.createExtendedFor(Key.class, "ATTACHED"); /** * Represents the {@link Key} for the attachment {@link Surface} * of a button or lever. */ public static final Key<Value<Surface>> ATTACHMENT_SURFACE = DummyObjectProvider.createExtendedFor(Key.class, "ATTACHMENT_SURFACE"); /** * Represents the {@link Key} for the damage dealt by a * {@link DamagingProjectile}, e.g. an {@link Arrow}. */ public static final Key<BoundedValue<Double>> ATTACK_DAMAGE = DummyObjectProvider.createExtendedFor(Key.class, "ATTACK_DAMAGE"); /** * Represents the {@link Key} for representing the {@link Axis} direction * of a {@link BlockState}. */ public static final Key<Value<Axis>> AXIS = DummyObjectProvider.createExtendedFor(Key.class, "AXIS"); /** * Represents the {@link Key} for a {@link Banner}'s base {@link DyeColor}. */ public static final Key<Value<DyeColor>> BANNER_BASE_COLOR = DummyObjectProvider.createExtendedFor(Key.class, "BANNER_BASE_COLOR"); /** * Represents the {@link Key} for a {@link Banner}'s patterns. */ public static final Key<ListValue<PatternLayer>> BANNER_PATTERNS = DummyObjectProvider.createExtendedFor(Key.class, "BANNER_PATTERNS"); /** * Represents the {@link Key} for the width of the physical form of an * {@link Entity}. * * <p>Together with {@link #HEIGHT} this defines the size of an * {@link Entity}.</p> */ public static final Key<BoundedValue<Float>> BASE_SIZE = DummyObjectProvider.createExtendedFor(Key.class, "BASE_SIZE"); /** * Represents the {@link Key} for the base vehicle a passenger is riding * at the moment. This may be different from {@link Keys#VEHICLE} as the * vehicle an {@link Entity} is riding may itself be the passenger of * another vehicle. */ public static final Key<Value<EntitySnapshot>> BASE_VEHICLE = DummyObjectProvider.createExtendedFor(Key.class, "BASE_VEHICLE"); /** * Represents the {@link Key} for a {@link Beacon}'s primary effect. */ public static final Key<OptionalValue<PotionEffectType>> BEACON_PRIMARY_EFFECT = DummyObjectProvider.createExtendedFor(Key.class, "BEACON_PRIMARY_EFFECT"); /** * Represents the {@link Key} for a {@link Beacon}'s secondary effect. */ public static final Key<OptionalValue<PotionEffectType>> BEACON_SECONDARY_EFFECT = DummyObjectProvider.createExtendedFor(Key.class, "BEACON_SECONDARY_EFFECT"); /** * Represents the {@link Key} for the pore sides * of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<SetValue<Direction>> BIG_MUSHROOM_PORES = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES"); /** * Represents the {@link Key} for the {@link Direction#DOWN} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_DOWN = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_DOWN"); /** * Represents the {@link Key} for the {@link Direction#EAST} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_EAST = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_EAST"); /** * Represents the {@link Key} for the {@link Direction#NORTH} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_NORTH = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_NORTH"); /** * Represents the {@link Key} for the {@link Direction#SOUTH} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_SOUTH = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_SOUTH"); /** * Represents the {@link Key} for the {@link Direction#UP} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_UP = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_UP"); /** * Represents the {@link Key} for the {@link Direction#WEST} * pores side of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. */ public static final Key<Value<Boolean>> BIG_MUSHROOM_PORES_WEST = DummyObjectProvider.createExtendedFor(Key.class, "BIG_MUSHROOM_PORES_WEST"); /** * Represents the {@link Key} for the rotation of specific body parts. * * <p>This value provides a mapping, effectively combining the data * referenced by {@link #HEAD_ROTATION}, {@link #CHEST_ROTATION}, * {@link #RIGHT_ARM_ROTATION}, {@link #LEFT_ARM_ROTATION}, * {@link #RIGHT_LEG_ROTATION}, and {@link #LEFT_LEG_ROTATION}.</p> */ public static final Key<MapValue<BodyPart, Vector3d>> BODY_ROTATIONS = DummyObjectProvider.createExtendedFor(Key.class, "BODY_ROTATIONS"); /** * Represents the {@link Key} for the author of a * {@link ItemTypes#WRITTEN_BOOK}. */ public static final Key<Value<Text>> BOOK_AUTHOR = DummyObjectProvider.createExtendedFor(Key.class, "BOOK_AUTHOR"); /** * Represents the {@link Key} for the content of a * {@link ItemTypes#WRITTEN_BOOK}. * * <p>Use {@link Keys#PLAIN_BOOK_PAGES} if you wish to inspect the contents * of a {@link ItemTypes#WRITABLE_BOOK}.</p> */ public static final Key<ListValue<Text>> BOOK_PAGES = DummyObjectProvider.createExtendedFor(Key.class, "BOOK_PAGES"); /** * Represents the {@link Key} for the {@link BlockType}s able to be broken * by an item. */ public static final Key<SetValue<BlockType>> BREAKABLE_BLOCK_TYPES = DummyObjectProvider.createExtendedFor(Key.class, "BREAKABLE_BLOCK_TYPES"); /** * Represents the {@link Key} for whether an {@link Entity} can breed. */ public static final Key<Value<Boolean>> CAN_BREED = DummyObjectProvider.createExtendedFor(Key.class, "CAN_BREED"); /** * Represents the {@link Key} for whether a {@link FallingBlock} can drop * as an item. */ public static final Key<Value<Boolean>> CAN_DROP_AS_ITEM = DummyObjectProvider.createExtendedFor(Key.class, "CAN_DROP_AS_ITEM"); /** * Represents the {@link Key} for whether a {@link Humanoid} can fly. * * <p>For a {@link Player} this means he is able to toggle flight mode by * double-tapping his jump button.</p> */ public static final Key<Value<Boolean>> CAN_FLY = DummyObjectProvider.createExtendedFor(Key.class, "CAN_FLY"); /** * Represents the {@link Key} for whether a {@link Living} entity may * change blocks. This mostly applies to {@link Enderman} or * {@link Creeper}s, but also to some projectiles like {@link Fireball}s. */ public static final Key<Value<Boolean>> CAN_GRIEF = DummyObjectProvider.createExtendedFor(Key.class, "CAN_GRIEF"); /** * Represents the {@link Key} for whether a {@link FallingBlock} will place * itself upon landing. */ public static final Key<Value<Boolean>> CAN_PLACE_AS_BLOCK = DummyObjectProvider.createExtendedFor(Key.class, "CAN_PLACE_AS_BLOCK"); /** * Represents the {@link Key} for the type of a {@link Cat}. */ public static final Key<Value<CatType>> CAT_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "CAT_TYPE"); /** * Represents the {@link Key} for the attachment of a {@link BlockTypes#CHEST} * or {@link BlockTypes#TRAPPED_CHEST}. */ public static final Key<Value<ChestAttachmentType>> CHEST_ATTACHMENT = DummyObjectProvider.createExtendedFor(Key.class, "CHEST_ATTACHMENT"); /** * Represents the {@link Key} for the rotation of the * {@link BodyParts#CHEST}. */ public static final Key<Value<Vector3d>> CHEST_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "CHEST_ROTATION"); /** * Represents the {@link Key} for the {@link Color} of an * {@link ItemStack}. */ public static final Key<Value<Color>> COLOR = DummyObjectProvider.createExtendedFor(Key.class, "COLOR"); /** * Represents a key for the stored command, mostly related to * {@link CommandBlock}s and {@link CommandBlockMinecart}s. */ public static final Key<Value<String>> COMMAND = DummyObjectProvider.createExtendedFor(Key.class, "COMMAND"); /** * Represents the {@link Key} for representing the {@link ComparatorType} * of a {@link BlockState}. */ public static final Key<Value<ComparatorType>> COMPARATOR_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "COMPARATOR_TYPE"); /** * Represents the {@link Key} for representing the connected directions * of a {@link BlockState}. */ public static final Key<SetValue<Direction>> CONNECTED_DIRECTIONS = DummyObjectProvider.createExtendedFor(Key.class, "CONNECTED_DIRECTIONS"); /** * Represents the {@link Key} for representing the "connected to the east" * of a {@link BlockState}. */ public static final Key<Value<Boolean>> CONNECTED_EAST = DummyObjectProvider.createExtendedFor(Key.class, "CONNECTED_EAST"); /** * Represents the {@link Key} for representing the "connected to the north" * state of a {@link BlockState}. */ public static final Key<Value<Boolean>> CONNECTED_NORTH = DummyObjectProvider.createExtendedFor(Key.class, "CONNECTED_NORTH"); /** * Represents the {@link Key} for representing the "connected to the south" * state of a {@link BlockState}. */ public static final Key<Value<Boolean>> CONNECTED_SOUTH = DummyObjectProvider.createExtendedFor(Key.class, "CONNECTED_SOUTH"); /** * Represents the {@link Key} for representing the "connected to the west" * state of a {@link BlockState}. */ public static final Key<Value<Boolean>> CONNECTED_WEST = DummyObjectProvider.createExtendedFor(Key.class, "CONNECTED_WEST"); /** * Represents the {@link Key} for the amount of experience points stored * by an {@link ExperienceOrb}. */ public static final Key<BoundedValue<Integer>> CONTAINED_EXPERIENCE = DummyObjectProvider.createExtendedFor(Key.class, "CONTAINED_EXPERIENCE"); /** * Represents the {@link Key} for the amount of ticks a {@link Hopper} has * to cool down before transferring the next item. */ public static final Key<BoundedValue<Integer>> COOLDOWN = DummyObjectProvider.createExtendedFor(Key.class, "COOLDOWN"); /** * Represents the {@link Key} for whether a {@link Creeper} is charged. */ public static final Key<Value<Boolean>> CREEPER_CHARGED = DummyObjectProvider.createExtendedFor(Key.class, "CREEPER_CHARGED"); /** * Represents the {@link Key} for whether the next attack of an * {@link Entity} will be a critical hit. */ public static final Key<Value<Boolean>> CRITICAL_HIT = DummyObjectProvider.createExtendedFor(Key.class, "CRITICAL_HIT"); /** * Represents the {@link Key} for whether a custom name is visible on an * {@link Entity}. */ public static final Key<Value<Boolean>> CUSTOM_NAME_VISIBLE = DummyObjectProvider.createExtendedFor(Key.class, "CUSTOM_NAME_VISIBLE"); /** * Represents the {@link Key} for the damage dealt towards entities of a * specific {@link EntityType}. Types not present in this mapping will be * dealt damage to according to {@link #ATTACK_DAMAGE}. */ public static final Key<MapValue<EntityType, Double>> DAMAGE_ENTITY_MAP = DummyObjectProvider.createExtendedFor(Key.class, "DAMAGE_ENTITY_MAP"); /** * Represents the {@link Key} for representing at which distance a {@link BlockState} * will decay. This usually applies to leaves, for example {@link BlockTypes#OAK_LEAVES}. */ public static final Key<BoundedValue<Integer>> DECAY_DISTANCE = DummyObjectProvider.createExtendedFor(Key.class, "DECAY_DISTANCE"); /** * Represents the {@link Key} for the delay on a redstone repeater. */ public static final Key<BoundedValue<Integer>> DELAY = DummyObjectProvider.createExtendedFor(Key.class, "DELAY"); /** * Represents the {@link Key} for representing the despawn delay * of an {@link Item}. */ public static final Key<BoundedValue<Integer>> DESPAWN_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "DESPAWN_DELAY"); /** * Represents the {@link Key} for representing the {@link Direction} * of a {@link BlockState}. */ public static final Key<Value<Direction>> DIRECTION = DummyObjectProvider.createExtendedFor(Key.class, "DIRECTION"); /** * Represents the {@link Key} for representing the "disarmed" state * of a {@link BlockState}. This usually applies to * {@link BlockTypes#TRIPWIRE}s and {@link BlockTypes#TRIPWIRE_HOOK}s. */ public static final Key<Value<Boolean>> DISARMED = DummyObjectProvider.createExtendedFor(Key.class, "DISARMED"); /** * Represents the {@link Key} for the display name of an {@link Entity}, * {@link ItemStack} or {@link BlockEntity}. * * <p>On a {@link ItemTypes#WRITTEN_BOOK} item this will also set the title * of the book.</p> */ public static final Key<Value<Text>> DISPLAY_NAME = DummyObjectProvider.createExtendedFor(Key.class, "DISPLAY_NAME"); /** * Represents the {@link Key} for representing the dominant {@link HandPreference} * of a {@link Living} entity. * * <p><em>NOTE:</em> Does not apply to {@link Player}s as their * {@link HandPreference} can not be changed server-side. * See {@link Properties#DOMINANT_HAND}.</p> */ public static final Key<Value<HandPreference>> DOMINANT_HAND = DummyObjectProvider.createExtendedFor(Key.class, "DOMINANT_HAND"); /** * Represents the {@link Key} for the color of a dyeable block, item or * entity. */ public static final Key<Value<DyeColor>> DYE_COLOR = DummyObjectProvider.createExtendedFor(Key.class, "DYE_COLOR"); /** * Represents the {@link Key} for the time until a {@link Chicken} lays an {@link ItemTypes#EGG}. */ public static final Key<Value<Integer>> EGG_TIMER = DummyObjectProvider.createExtendedFor(Key.class, "EGG_TIMER"); /** * Represents the {@link Key} for representing the age of * an {@link EndGateway}. */ public static final Key<Value<Long>> END_GATEWAY_AGE = DummyObjectProvider.createExtendedFor(Key.class, "END_GATEWAY_AGE"); /** * Represents the {@link Key} for representing the teleport cooldown of * an {@link EndGateway}. */ public static final Key<Value<Integer>> END_GATEWAY_TELEPORT_COOLDOWN = DummyObjectProvider.createExtendedFor(Key.class, "END_GATEWAY_TELEPORT_COOLDOWN"); /** * Represents the {@link Key} for representing if the exact teleport location * should be used with a {@link EndGateway}. */ public static final Key<Value<Boolean>> EXACT_TELEPORT = DummyObjectProvider.createExtendedFor(Key.class, "EXACT_TELEPORT"); /** * Represents the {@link Key} for the current level of exhaustion of a * {@link Humanoid}. * * <p>Exhaustion will <em>decrease</em> on activities like walking, running * or jumping. Once it reaches 0, the {@link #SATURATION} will decrease and * the exhaustion level will be reset to its maximum.</p> */ public static final Key<BoundedValue<Double>> EXHAUSTION = DummyObjectProvider.createExtendedFor(Key.class, "EXHAUSTION"); /** * Represents the {@link Key} for representing the exit * portal {@link Vector3i location} of an {@link EndGateway}. */ public static final Key<Value<Vector3i>> EXIT_POSITION = DummyObjectProvider.createExtendedFor(Key.class, "EXIT_PORTAL"); /** * Represents the {@link Key} for the total experience a {@link Player} * requires to advance from his current level to the next one. */ public static final Key<BoundedValue<Integer>> EXPERIENCE_FROM_START_OF_LEVEL = DummyObjectProvider.createExtendedFor(Key.class, "EXPERIENCE_FROM_START_OF_LEVEL"); /** * Represents the {@link Key} for the current level a {@link Player} has. */ public static final Key<BoundedValue<Integer>> EXPERIENCE_LEVEL = DummyObjectProvider.createExtendedFor(Key.class, "EXPERIENCE_LEVEL"); /** * Represents the {@link Key} for the amount of experience a {@link Player} * has collected towards the next level. */ public static final Key<BoundedValue<Integer>> EXPERIENCE_SINCE_LEVEL = DummyObjectProvider.createExtendedFor(Key.class, "EXPERIENCE_SINCE_LEVEL"); /** * Represents the {@link Key} for how long an entity or * {@link Weather} will last before expiring. * * <p>Usually applies to {@link Weather}, {@link Endermite}s or {@link Item}s.</p> */ public static final Key<Value<Duration>> EXPIRATION_DURATION = DummyObjectProvider.createExtendedFor(Key.class, "EXPIRATION_DURATION"); public static final Key<OptionalValue<Integer>> EXPLOSION_RADIUS = DummyObjectProvider.createExtendedFor(Key.class, "EXPLOSION_RADIUS"); /** * Represents the {@link Key} for representing whether a {@link Piston} is * currently extended. */ public static final Key<Value<Boolean>> EXTENDED = DummyObjectProvider.createExtendedFor(Key.class, "EXTENDED"); /** * Represents the {@link Key} for whether a {@link FallingBlock} will * damage an {@link Entity} it lands on. */ public static final Key<Value<Boolean>> FALLING_BLOCK_CAN_HURT_ENTITIES = DummyObjectProvider.createExtendedFor(Key.class, "FALLING_BLOCK_CAN_HURT_ENTITIES"); /** * Represents the {@link Key} for the {@link BlockState} of a * {@link FallingBlock}. */ public static final Key<Value<BlockState>> FALLING_BLOCK_STATE = DummyObjectProvider.createExtendedFor(Key.class, "FALLING_BLOCK_STATE"); /** * Represents the {@link Key} for how much damage a {@link FallingBlock} * deals to {@link Living} entities it hits. * * <p>This damage is capped by {@link #MAX_FALL_DAMAGE}.</p> */ public static final Key<BoundedValue<Double>> FALL_DAMAGE_PER_BLOCK = DummyObjectProvider.createExtendedFor(Key.class, "FALL_DAMAGE_PER_BLOCK"); /** * Represents the {@link Key} for representing the distance an entity has * fallen. */ public static final Key<BoundedValue<Float>> FALL_DISTANCE = DummyObjectProvider.createExtendedFor(Key.class, "FALL_DISTANCE"); /** * Represents the {@link Key} for the amount of ticks a * {@link FallingBlock} has been falling for. */ public static final Key<Value<Integer>> FALL_TIME = DummyObjectProvider.createExtendedFor(Key.class, "FALL_TIME"); /** * Represents the {@link Key} for representing the "filled" state * of a {@link BlockState}. * * <p>Usually applies to {@link BlockTypes#END_PORTAL_FRAME}s.</p> */ public static final Key<Value<Boolean>> FILLED = DummyObjectProvider.createExtendedFor(Key.class, "FILLED"); /** * Represents the {@link Key} for the {@link FireworkEffect}s of a * {@link ItemTypes#FIREWORK_STAR}, {@link ItemTypes#FIREWORK_ROCKET} or a * {@link FireworkRocket}. */ public static final Key<ListValue<FireworkEffect>> FIREWORK_EFFECTS = DummyObjectProvider.createExtendedFor(Key.class, "FIREWORK_EFFECTS"); /** * Represents the {@link Key} for the flight duration of a firework. * * <p>The duration is tiered and will stay partially random. A rocket will * fly for roughly {@code modifier * 10 + (random number from 0 to 13)} * ticks in Vanilla Minecraft.</p> */ public static final Key<BoundedValue<Integer>> FIREWORK_FLIGHT_MODIFIER = DummyObjectProvider.createExtendedFor(Key.class, "FIREWORK_FLIGHT_MODIFIER"); /** * Represents the {@link Key} for the delay in ticks until the * {@link Entity} will be damaged by the fire. */ public static final Key<BoundedValue<Integer>> FIRE_DAMAGE_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "FIRE_DAMAGE_DELAY"); /** * Represents the {@link Key} for the amount of ticks an * {@link Entity} is still burning. */ public static final Key<BoundedValue<Integer>> FIRE_TICKS = DummyObjectProvider.createExtendedFor(Key.class, "FIRE_TICKS"); /** * Represents the {@link Key} for the time a {@link Player} first played * on the Server. */ public static final Key<Value<Instant>> FIRST_DATE_PLAYED = DummyObjectProvider.createExtendedFor(Key.class, "FIRST_DATE_PLAYED"); /** * Represents the {@link Key} for representing the * {@link FluidStackSnapshot} contained within an item container. Item * containers may include buckets and other mod added items. */ public static final Key<Value<FluidStackSnapshot>> FLUID_ITEM_STACK = DummyObjectProvider.createExtendedFor(Key.class, "FLUID_ITEM_STACK"); /** * Represents the {@link Key} for representing the "fluid level" state * of a {@link BlockState}. */ public static final Key<BoundedValue<Integer>> FLUID_LEVEL = DummyObjectProvider.createExtendedFor(Key.class, "FLUID_LEVEL"); /** * Represents the {@link Key} for representing the directional tank * information. */ public static final Key<MapValue<Direction, List<FluidStackSnapshot>>> FLUID_TANK_CONTENTS = DummyObjectProvider.createExtendedFor(Key.class, "FLUID_TANK_CONTENTS"); /** * Represents the {@link Key} for the speed at which an entity flies. */ public static final Key<Value<Double>> FLYING_SPEED = DummyObjectProvider.createExtendedFor(Key.class, "FLYING_SPEED"); /** * Represents the {@link Key} for the food level of a {@link Humanoid}. */ public static final Key<BoundedValue<Integer>> FOOD_LEVEL = DummyObjectProvider.createExtendedFor(Key.class, "FOOD_LEVEL"); /** * Represents the {@link Key} for the type of a {@link Fox}. */ public static final Key<Value<FoxType>> FOX_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "FOX_TYPE"); /** * Represents the {@link Key} for the time a {@link FusedExplosive}'s fuse * will burn before the explosion. */ public static final Key<Value<Integer>> FUSE_DURATION = DummyObjectProvider.createExtendedFor(Key.class, "FUSE_DURATION"); /** * Represents the {@link Key} for the {@link GameMode} a {@link Humanoid} * has. */ public static final Key<Value<GameMode>> GAME_MODE = DummyObjectProvider.createExtendedFor(Key.class, "GAME_MODE"); /** * Represents the {@link Key} for the generation of a * {@link ItemTypes#WRITTEN_BOOK}. Depending on the book's generation * it may be impossible to copy it. */ public static final Key<BoundedValue<Integer>> GENERATION = DummyObjectProvider.createExtendedFor(Key.class, "GENERATION"); /** * Represents the {@link Key} for representing whether an entity has a * glowing outline. */ public static final Key<Value<Boolean>> GLOWING = DummyObjectProvider.createExtendedFor(Key.class, "GLOWING"); /** * Represents the {@link Key} for representing the "got fish" state of a {@link Dolphin}. */ public static final Key<Value<Boolean>> GOT_FISH = DummyObjectProvider.createExtendedFor(Key.class, "GOT_FISH"); /** * Represents the {@link Key} for representing the "growth stage" state * of a {@link BlockState}. */ public static final Key<BoundedValue<Integer>> GROWTH_STAGE = DummyObjectProvider.createExtendedFor(Key.class, "GROWTH_STAGE"); /** * Represents the {@link Key} for whether an {@link Entity} is affected by * gravity. */ public static final Key<Value<Boolean>> HAS_GRAVITY = DummyObjectProvider.createExtendedFor(Key.class, "HAS_GRAVITY"); /** * Represents the {@link Key} for the direction an entities head is * rotated to. */ public static final Key<Value<Vector3d>> HEAD_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "HEAD_ROTATION"); /** * Represents the {@link Key} for a {@link Living}'s current health. */ public static final Key<BoundedValue<Double>> HEALTH = DummyObjectProvider.createExtendedFor(Key.class, "HEALTH"); /** * Represents the {@link Key} for how much health a half-heart on a * {@link Player}'s GUI will stand for. */ public static final Key<BoundedValue<Double>> HEALTH_SCALE = DummyObjectProvider.createExtendedFor(Key.class, "HEALTH_SCALE"); /** * Represents the {@link Key} for the height of the physical form of an * {@link Entity}. * * <p>Together with {@link #BASE_SIZE} this defines the size of an * {@link Entity}.</p> */ public static final Key<BoundedValue<Float>> HEIGHT = DummyObjectProvider.createExtendedFor(Key.class, "HEIGHT"); /** * Represents the {@link Key} for representing the "attributes hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_ATTRIBUTES = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_ATTRIBUTES"); /** * Represents the {@link Key} for representing the "can destroy hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_CAN_DESTROY = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_CAN_DESTROY"); /** * Represents the {@link Key} for representing the "can place hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_CAN_PLACE = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_CAN_PLACE"); /** * Represents the {@link Key} for representing the "enchantments hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_ENCHANTMENTS = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_ENCHANTMENTS"); /** * Represents the {@link Key} for representing the "miscellaneous hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_MISCELLANEOUS = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_MISCELLANEOUS"); /** * Represents the {@link Key} for representing the "unbreakable hidden" * state of an {@link ItemStack}. */ public static final Key<Value<Boolean>> HIDE_UNBREAKABLE = DummyObjectProvider.createExtendedFor(Key.class, "HIDE_UNBREAKABLE"); /** * Represents the {@link Key} for representing the {@link Hinge} * of a {@link BlockState}. */ public static final Key<Value<Hinge>> HINGE_POSITION = DummyObjectProvider.createExtendedFor(Key.class, "HINGE_POSITION"); /** * Represents the {@link Key} for the color of a {@link Horse}. */ public static final Key<Value<HorseColor>> HORSE_COLOR = DummyObjectProvider.createExtendedFor(Key.class, "HORSE_COLOR"); /** * Represents the {@link Key} for the style of a {@link Horse}. */ public static final Key<Value<HorseStyle>> HORSE_STYLE = DummyObjectProvider.createExtendedFor(Key.class, "HORSE_STYLE"); /** * Represents the {@link Key} for whether an {@link Item} will not despawn * for an infinite time. */ public static final Key<Value<Boolean>> INFINITE_DESPAWN_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "INFINITE_DESPAWN_DELAY"); /** * Represents the {@link Key} for representing the "is infinite" state * of the pickup delay of an {@link Item}. */ public static final Key<Value<Boolean>> INFINITE_PICKUP_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "INFINITE_PICKUP_DELAY"); /** * Represents the {@link Key} for the {@link InstrumentType} * of a {@link BlockTypes#NOTE_BLOCK}. */ public static final Key<Value<InstrumentType>> INSTRUMENT = DummyObjectProvider.createExtendedFor(Key.class, "INSTRUMENT"); /** * Represents the {@link Key} for the "inverted" state of * an {@link BlockTypes#DAYLIGHT_DETECTOR}. */ public static final Key<Value<Boolean>> INVERTED = DummyObjectProvider.createExtendedFor(Key.class, "INVERTED"); /** * Represents the {@link Key} for representing the "vanish" state * of an {@link Entity}. This will only simply render the entity as * vanish, but not prevent any entity updates being sent to clients. * To fully "vanish" an {@link Entity}, use {@link #VANISH}. */ public static final Key<Value<Boolean>> INVISIBLE = DummyObjectProvider.createExtendedFor(Key.class, "INVISIBLE"); /** * Represents the {@link Key} for the amount of ticks an {@link Entity} * will remain invulnerable for. */ public static final Key<BoundedValue<Integer>> INVULNERABILITY_TICKS = DummyObjectProvider.createExtendedFor(Key.class, "INVULNERABILITY_TICKS"); /** * Represents the {@link Key} for representing if an {@link Entity} * is invulnerable or not. * * <p>This does not protect from the void, players in creative mode, * and manual killing like the /kill command.</p> */ public static final Key<Value<Boolean>> INVULNERABLE = DummyObjectProvider.createExtendedFor(Key.class, "INVULNERABLE"); /** * Represents the {@link Key} for representing the "in-wall" state of * fences, for example {@link BlockTypes#OAK_FENCE}. */ public static final Key<Value<Boolean>> IN_WALL = DummyObjectProvider.createExtendedFor(Key.class, "IN_WALL"); /** * Represents the {@link Key} for the state whether a {@link Ageable} * entity is considered an "adult" and may affect breeding capabilities. */ public static final Key<Value<Boolean>> IS_ADULT = DummyObjectProvider.createExtendedFor(Key.class, "IS_ADULT"); /** * Represents the {@link Key} for whether a {@link Blaze} is currently * burning. * * <p>Unlike {@link #MAX_BURN_TIME}, the burning effect will not damage * the burning entity.</p> */ public static final Key<Value<Boolean>> IS_AFLAME = DummyObjectProvider.createExtendedFor(Key.class, "IS_AFLAME"); /** * Represents the {@link Key} for whether a {@link Player} is flying with an * {@link ItemTypes#ELYTRA}. */ public static final Key<Value<Boolean>> IS_ELYTRA_FLYING = DummyObjectProvider.createExtendedFor(Key.class, "IS_ELYTRA_FLYING"); /** * Represents the {@link Key} for whether an {@link Entity} is flying. * * <p>This key only tells whether an entity is flying at the moment. On a * {@link Player} it does not necessarily mean that the player may toggle * freely between flying and walking. To check whether a player may switch * his flying state, check {@link #CAN_FLY}.</p> */ public static final Key<Value<Boolean>> IS_FLYING = DummyObjectProvider.createExtendedFor(Key.class, "IS_FLYING"); public static final Key<Value<Boolean>> IS_JOHNNY = DummyObjectProvider.createExtendedFor(Key.class, "IS_JOHNNY"); /** * Represents the {@link Key} for whether a {@link Villager} is playing. * * <p>In Vanilla, this only applies to villagers that are considered * "babies" according to {@link #AGE}.</p> */ public static final Key<Value<Boolean>> IS_PLAYING = DummyObjectProvider.createExtendedFor(Key.class, "IS_PLAYING"); /** * Represents the {@link Key} for whether an {@link Enderman} is screaming. */ public static final Key<Value<Boolean>> IS_SCREAMING = DummyObjectProvider.createExtendedFor(Key.class, "IS_SCREAMING"); /** * Represents the {@link Key} for whether a {@link Sheep} is sheared. */ public static final Key<Value<Boolean>> IS_SHEARED = DummyObjectProvider.createExtendedFor(Key.class, "IS_SHEARED"); /** * Represents the {@link Key} for whether an {@link Entity} is silent. * * <p>A silent entity will not emit sounds or make noises.</p> */ public static final Key<Value<Boolean>> IS_SILENT = DummyObjectProvider.createExtendedFor(Key.class, "IS_SILENT"); /** * Represents the {@link Key} for whether a {@link Wolf} or {@link Ocelot} * is sitting. */ public static final Key<Value<Boolean>> IS_SITTING = DummyObjectProvider.createExtendedFor(Key.class, "IS_SITTING"); /** * Represents the {@link Key} for whether a {@link Bat} or {@link Player} * is sleeping. * * <p>If a player is considered sleeping as per this data value, he does * not need to be in bed in order for the other players to be able to * advance through the night by going to bed.</p> */ public static final Key<Value<Boolean>> IS_SLEEPING = DummyObjectProvider.createExtendedFor(Key.class, "IS_SLEEPING"); /** * Represents the {@link Key} for whether an {@link Entity} is sneaking. * * <p>Sneaking entities generally move slower and do not make walking * sounds.</p> */ public static final Key<Value<Boolean>> IS_SNEAKING = DummyObjectProvider.createExtendedFor(Key.class, "IS_SNEAKING"); /** * Represents the {@link Key} for whether an {@link Entity} is sprinting. */ public static final Key<Value<Boolean>> IS_SPRINTING = DummyObjectProvider.createExtendedFor(Key.class, "IS_SPRINTING"); /** * Represents the {@link Key} for if a {@link PolarBear} is currently standing. */ public static final Key<Value<Boolean>> IS_STANDING = DummyObjectProvider.createExtendedFor(Key.class, "IS_STANDING"); /** * Represents the {@link Key} for if an {@link Ocelot} is currently trusting of {@link Player}s. */ public static final Key<Value<Boolean>> IS_TRUSTING = DummyObjectProvider.createExtendedFor(Key.class, "IS_TRUSTING"); /** * Represents the {@link Key} for whether a {@link Wolf}, a * {@link BlockState} of {@link BlockTypes#SPONGE} or an {@link ItemStack} * of {@link ItemTypes#SPONGE} is wet. */ public static final Key<Value<Boolean>> IS_WET = DummyObjectProvider.createExtendedFor(Key.class, "IS_WET"); /** * Represents the {@link Key} for the {@link BlockState} represented by * an {@link ItemStack}. */ public static final Key<Value<BlockState>> ITEM_BLOCKSTATE = DummyObjectProvider.createExtendedFor(Key.class, "ITEM_BLOCKSTATE"); /** * Represents the {@link Key} for the durability of an {@link ItemStack}. */ public static final Key<BoundedValue<Integer>> ITEM_DURABILITY = DummyObjectProvider.createExtendedFor(Key.class, "ITEM_DURABILITY"); /** * Represents the {@link Key} for the enchantments applied to an * {@link ItemStack}. * * <p>This data is usually applicable to all types of armor, weapons and * tools. Enchantments that are only stored on an item stack in order to * be transferred to another item (like on * {@link ItemTypes#ENCHANTED_BOOK}s) use the {@link #STORED_ENCHANTMENTS} * key instead.)</p> */ public static final Key<ListValue<Enchantment>> ITEM_ENCHANTMENTS = DummyObjectProvider.createExtendedFor(Key.class, "ITEM_ENCHANTMENTS"); /** * Represents the {@link Key} for the displayed description ("lore") text * of an {@link ItemStack}. * * <p>The lore text is usually displayed when the player hovers his cursor * over the stack. For the contents of a book see {@link #BOOK_PAGES} * instead.</p> */ public static final Key<ListValue<Text>> ITEM_LORE = DummyObjectProvider.createExtendedFor(Key.class, "ITEM_LORE"); /** * Represents the {@link Key} for the knockback strength applied by an * {@link Arrow}. * * <p>For the knockback provided by hits with a weapon according to the * enchantment of the same name, see {@link #ITEM_ENCHANTMENTS}.</p> */ public static final Key<BoundedValue<Integer>> KNOCKBACK_STRENGTH = DummyObjectProvider.createExtendedFor(Key.class, "KNOCKBACK_STRENGTH"); /** * Represents the {@link Key} for the output yielded by the last command of * a {@link CommandBlock}. */ public static final Key<OptionalValue<Text>> LAST_COMMAND_OUTPUT = DummyObjectProvider.createExtendedFor(Key.class, "LAST_COMMAND_OUTPUT"); /** * Represents the {@link Key} for the last time a {@link User} has been * playing on the server. */ public static final Key<Value<Instant>> LAST_DATE_PLAYED = DummyObjectProvider.createExtendedFor(Key.class, "LAST_DATE_PLAYED"); /** * Represents the {@link Key} for representing the "layer" value of * {@link BlockTypes#SNOW} and other possible layered blocks. */ public static final Key<BoundedValue<Integer>> LAYER = DummyObjectProvider.createExtendedFor(Key.class, "LAYER"); /** * Represents the {@link Key} for the rotation of an {@link Entity}'s left * arm. */ public static final Key<Value<Vector3d>> LEFT_ARM_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "LEFT_ARM_ROTATION"); /** * Represents the {@link Key} for the rotation of an {@link Entity}'s left * leg. */ public static final Key<Value<Vector3d>> LEFT_LEG_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "LEFT_LEG_ROTATION"); /** * Represents the {@link Key} for the state that something is "lit", * for example a {@link BlockTypes#FURNACE} or {@link BlockTypes#REDSTONE_TORCH}. */ public static final Key<Value<Boolean>> LIT = DummyObjectProvider.createExtendedFor(Key.class, "LIT"); /** * Represents the {@link Key} for a {@link Llama}s carrying strength. The higher the strength, * the more items it can carry (effectively the size of inventory). */ public static final Key<BoundedValue<Integer>> LLAMA_STRENGTH = DummyObjectProvider.createExtendedFor(Key.class, "LLAMA_STRENGTH"); /** * Represents the {@link Key} for a {@link Llama}'s {@link LlamaType}. */ public static final Key<Value<LlamaType>> LLAMA_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "LLAMA_TYPE"); /** * Represents the {@link Key} for the token used to lock a * {@link BlockEntityCarrier}. */ public static final Key<Value<String>> LOCK_TOKEN = DummyObjectProvider.createExtendedFor(Key.class, "LOCK_TOKEN"); /** * Represents the {@link Key} for the maximum air supply a {@link Living} * may have. * * <p>For the current amount of air, check {@link #REMAINING_AIR}.</p> */ public static final Key<BoundedValue<Integer>> MAX_AIR = DummyObjectProvider.createExtendedFor(Key.class, "MAX_AIR"); /** * Represents the {@link Key} for the maximum amount of ticks a * {@link Furnace} can burn with the currently used fuel item. */ public static final Key<BoundedValue<Integer>> MAX_BURN_TIME = DummyObjectProvider.createExtendedFor(Key.class, "MAX_BURN_TIME"); /** * Represents the {@link Key} for the total time the current * {@link ItemStack} in a {@link Furnace} has to be cooked. */ public static final Key<BoundedValue<Integer>> MAX_COOK_TIME = DummyObjectProvider.createExtendedFor(Key.class, "MAX_COOK_TIME"); /** * Represents the {@link Key} for the maximum damage a {@link FallingBlock} * can deal. */ public static final Key<BoundedValue<Double>> MAX_FALL_DAMAGE = DummyObjectProvider.createExtendedFor(Key.class, "MAX_FALL_DAMAGE"); /** * Represents the {@link Key} for the maximum health of a {@link Living}. */ public static final Key<BoundedValue<Double>> MAX_HEALTH = DummyObjectProvider.createExtendedFor(Key.class, "MAX_HEALTH"); /** * Represents the {@link Key} for representing the "moisture" state of {@link BlockTypes#FARMLAND}. */ public static final Key<BoundedValue<Integer>> MOISTURE = DummyObjectProvider.createExtendedFor(Key.class, "MOISTURE"); /** * Represents the {@link Key} for the type of a {@link Mooshroom}. */ public static final Key<Value<MooshroomType>> MOOSHROOM_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "MOOSHROOM_TYPE"); /** * Represents the {@link Key} for the pitch of a {@link BlockTypes#NOTE_BLOCK}. */ public static final Key<Value<NotePitch>> NOTE_PITCH = DummyObjectProvider.createExtendedFor(Key.class, "NOTE_PITCH"); /** * Represents the {@link Key} for representing the "occupied" state of * beds, for example {@link BlockTypes#WHITE_BED}. */ public static final Key<Value<Boolean>> OCCUPIED = DummyObjectProvider.createExtendedFor(Key.class, "OCCUPIED"); /** * Represents the {@link Key} for representing a block's offset when inside * a {@link Minecart}. */ public static final Key<Value<Integer>> OFFSET = DummyObjectProvider.createExtendedFor(Key.class, "OFFSET"); /** * Represents the {@link Key} for representing the "open" state of * various door typed blocks. */ public static final Key<Value<Boolean>> OPEN = DummyObjectProvider.createExtendedFor(Key.class, "OPEN"); /** * Represents the {@link Key} for the type of a {@link Panda}. */ public static final Key<Value<PandaType>> PANDA_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "PANDA_TYPE"); /** * Represents the {@link ParrotType type} of a {@link Parrot}. */ public static final Key<Value<ParrotType>> PARROT_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "PARROT_TYPE"); /** * Represents the {@link Key} for the amount of ticks a {@link Furnace} has * already been burning with the current fuel item. * * <p>Once this value reaches the one of {@link #MAX_BURN_TIME}, the * furnace will require more fuel in order to keep burning.</p> */ public static final Key<BoundedValue<Integer>> PASSED_BURN_TIME = DummyObjectProvider.createExtendedFor(Key.class, "PASSED_BURN_TIME"); /** * Represents the {@link Key} for the amount of ticks a {@link Furnace} has * been cooking the current item for. * * <p>Once this value reaches the one of {@link #MAX_COOK_TIME}, the * item will be finished cooking.</p> */ public static final Key<BoundedValue<Integer>> PASSED_COOK_TIME = DummyObjectProvider.createExtendedFor(Key.class, "PASSED_COOK_TIME"); /** * Represents the {@link Key} for the entities that act as passengers for * an {@link Entity}. * * <p>For example, a {@link Player} riding on a {@link Horse} or a * {@link Pig} would be considered its passenger.</p> */ public static final Key<ListValue<UUID>> PASSENGERS = DummyObjectProvider.createExtendedFor(Key.class, "PASSENGERS"); /** * Represents the {@link Key} for whether an {@link Entity} or * {@link BlockState} will be prevented from despawning/decaying. * * <p>In Vanilla, entities may despawn if the player moves too far from * them. A persisting entity will not be removed due to no players being * near it.</p> */ public static final Key<Value<Boolean>> PERSISTENT = DummyObjectProvider.createExtendedFor(Key.class, "PERSISTENT"); /** * Represents the {@link Key} for representing the pickup delay * of an {@link Item}. */ public static final Key<BoundedValue<Integer>> PICKUP_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "PICKUP_DELAY"); /** * Represents the {@link Key} for the "pickup rule" of an {@link Arrow}. */ public static final Key<Value<PickupRule>> PICKUP_RULE = DummyObjectProvider.createExtendedFor(Key.class, "PICKUP_RULE"); /** * Represents the {@link Key} for whether a {@link Pig} is saddled. */ public static final Key<Value<Boolean>> PIG_SADDLE = DummyObjectProvider.createExtendedFor(Key.class, "PIG_SADDLE"); /** * Represents the {@link Key} for which block types an {@link ItemStack} * may be placed on. */ public static final Key<SetValue<BlockType>> PLACEABLE_BLOCKS = DummyObjectProvider.createExtendedFor(Key.class, "PLACEABLE_BLOCKS"); /** * Represents the {@link Key} for the content of a * {@link ItemTypes#WRITABLE_BOOK}. * * <p>Use {@link Keys#BOOK_PAGES} if you wish to get the contents of a * {@link ItemTypes#WRITTEN_BOOK}</p> */ public static final Key<ListValue<String>> PLAIN_BOOK_PAGES = DummyObjectProvider.createExtendedFor(Key.class, "PLAIN_BOOK_PAGES"); public static final Key<Value<Boolean>> PLAYER_CREATED = DummyObjectProvider.createExtendedFor(Key.class, "PLAYER_CREATED"); /** * Represents the {@link Key} for representing the {@link PortionType} * of a {@link BlockState}. */ public static final Key<Value<PortionType>> PORTION_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "PORTION_TYPE"); /** * Represents the {@link Key} for which potion effects are present on an * {@link Entity} or stored on an {@link ItemStack}. */ public static final Key<ListValue<PotionEffect>> POTION_EFFECTS = DummyObjectProvider.createExtendedFor(Key.class, "POTION_EFFECTS"); /** * Represents the {@link Key} for representing the potion type of an {@link ItemStack}. */ public static final Key<Value<PotionType>> POTION_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "POTION_TYPE"); /** * Represents the {@link Key} for representing the "power" state * of a {@link BlockState}. * * <p>Applies to blocks that may emit a Redstone signal of variable * strength, such as {@link BlockTypes#REDSTONE_WIRE}, * {@link BlockTypes#DAYLIGHT_DETECTOR}, * {@link BlockTypes#LIGHT_WEIGHTED_PRESSURE_PLATE} etc.</p> */ public static final Key<BoundedValue<Integer>> POWER = DummyObjectProvider.createExtendedFor(Key.class, "POWER"); /** * Represents the {@link Key} for representing the "powered" state * of a {@link BlockState}. * * <p>Applies to blocks that may be powered in order to emit a * Redstone signal of consistently maximum strength, such as * {@link BlockTypes#LEVER}, {@link BlockTypes#OAK_BUTTON}, * {@link BlockTypes#OAK_PRESSURE_PLATE}, and their stone * counterparts.</p> */ public static final Key<Value<Boolean>> POWERED = DummyObjectProvider.createExtendedFor(Key.class, "POWERED"); /** * Represents the {@link Key} for the {@link Villager} or {@link ZombieVillager}'s {@link Profession}. */ public static final Key<Value<Profession>> PROFESSION = DummyObjectProvider.createExtendedFor(Key.class, "PROFESSION"); /** * Represents the {@link Key} for the type of a {@link Rabbit}. */ public static final Key<Value<RabbitType>> RABBIT_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "RABBIT_TYPE"); /** * Represents the {@link Key} for representing the {@link RailDirection} * of a {@link BlockState}. */ public static final Key<Value<RailDirection>> RAIL_DIRECTION = DummyObjectProvider.createExtendedFor(Key.class, "RAIL_DIRECTION"); /** * Represents the {@link Key} for how much air a {@link Living} has left. */ public static final Key<BoundedValue<Integer>> REMAINING_AIR = DummyObjectProvider.createExtendedFor(Key.class, "REMAINING_AIR"); /** * Represents the {@link Key} for how many more ticks the current brewing * process of a {@link BrewingStand} will take. * * <p>If nothing is being brewed, the remaining brew time will be 0.</p> */ public static final Key<BoundedValue<Integer>> REMAINING_BREW_TIME = DummyObjectProvider.createExtendedFor(Key.class, "REMAINING_BREW_TIME"); /** * Represents the {@link Key} for representing the {@link BlockState} * inside a {@link Minecart}. */ public static final Key<Value<BlockState>> REPRESENTED_BLOCK = DummyObjectProvider.createExtendedFor(Key.class, "REPRESENTED_BLOCK"); /** * Represents the {@link Key} for the item displayed in an * {@link ItemFrame}. */ public static final Key<Value<ItemStackSnapshot>> REPRESENTED_ITEM = DummyObjectProvider.createExtendedFor(Key.class, "REPRESENTED_ITEM"); /** * Represents the {@link Key} for the player represented by a * {@link BlockTypes#PLAYER_HEAD} (and {@link BlockTypes#PLAYER_WALL_HEAD}) * block or a {@link ItemTypes#PLAYER_HEAD} item stack. */ public static final Key<Value<GameProfile>> REPRESENTED_PLAYER = DummyObjectProvider.createExtendedFor(Key.class, "REPRESENTED_PLAYER"); /** * Represents the {@link Key} for the spawn locations a {@link Player} * may have for various worlds based on {@link UUID} of the world. */ public static final Key<MapValue<UUID, RespawnLocation>> RESPAWN_LOCATIONS = DummyObjectProvider.createExtendedFor(Key.class, "RESPAWN_LOCATIONS"); /** * Represents the {@link Key} for the rotation of an {@link Entity}'s right * arm. */ public static final Key<Value<Vector3d>> RIGHT_ARM_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "RIGHT_ARM_ROTATION"); /** * Represents the {@link Key} for the rotation of an {@link Entity}'s right * leg. */ public static final Key<Value<Vector3d>> RIGHT_LEG_ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "RIGHT_LEG_ROTATION"); /** * Represents the {@link Key} for the {@link Rotation} of a block or an * {@link ItemFrame}. */ public static final Key<Value<Rotation>> ROTATION = DummyObjectProvider.createExtendedFor(Key.class, "ROTATION"); /** * Represents the {@link Key} for the current saturation of a {@link Living}. * * <p>When the saturation reaches 0, the {@link #FOOD_LEVEL} will decrease * and the saturation will be reset to maximum.</p> */ public static final Key<BoundedValue<Double>> SATURATION = DummyObjectProvider.createExtendedFor(Key.class, "SATURATION"); /** * Represents the {@link Key} for the "scale" for the size of an * {@link Entity}. */ public static final Key<BoundedValue<Float>> SCALE = DummyObjectProvider.createExtendedFor(Key.class, "SCALE"); /** * Represents the {@link Key} for representing the "should drop" state * of a {@link BlockState}. */ public static final Key<Value<Boolean>> SHOULD_DROP = DummyObjectProvider.createExtendedFor(Key.class, "SHOULD_DROP"); /** * Represents the {@link Key} for the lines displayed on a {@link Sign}. */ public static final Key<ListValue<Text>> SIGN_LINES = DummyObjectProvider.createExtendedFor(Key.class, "SIGN_LINES"); /** * Represents the {@link Key} for the skin of a {@link Humanoid}. * * <p>Skins can only be manipulated by supplying the UUID of a player * having that skin. The binary skin data is signed by Mojang so fully * customized skins are not possible.</p> */ public static final Key<Value<ProfileProperty>> SKIN = DummyObjectProvider.createExtendedFor(Key.class, "SKIN"); /** * Represents the {@link Key} for representing the "moisture" state of a {@link Dolphin}. */ public static final Key<Value<Integer>> SKIN_MOISTURE = DummyObjectProvider.createExtendedFor(Key.class, "SKIN_MOISTURE"); /** * Represents the {@link Key} for representing the {@link SlabPortion} * of a {@link BlockState}. */ public static final Key<Value<SlabPortion>> SLAB_PORTION = DummyObjectProvider.createExtendedFor(Key.class, "SLAB_PORTION"); /** * Represents the {@link Key} for the size of a {@link Slime}. */ public static final Key<BoundedValue<Integer>> SLIME_SIZE = DummyObjectProvider.createExtendedFor(Key.class, "SLIME_SIZE"); /** * Represents the {@link Key} for representing the "snowed" state * of a {@link BlockState}. */ public static final Key<Value<Boolean>> SNOWED = DummyObjectProvider.createExtendedFor(Key.class, "SNOWED"); /** * Represents the {@link Key} for the list of {@link EntityArchetype}s able * to be spawned by a {@link MobSpawner}. */ public static final Key<WeightedCollectionValue<EntityArchetype>> SPAWNER_ENTITIES = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_ENTITIES"); /** * Represents the {@link Key} for the maximum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Key<BoundedValue<Short>> SPAWNER_MAXIMUM_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_MAXIMUM_DELAY"); /** * Represents the {@link Key} for the maximum number of entities around a * {@link MobSpawner}. A spawner will not spawn entities if there are more * entities around than this value permits. */ public static final Key<BoundedValue<Short>> SPAWNER_MAXIMUM_NEARBY_ENTITIES = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_MAXIMUM_NEARBY_ENTITIES"); /** * Represents the {@link Key} for the minimum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Key<BoundedValue<Short>> SPAWNER_MINIMUM_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_MINIMUM_DELAY"); /** * Represents the {@link Key} for the next entity that will be spawned * by a {@link MobSpawner}. * * <p>Normally the entities to be spawned are determined by a random value * applied to the {@link #SPAWNER_ENTITIES} weighted collection. If this * value exists, it will override the random spawn with a definite one.</p> */ public static final Key<Value<WeightedSerializableObject<EntityArchetype>>> SPAWNER_NEXT_ENTITY_TO_SPAWN = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_NEXT_ENTITY_TO_SPAWN"); /** * Represents the {@link Key} for the remaining number of ticks to pass * before another attempt to spawn entities is made by a {@link MobSpawner}. */ public static final Key<BoundedValue<Short>> SPAWNER_REMAINING_DELAY = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_REMAINING_DELAY"); /** * Represents the {@link Key} for how close a {@link Player} has to be * around the {@link MobSpawner} in order for it to attempt to * spawn entities. */ public static final Key<BoundedValue<Short>> SPAWNER_REQUIRED_PLAYER_RANGE = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_REQUIRED_PLAYER_RANGE"); /** * Represents the {@link Key} for how many entities a {@link MobSpawner} has * spawned so far. */ public static final Key<BoundedValue<Short>> SPAWNER_SPAWN_COUNT = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_SPAWN_COUNT"); /** * Represents the {@link Key} for how far away from the * {@link MobSpawner} the entities spawned by it may appear. */ public static final Key<BoundedValue<Short>> SPAWNER_SPAWN_RANGE = DummyObjectProvider.createExtendedFor(Key.class, "SPAWNER_SPAWN_RANGE"); /** * Represents the {@link Key} for representing the {@link StairShape} * of a {@link BlockState}. */ public static final Key<Value<StairShape>> STAIR_SHAPE = DummyObjectProvider.createExtendedFor(Key.class, "STAIR_SHAPE"); /** * Represents the {@link Key} for the {@link Statistic}s of a {@link Player}. */ public static final Key<MapValue<Statistic, Long>> STATISTICS = DummyObjectProvider.createExtendedFor(Key.class, "STATISTICS"); /** * Represents the {@link Key} for the enchantments stored on an * {@link ItemStack}. * * <p>Stored enchantments are meant to be transferred. Usually this key * applies to {@link ItemTypes#ENCHANTED_BOOK} stacks. Enchantments * affecting the item stack are retrieved via {@link #ITEM_ENCHANTMENTS} * instead.</p> */ public static final Key<ListValue<Enchantment>> STORED_ENCHANTMENTS = DummyObjectProvider.createExtendedFor(Key.class, "STORED_ENCHANTMENTS"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<String>> STRUCTURE_AUTHOR = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_AUTHOR"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Boolean>> STRUCTURE_IGNORE_ENTITIES = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_IGNORE_ENTITIES"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Float>> STRUCTURE_INTEGRITY = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_INTEGRITY"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<StructureMode>> STRUCTURE_MODE = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_MODE"); /** * Represents the {@link Key} for representing the position of a {@link Structure}. */ public static final Key<Value<Vector3i>> STRUCTURE_POSITION = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_POSITION"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Boolean>> STRUCTURE_POWERED = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_POWERED"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Long>> STRUCTURE_SEED = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_SEED"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Boolean>> STRUCTURE_SHOW_AIR = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_SHOW_AIR"); /** * Represents the {@link Key} for representing the mode of a {@link Structure}. */ public static final Key<Value<Boolean>> STRUCTURE_SHOW_BOUNDING_BOX = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_SHOW_BOUNDING_BOX"); /** * Represents the {@link Key} for representing the size of a {@link Structure}. */ public static final Key<Value<Vector3i>> STRUCTURE_SIZE = DummyObjectProvider.createExtendedFor(Key.class, "STRUCTURE_SIZE"); /** * Represents the {@link Key} for representing the amount of "stuck arrows" * in {@link Living} entities. */ public static final Key<BoundedValue<Integer>> STUCK_ARROWS = DummyObjectProvider.createExtendedFor(Key.class, "STUCK_ARROWS"); /** * Represents a key for the amount of successful executions of a command * stored in a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Key<BoundedValue<Integer>> SUCCESS_COUNT = DummyObjectProvider.createExtendedFor(Key.class, "SUCCESS_COUNT"); /** * Represents the {@link Key} for representing the "suspended" state * of a {@link BlockState}. */ public static final Key<Value<Boolean>> SUSPENDED = DummyObjectProvider.createExtendedFor(Key.class, "SUSPENDED"); public static final Key<SetValue<String>> TAGS = DummyObjectProvider.createExtendedFor(Key.class, "TAGS"); /** * Represents the {@link Key} for the owner uuid of a tamed {@link Animal}. * * <p>Tamable animals in Vanilla may be a {@link Wolf}, an {@link Ocelot} * or a {@link Horse}.</p> */ public static final Key<OptionalValue<UUID>> TAMED_OWNER = DummyObjectProvider.createExtendedFor(Key.class, "TAMED_OWNER"); /** * Represents the {@link Key} for a targeted entity, * like by a {@link ShulkerBullet}. */ public static final Key<Value<EntitySnapshot>> TARGETED_ENTITY = DummyObjectProvider.createExtendedFor(Key.class, "TARGETED_ENTITY"); /** * Represents the {@link Key} for the location targeted by an * {@link EyeOfEnder} or a {@link Player}'s compass. */ public static final Key<Value<Vector3d>> TARGETED_LOCATION = DummyObjectProvider.createExtendedFor(Key.class, "TARGETED_LOCATION"); /** * Represents the {@link Key} for the remaining fuse time in ticks of a * {@link FusedExplosive}. This value may be set to an arbitrary value * if the explosive is not primed. */ public static final Key<Value<Integer>> TICKS_REMAINING = DummyObjectProvider.createExtendedFor(Key.class, "TICKS_REMAINING"); /** * Represents the {@link Key} for the full amount of experience a * {@link Player} has. */ public static final Key<BoundedValue<Integer>> TOTAL_EXPERIENCE = DummyObjectProvider.createExtendedFor(Key.class, "TOTAL_EXPERIENCE"); /** * Represents the {@link Key} for whether a {@link CommandBlock} does track * its output. * * <p>If this is set, the output of the most recent execution can be * retrieved using {@link #LAST_COMMAND_OUTPUT}.</p> */ public static final Key<Value<Boolean>> TRACKS_OUTPUT = DummyObjectProvider.createExtendedFor(Key.class, "TRACKS_OUTPUT"); /** * Represents the {@link Key} for the {@link TradeOffer}s offered by a * {@link Trader}. */ public static final Key<ListValue<TradeOffer>> TRADE_OFFERS = DummyObjectProvider.createExtendedFor(Key.class, "TRADE_OFFERS"); /** * Represents the {@link Key} for whether an {@link ItemStack} is unbreakable. * * <p>Setting this to {@code true} will prevent the item stack's * {@link #ITEM_DURABILITY} from changing.</p> */ public static final Key<Value<Boolean>> UNBREAKABLE = DummyObjectProvider.createExtendedFor(Key.class, "UNBREAKABLE"); /** * Represents the {@link Key} for whether or not changes to {@link Keys#SKIN} should * be reflected in an entitie's {@link GameProfile}. */ public static final Key<Value<Boolean>> UPDATE_GAME_PROFILE = DummyObjectProvider.createExtendedFor(Key.class, "UPDATE_GAME_PROFILE"); /** * Gets the {@link Key} for the "vanish" state of an {@link Entity}. * * <p>The presence of a vanished entity will not be made known to a client; * no packets pertaining to this entity are sent. Client-side, this entity * will cease to exist. Server-side it may still be targeted by hostile * entities or collide with other entities.</p> * * <p>Vanishing an {@link Entity} ridden by other entities (see * {@link #PASSENGERS} will cause problems.</p> * <p> * #VANISH */ public static final Key<Value<Boolean>> VANISH = DummyObjectProvider.createExtendedFor(Key.class, "VANISH"); /** * Represents the {@link Key} for whether an {@link Entity} ignores collision * with other entities. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.</p> */ public static final Key<Value<Boolean>> VANISH_IGNORES_COLLISION = DummyObjectProvider.createExtendedFor(Key.class, "VANISH_IGNORES_COLLISION"); /** * Represents the {@link Key} for * Gets the {@link Value} for whether an {@link Entity} can be targeted for * attack by another entity. This prevents neither {@link Player}s from * attacking the entity nor will it be protected from untargeted damage * like fire or explosions. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.}.</p> */ public static final Key<Value<Boolean>> VANISH_PREVENTS_TARGETING = DummyObjectProvider.createExtendedFor(Key.class, "VANISH_PREVENTS_TARGETING"); /** * Represents the {@link Key} for the vehicle an {@link Entity} is riding. * * <p>Vehicles may be nested as a vehicle might itself ride another entity. * To get the vehicle on bottom, use {@link #BASE_VEHICLE}.</p> */ public static final Key<Value<EntitySnapshot>> VEHICLE = DummyObjectProvider.createExtendedFor(Key.class, "VEHICLE"); /** * Represents the {@link Key} for the velocity of an {@link Entity}. */ public static final Key<Value<Vector3d>> VELOCITY = DummyObjectProvider.createExtendedFor(Key.class, "VELOCITY"); /** * Represents the {@link Key} for the type of a {@link Villager} or {@link ZombieVillager}. */ public static final Key<Value<VillagerType>> VILLAGER_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "VILLAGER_TYPE"); /** * Represents the {@link Key} for the speed at which an entity walks. */ public static final Key<Value<Double>> WALKING_SPEED = DummyObjectProvider.createExtendedFor(Key.class, "WALKING_SPEED"); /** * Represents the {@link Key} for whether a thrown {@link EyeOfEnder} will * shatter. */ public static final Key<Value<Boolean>> WILL_SHATTER = DummyObjectProvider.createExtendedFor(Key.class, "WILL_SHATTER"); /** * Represents the {@link Key} for how a {@link BlockTypes#REDSTONE_WIRE} is * connected to its neighboring blocks. */ public static final Key<MapValue<Direction, WireAttachmentType>> WIRE_ATTACHMENTS = DummyObjectProvider.createExtendedFor(Key.class, "WIRE_ATTACHMENTS"); /** * Represents the {@link Key} for how a {@link BlockTypes#REDSTONE_WIRE} is * connected to its neighboring block to the {@link Direction#EAST}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_EAST = DummyObjectProvider.createExtendedFor(Key.class, "WIRE_ATTACHMENT_EAST"); /** * Represents the {@link Key} for how a {@link BlockTypes#REDSTONE_WIRE} is * connected to its neighboring block to the {@link Direction#NORTH}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_NORTH = DummyObjectProvider.createExtendedFor(Key.class, "WIRE_ATTACHMENT_NORTH"); /** * Represents the {@link Key} for how a {@link BlockTypes#REDSTONE_WIRE} is * connected to its neighboring block to the {@link Direction#SOUTH}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_SOUTH = DummyObjectProvider.createExtendedFor(Key.class, "WIRE_ATTACHMENT_SOUTH"); /** * Represents the {@link Key} for how a {@link BlockTypes#REDSTONE_WIRE} is * connected to its neighboring block to the {@link Direction#WEST}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_WEST = DummyObjectProvider.createExtendedFor(Key.class, "WIRE_ATTACHMENT_WEST"); /** * Represents the {@link Key} for representing the {@link WoodType} * of a {@link Boat}. */ public static final Key<Value<WoodType>> WOOD_TYPE = DummyObjectProvider.createExtendedFor(Key.class, "WOOD_TYPE"); // SORTFIELDS:OFF private Keys() { throw new AssertionError("You should not be attempting to instantiate this class."); } }
package com.nullprogram.maze; import java.awt.Dimension; import javax.swing.JApplet; /** * Runs the maze animation as an applet. */ public class MazeApplet extends JApplet implements SolverListener { private static final long serialVersionUID = 7742407602430714892L; /* Defaults */ private static final int CELL_SIZE = 15; private static final int SPEED = 10; private static final int RESTART_DELAY = 3000; private int cellSize = CELL_SIZE; private int speed = SPEED; private Maze maze; private MazeDisplay display; private MazeSolver solution; @Override public final void init() { String paramSize = getParameter("cellsize"); if (paramSize != null) { cellSize = Integer.parseInt(paramSize); } Dimension size = getSize(); maze = new DepthMaze((int) (size.getWidth() / cellSize), (int) (size.getHeight() / cellSize), cellSize); if (display == null) { display = new MazeDisplay(maze); add(display); } else { display.setMaze(maze); } solution = new MazeSolver(maze, speed); solution.addListener(this); solution.addListener(display); } @Override public final void start() { solution.start(); } @Override public final void stop() { solution.stop(); } @Override public final void destroy() { stop(); } @Override public final void solveDone() { try { Thread.sleep(RESTART_DELAY); } catch (InterruptedException e) { return; } init(); start(); } @Override public final void solveStep() { } }
package org.opencms.gwt.client.ui.tree; import org.opencms.gwt.client.dnd.CmsDNDHandler.Orientation; import org.opencms.gwt.client.dnd.I_CmsDraggable; import org.opencms.gwt.client.dnd.I_CmsDropTarget; import org.opencms.gwt.client.ui.CmsList; import org.opencms.gwt.client.ui.CmsListItem; import org.opencms.gwt.client.ui.CmsToggleButton; import org.opencms.gwt.client.ui.I_CmsButton; import org.opencms.gwt.client.ui.I_CmsButton.ButtonStyle; import org.opencms.gwt.client.ui.I_CmsButton.Size; import org.opencms.gwt.client.ui.I_CmsListItem; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.I_CmsListTreeCss; import org.opencms.gwt.client.ui.input.CmsCheckBox; import org.opencms.gwt.client.util.CmsDomUtil; import org.opencms.gwt.client.util.CmsStyleVariable; import com.google.common.base.Function; import com.google.gwt.animation.client.Animation; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; /** * List tree item implementation.<p> * * Implemented as: * <pre> * &lt;li class='listTreeItem listTreeItem*state*'> * &lt;span class='listTreeItemImage'>&lt;/span> * &lt;div class='listTreeItemContent'>...*content*&lt;/div> * &lt;ul class='listTreeItemChildren'> * *children* * &lt;/ul> * &lt;/li> * </pre> * * Where state can be <code>opened</code>, <code>closed</code> or <code>leaf</code>.<p> * * @since 8.0.0 */ public class CmsTreeItem extends CmsListItem { /** The duration of the animations. */ public static final int ANIMATION_DURATION = 200; /** The CSS bundle used for this widget. */ private static final I_CmsListTreeCss CSS = I_CmsLayoutBundle.INSTANCE.listTreeCss(); /** The width of the opener. */ private static final int OPENER_WIDTH = 16; /** The children list. */ protected CmsList<CmsTreeItem> m_children; /** The element showing the open/close icon. */ protected CmsToggleButton m_opener; /** Flag to indicate if drag'n drop is enabled. 3-states: if <code>null</code> the tree decides. */ private Boolean m_dropEnabled; /** The style variable controlling this tree item's leaf/non-leaf state. */ private CmsStyleVariable m_leafStyleVar; /** Flag to indicate if open or closed. */ private boolean m_open; /** The item parent. */ private CmsTreeItem m_parentItem; /** The style variable controlling this tree item's open/closed state. */ private CmsStyleVariable m_styleVar; /** The tree reference. */ private CmsTree<CmsTreeItem> m_tree; /** * Creates a new list tree item containing a main widget and a check box.<p> * * @param showOpeners if true, show open/close icons * @param checkbox the check box * @param mainWidget the main widget */ public CmsTreeItem(boolean showOpeners, CmsCheckBox checkbox, Widget mainWidget) { this(showOpeners); addMainWidget(mainWidget); addCheckBox(checkbox); initContent(); if (!showOpeners) { hideOpeners(); } } /** * Creates a new list tree item containing a main widget.<p> * * @param showOpeners if true, show open/close icons * @param mainWidget the main widget */ public CmsTreeItem(boolean showOpeners, Widget mainWidget) { this(showOpeners); addMainWidget(mainWidget); initContent(); if (!showOpeners) { hideOpeners(); } } /** * Creates a new tree item with a 24px wide icon.<p> * * @param showOpeners if <code>true</code>, show open/close icons * @param mainWidget the main widget * @param icon the icon style name */ public CmsTreeItem(boolean showOpeners, Widget mainWidget, String icon) { this(showOpeners); addMainWidget(mainWidget); Label label = new Label(); label.addStyleName(icon); addDecoration(label, 28, true); initContent(); if (!showOpeners) { hideOpeners(); } } /** * Default constructor.<p> * * @param showOpeners if true, the opener icons should be shown */ protected CmsTreeItem(boolean showOpeners) { super(); m_styleVar = new CmsStyleVariable(this); m_leafStyleVar = new CmsStyleVariable(this); m_opener = createOpener(); addDecoration(m_opener, showOpeners ? OPENER_WIDTH : 0, true); m_children = new CmsList<CmsTreeItem>(); m_children.setStyleName(CSS.listTreeItemChildren()); m_panel.add(m_children); onChangeChildren(); m_open = true; setOpen(false); } /** * Returns the last opened item of a tree fragment.<p> * * @param item the tree item * @param stopLevel the level to stop at, set -1 to go to the very last opened item * @param requiresDropEnabled <code>true</code> if it is required the returned element to be drop enabled * * @return the last visible item of a tree fragment */ protected static CmsTreeItem getLastOpenedItem(CmsTreeItem item, int stopLevel, boolean requiresDropEnabled) { if (stopLevel != -1) { // stop level is set int currentLevel = getPathLevel(item.getPath()); if (currentLevel > stopLevel) { // we are past the stop level, prevent further checks stopLevel = -1; } else if (currentLevel == stopLevel) { // matches stop level return item; } } if (item.getChildCount() > 0) { int childIndex = item.getChildCount() - 1; CmsTreeItem child = item.getChild(childIndex); if (requiresDropEnabled) { while (!child.isDropEnabled()) { childIndex if (childIndex < 0) { return item; } child = item.getChild(childIndex); } } if (child.isOpen()) { return CmsTreeItem.getLastOpenedItem(child, stopLevel, requiresDropEnabled); } } return item; } /** * Method determining the path level by counting the number of '/'.<p> * Example: '/xxx/xxx/' has a path-level of 2.<p> * * @param path the path to test * * @return the path level */ protected static native int getPathLevel(String path)/*-{ return path.match(/\//g).length - 1; }-*/; /** * Unsupported operation.<p> * * @see org.opencms.gwt.client.ui.CmsListItem#add(com.google.gwt.user.client.ui.Widget) */ @Override public void add(Widget w) { throw new UnsupportedOperationException(); } /** * Adds a child list item.<p> * * @param item the child to add * * @see org.opencms.gwt.client.ui.CmsList#addItem(org.opencms.gwt.client.ui.I_CmsListItem) */ public void addChild(CmsTreeItem item) { m_children.addItem(item); adopt(item); } /** * @see com.google.gwt.user.client.ui.HasWidgets#clear() */ public void clear() { clearChildren(); } /** * Removes all children.<p> * * @see org.opencms.gwt.client.ui.CmsList#clearList() */ public void clearChildren() { for (int i = getChildCount(); i > 0; i removeChild(i - 1); } } /** * Closes all empty child entries.<p> */ public void closeAllEmptyChildren() { for (Widget child : m_children) { if (child instanceof CmsTreeItem) { CmsTreeItem item = (CmsTreeItem)child; if (item.isOpen()) { if (item.getChildCount() == 0) { item.setOpen(false); } else { item.closeAllEmptyChildren(); } } } } } /** * Returns the child tree item at the given position.<p> * * @param index the position * * @return the tree item * * @see org.opencms.gwt.client.ui.CmsList#getItem(int) */ public CmsTreeItem getChild(int index) { return m_children.getItem(index); } /** * Returns the tree item with the given id.<p> * * @param itemId the id of the item to retrieve * * @return the tree item * * @see org.opencms.gwt.client.ui.CmsList#getItem(String) */ public CmsTreeItem getChild(String itemId) { CmsTreeItem result = m_children.getItem(itemId); return result; } /** * Helper method which gets the number of children.<p> * * @return the number of children * * @see org.opencms.gwt.client.ui.CmsList#getWidgetCount() */ public int getChildCount() { return m_children.getWidgetCount(); } /** * Returns the children of this list item.<p> * * @return the children list */ public CmsList<? extends I_CmsListItem> getChildren() { return m_children; } /** * @see org.opencms.gwt.client.dnd.I_CmsDraggable#getDragHelper(I_CmsDropTarget) */ @Override public Element getDragHelper(I_CmsDropTarget target) { // disable animation to get a drag helper without any visible children boolean isAnimated = getTree().isAnimationEnabled(); getTree().setAnimationEnabled(false); setOpen(false); getTree().setAnimationEnabled(isAnimated); return super.getDragHelper(target); } /** * Returns the given item position.<p> * * @param item the item to get the position for * * @return the item position */ public int getItemPosition(CmsTreeItem item) { return m_children.getWidgetIndex(item); } /** * Returns the parent item.<p> * * @return the parent item */ public CmsTreeItem getParentItem() { return m_parentItem; } /** * @see org.opencms.gwt.client.ui.CmsListItem#getParentTarget() */ @Override public I_CmsDropTarget getParentTarget() { return getTree(); } /** * Returns the path of IDs for the this item.<p> * * @return a path of IDs separated by slash */ public String getPath() { StringBuffer path = new StringBuffer("/"); CmsTreeItem current = this; while (current != null) { path.insert(0, current.getId()).insert(0, "/"); current = current.getParentItem(); } String result = path.toString(); if (result.startsWith(" // This happens if the root item has an empty id. // In that case, we cut off the first slash. result = result.substring(1); } return result; } /** * Gets the tree to which this tree item belongs, or null if it does not belong to a tree.<p> * * @return a tree or <code>null</code> */ public CmsTree<CmsTreeItem> getTree() { return m_tree; } /** * Hides the open/close icons for this tree item and its descendants.<p> */ public void hideOpeners() { addStyleName(CSS.listTreeItemNoOpeners()); } /** * Inserts the given item at the given position.<p> * * @param item the item to insert * @param position the position * * @see org.opencms.gwt.client.ui.CmsList#insertItem(org.opencms.gwt.client.ui.I_CmsListItem, int) */ public void insertChild(CmsTreeItem item, int position) { m_children.insert(item, position); adopt(item); } /** * Checks if dropping is enabled.<p> * * @return <code>true</code> if dropping is enabled */ public boolean isDropEnabled() { if (m_dropEnabled != null) { return m_dropEnabled.booleanValue(); } CmsTree<?> tree = getTree(); if (tree == null) { return false; } return tree.isDropEnabled(); } /** * Checks if the item is open or closed.<p> * * @return <code>true</code> if open */ public boolean isOpen() { return m_open; } /** * @see org.opencms.gwt.client.dnd.I_CmsDraggable#onDragCancel() */ @Override public void onDragCancel() { CmsTreeItem parent = getParentItem(); if (parent != null) { parent.insertChild(this, parent.getItemPosition(this)); } super.onDragCancel(); } /** * Removes an item from the list.<p> * * @param item the item to remove * * @return the removed item * * @see org.opencms.gwt.client.ui.CmsList#removeItem(org.opencms.gwt.client.ui.I_CmsListItem) */ public CmsTreeItem removeChild(final CmsTreeItem item) { item.setParentItem(null); item.setTree(null); if ((m_tree != null) && m_tree.isAnimationEnabled()) { // could be null if already detached // animate (new Animation() { /** * @see com.google.gwt.animation.client.Animation#onComplete() */ @Override protected void onComplete() { super.onComplete(); m_children.removeItem(item); onChangeChildren(); } /** * @see com.google.gwt.animation.client.Animation#onUpdate(double) */ @Override protected void onUpdate(double progress) { item.getElement().getStyle().setOpacity(1 - progress); } }).run(ANIMATION_DURATION); } else { m_children.removeItem(item); onChangeChildren(); } return item; } /** * Removes the item identified by the given index from the list.<p> * * @param index the index of the item to remove * * @return the removed item * * @see org.opencms.gwt.client.ui.CmsList#remove(int) */ public CmsTreeItem removeChild(int index) { return removeChild(m_children.getItem(index)); } /** * Removes an item from the list.<p> * * @param itemId the id of the item to remove * * @return the removed item * * @see org.opencms.gwt.client.ui.CmsList#removeItem(String) */ public CmsTreeItem removeChild(String itemId) { return removeChild(m_children.getItem(itemId)); } /** * Removes the opener widget.<p> */ public void removeOpener() { removeDecorationWidget(m_opener, OPENER_WIDTH); } /** * Positions the drag and drop placeholder as a sibling or descendant of this element.<p> * * @param x the cursor client x position * @param y the cursor client y position * @param placeholder the placeholder * @param orientation the drag and drop orientation * * @return the placeholder index */ public int repositionPlaceholder(int x, int y, Element placeholder, Orientation orientation) { I_CmsDraggable draggable = null; if (getTree().getDnDHandler() != null) { draggable = getTree().getDnDHandler().getDraggable(); } Element itemElement = getListItemWidget().getElement(); // check if the mouse pointer is within the height of the element int top = CmsDomUtil.getRelativeY(y, itemElement); int height = itemElement.getOffsetHeight(); int index; String parentPath; boolean isParentDndEnabled; CmsTreeItem parentItem = getParentItem(); if (parentItem == null) { index = getTree().getItemPosition(this); parentPath = "/"; isParentDndEnabled = getTree().isRootDropEnabled(); } else { index = parentItem.getItemPosition(this); parentPath = getParentItem().getPath(); isParentDndEnabled = getParentItem().isDropEnabled(); } if (top < height) { // the mouse pointer is within the widget int diff = x - getListItemWidget().getAbsoluteLeft(); if ((draggable != this) && isDropEnabled() && (diff > 0) && (diff < 32)) { // over icon getTree().setOpenTimer(this); m_children.getElement().insertBefore(placeholder, m_children.getElement().getFirstChild()); getTree().setPlaceholderPath(getPath()); return 0; } getTree().cancelOpenTimer(); // In this case try to drop on the parent if (!isParentDndEnabled) { // we are not allowed to drop here // keeping old position return getTree().getPlaceholderIndex(); } int originalPathLevel = -1; if (draggable instanceof CmsTreeItem) { originalPathLevel = getPathLevel(((CmsTreeItem)draggable).getPath()) - 1; } if (shouldInsertIntoSiblingList(originalPathLevel, parentItem, index)) { @SuppressWarnings("null") CmsTreeItem previousSibling = parentItem.getChild(index - 1); if (previousSibling.isOpen()) { // insert as last into the last opened of the siblings tree fragment return CmsTreeItem.getLastOpenedItem( previousSibling, originalPathLevel, true).insertPlaceholderAsLastChild(placeholder); } } // insert place holder at the parent before the current item getElement().getParentElement().insertBefore(placeholder, getElement()); getTree().setPlaceholderPath(parentPath); return index; } else if ((draggable != this) && isOpen()) { getTree().cancelOpenTimer(); // the mouse pointer is on children for (int childIndex = 0; childIndex < getChildCount(); childIndex++) { CmsTreeItem child = getChild(childIndex); Element childElement = child.getElement(); boolean over = false; switch (orientation) { case HORIZONTAL: over = CmsDomUtil.checkPositionInside(childElement, x, -1); break; case VERTICAL: over = CmsDomUtil.checkPositionInside(childElement, -1, y); break; case ALL: default: over = CmsDomUtil.checkPositionInside(childElement, x, y); } if (over) { return child.repositionPlaceholder(x, y, placeholder, orientation); } } } getTree().cancelOpenTimer(); // keeping old position return getTree().getPlaceholderIndex(); } /** * Enables/disables dropping.<p> * * @param enabled <code>true</code> to enable, or <code>false</code> to disable */ public void setDropEnabled(boolean enabled) { if ((m_dropEnabled != null) && (m_dropEnabled.booleanValue() == enabled)) { return; } m_dropEnabled = Boolean.valueOf(enabled); } /** * Sets the tree item style to leaf, hiding the list opener.<p> * * @param isLeaf <code>true</code> to set to leaf style */ public void setLeafStyle(boolean isLeaf) { if (isLeaf) { m_leafStyleVar.setValue(CSS.listTreeItemLeaf()); } else { m_leafStyleVar.setValue(CSS.listTreeItemInternal()); } } /** * Opens or closes this tree item (i.e. shows or hides its descendants).<p> * * @param open if <code>true</code>, open the tree item, else close it */ public void setOpen(boolean open) { setOpen(open, true); } /** * Opens or closes this tree item (i.e. shows or hides its descendants).<p> * * @param open if <code>true</code>, open the tree item, else close it * @param fireEvents true if the open/close events should be fired */ public void setOpen(boolean open, boolean fireEvents) { if (m_open == open) { return; } m_open = open; executeOpen(fireEvents); CmsDomUtil.resizeAncestor(getParent()); } /** * Sets the parent item.<p> * * @param parentItem the parent item to set */ public void setParentItem(CmsTreeItem parentItem) { m_parentItem = parentItem; } /** * Sets the tree to which this tree item belongs.<p> * * This is automatically called when this tree item or one of its ancestors is inserted into a tree.<p> * * @param tree the tree into which the item has been inserted */ public void setTree(CmsTree<CmsTreeItem> tree) { m_tree = tree; for (Widget widget : m_children) { if (widget instanceof CmsTreeItem) { ((CmsTreeItem)widget).setTree(tree); } } } /** * Shows the open/close icons for this tree item and its descendants.<p> */ public void showOpeners() { removeStyleName(CSS.listTreeItemNoOpeners()); } /** * @see org.opencms.gwt.client.ui.I_CmsTruncable#truncate(java.lang.String, int) */ @Override public void truncate(String textMetricsPrefix, int widgetWidth) { super.truncate(textMetricsPrefix, widgetWidth); for (int i = 0; i < getChildCount(); i++) { getChild(i).truncate(textMetricsPrefix, widgetWidth); } } /** * Visits all nested tree items with the given visitor function.<p> * * @param visitor the visitor */ public void visit(Function<CmsTreeItem, Boolean> visitor) { visitor.apply(this); for (Widget child : m_children) { ((CmsTreeItem)child).visit(visitor); } } /** * Adopts the given item.<p> * * @param item the item to adopt */ protected void adopt(final CmsTreeItem item) { item.setParentItem(this); item.setTree(m_tree); onChangeChildren(); if ((m_tree != null) && m_tree.isAnimationEnabled()) { // could be null if not yet attached item.getElement().getStyle().setOpacity(0); // animate (new Animation() { /** * @see com.google.gwt.animation.client.Animation#onUpdate(double) */ @Override protected void onUpdate(double progress) { item.getElement().getStyle().setOpacity(progress); } }).run(ANIMATION_DURATION); } } /** * Creates the button for opening/closing this item.<p> * * @return a button */ protected CmsToggleButton createOpener() { final CmsToggleButton opener = new CmsToggleButton(); opener.setButtonStyle(ButtonStyle.FONT_ICON, null); opener.setSize(Size.small); opener.addStyleName(CSS.listTreeItemOpener()); opener.setUpFace("", I_CmsButton.TREE_PLUS); opener.setDownFace("", I_CmsButton.TREE_MINUS); opener.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent e) { setOpen(opener.isDown()); e.stopPropagation(); e.preventDefault(); } }); return opener; } /** * Executes the open call.<p> * * @param fireEvents if true, open/close events will be fired */ protected void executeOpen(boolean fireEvents) { m_styleVar.setValue(m_open ? CSS.listTreeItemOpen() : CSS.listTreeItemClosed()); setLeafStyle(false); m_children.getElement().getStyle().clearDisplay(); if (m_opener.isDown() != m_open) { m_opener.setDown(m_open); } if (fireEvents) { if (m_open) { fireOpen(); } else { fireClose(); } } // reset the leaf style according to the child count setLeafStyle(0 == getChildCount()); } /** * Fires the close event.<p> */ protected void fireClose() { if (m_tree != null) { m_tree.fireClose(this); } } /** * Fires the open event on the tree.<p> */ protected void fireOpen() { if (m_tree != null) { m_tree.fireOpen(this); } } /** * Inserts the placeholder element as last child of the children list. * Setting it's path as the current placeholder path and returning the new index.<p> * * @param placeholder the placeholder element * * @return the new index */ protected int insertPlaceholderAsLastChild(Element placeholder) { m_children.getElement().appendChild(placeholder); getTree().setPlaceholderPath(getPath()); return getChildCount(); } /** * Helper method which is called when the list of children changes.<p> */ protected void onChangeChildren() { setLeafStyle(0 == getChildCount()); } /** * Determines if the draggable should be inserted into the previous siblings children list.<p> * * @param originalPathLevel the original path level * @param parent the parent item * @param index the current index * * @return <code>true</code> if the item should be inserted into the previous siblings children list */ private boolean shouldInsertIntoSiblingList(int originalPathLevel, CmsTreeItem parent, int index) { if ((index <= 0) || (parent == null)) { return false; } return originalPathLevel != getPathLevel(parent.getPath()); } }
package org.opennms.netmgt.provision.persist; import java.util.Set; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Category; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.config.SnmpEventInfo; import org.opennms.netmgt.config.SnmpPeerFactory; import org.opennms.netmgt.dao.CategoryDao; import org.opennms.netmgt.dao.NodeDao; import org.opennms.netmgt.dao.ServiceTypeDao; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsMonitoredService; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsServiceType; import org.opennms.netmgt.model.OnmsIpInterface.PrimaryType; import org.opennms.netmgt.model.events.EventProxy; import org.opennms.netmgt.model.events.EventProxyException; import org.opennms.netmgt.provision.persist.requisition.Requisition; import org.opennms.netmgt.provision.persist.requisition.RequisitionAsset; import org.opennms.netmgt.provision.persist.requisition.RequisitionCategory; import org.opennms.netmgt.provision.persist.requisition.RequisitionInterface; import org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService; import org.opennms.netmgt.provision.persist.requisition.RequisitionNode; import org.opennms.netmgt.xml.event.Event; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.ModelAndView; public class DefaultNodeProvisionService implements NodeProvisionService { private EventProxy m_eventProxy; private CategoryDao m_categoryDao; private NodeDao m_nodeDao; private ServiceTypeDao m_serviceTypeDao; private ForeignSourceRepository m_foreignSourceRepository; private SnmpPeerFactory m_snmpPeerFactory; public ModelAndView getModelAndView(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("foreignSources", m_foreignSourceRepository.getForeignSources()); modelAndView.addObject("requisitions", m_foreignSourceRepository.getRequisitions()); modelAndView.addObject("categories", m_categoryDao.getAllCategoryNames()); modelAndView.addObject("success", Boolean.parseBoolean(request.getParameter("success"))); modelAndView.addObject("foreignSource", request.getParameter("foreignSource")); return modelAndView; } @Transactional public boolean provisionNode(String foreignSource, String foreignId, String nodeLabel, String ipAddress, String[] categories, String snmpCommunity, String snmpVersion, String deviceUsername, String devicePassword, String enablePassword) throws NodeProvisionException { if (log().isDebugEnabled()) { log().debug(String.format("adding SNMP community %s (%s)", snmpCommunity, snmpVersion)); } // Set the SNMP community name (if necessary) if (snmpCommunity != null && snmpVersion != null) { try { SnmpEventInfo info = new SnmpEventInfo(); info.setCommunityString(snmpCommunity); info.setFirstIPAddress(ipAddress); info.setVersion(snmpVersion); m_snmpPeerFactory.define(info); SnmpPeerFactory.saveCurrent(); } catch (Exception e) { throw new NodeProvisionException("unable to add SNMP community information", e); } } log().debug("creating requisition node"); // Create a requisition node based on the form input RequisitionInterface reqIface = new RequisitionInterface(); reqIface.setIpAddr(ipAddress); reqIface.setManaged(true); reqIface.setSnmpPrimary("P"); reqIface.setStatus(1); reqIface.putMonitoredService(new RequisitionMonitoredService("ICMP")); reqIface.putMonitoredService(new RequisitionMonitoredService("SNMP")); RequisitionNode reqNode = new RequisitionNode(); reqNode.setNodeLabel(nodeLabel); reqNode.setForeignId(foreignId); reqNode.putInterface(reqIface); for (String category : categories) { reqNode.putCategory(new RequisitionCategory(category)); } if (deviceUsername != null) { reqNode.putAsset(new RequisitionAsset("username", deviceUsername)); } if (devicePassword != null) { reqNode.putAsset(new RequisitionAsset("password", devicePassword)); } if (enablePassword != null) { reqNode.putAsset(new RequisitionAsset("enable", enablePassword)); } // Now save it to the requisition try { Requisition req = m_foreignSourceRepository.getRequisition(foreignSource); req.putNode(reqNode); log().debug("saving requisition node"); m_foreignSourceRepository.save(req); } catch (ForeignSourceRepositoryException e) { throw new RuntimeException("unable to retrieve foreign source '" + foreignSource + "'", e); } log().debug("creating database node"); // Create the basic node OnmsNode node = new OnmsNode(); node.setForeignSource(foreignSource); node.setForeignId(foreignId); node.setLabel(nodeLabel); OnmsIpInterface iface = new OnmsIpInterface(); iface.setNode(node); iface.setIpAddress(ipAddress); iface.setIsManaged("M"); iface.setIsSnmpPrimary(new PrimaryType('P')); node.addIpInterface(iface); Set<OnmsMonitoredService> services = new TreeSet<OnmsMonitoredService>(); services.add(new OnmsMonitoredService(iface, getServiceType("ICMP"))); services.add(new OnmsMonitoredService(iface, getServiceType("SNMP"))); iface.setMonitoredServices(services); log().debug("saving database node"); m_nodeDao.save(node); node = m_nodeDao.findByForeignId(foreignSource, foreignId); try { log().debug("sending event for new node ID " + node.getNodeId()); Event e = new Event(); e.setUei(EventConstants.NODE_ADDED_EVENT_UEI); e.setNodeid(node.getId()); e.setSource(getClass().getName()); e.setTime(EventConstants.formatToString(new java.util.Date())); m_eventProxy.send(e); e = new Event(); e.setUei(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI); e.setNodeid(node.getId()); e.setInterface(ipAddress); e.setSource(getClass().getName()); e.setTime(EventConstants.formatToString(new java.util.Date())); m_eventProxy.send(e); e = new Event(); e.setUei(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI); e.setNodeid(node.getId()); e.setInterface(ipAddress); e.setService("ICMP"); e.setService("SNMP"); e.setSource(getClass().getName()); e.setTime(EventConstants.formatToString(new java.util.Date())); m_eventProxy.send(e); } catch (EventProxyException ex) { throw new NodeProvisionException("Unable to send node events", ex); } return true; } private OnmsServiceType getServiceType(String string) { return m_serviceTypeDao.findByName(string); } public void setForeignSourceRepository(ForeignSourceRepository repository) { m_foreignSourceRepository = repository; } public void setCategoryDao(CategoryDao dao) { m_categoryDao = dao; } public void setSnmpPeerFactory(SnmpPeerFactory pf) { m_snmpPeerFactory = pf; } public void setNodeDao(NodeDao dao) { m_nodeDao = dao; } public void setServiceTypeDao(ServiceTypeDao dao) { m_serviceTypeDao = dao; } public void setEventProxy(EventProxy proxy) { m_eventProxy = proxy; } protected Category log() { return ThreadCategory.getInstance(getClass()); } }
package org.vovkasm.WebImage; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.annotation.ColorInt; import android.support.annotation.IntDef; import android.view.View; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.request.target.ViewTarget; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.FloatUtil; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.yoga.YogaConstants; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; class WebImageView extends View { @Retention(RetentionPolicy.SOURCE) @IntDef({SCALE_CONTAIN, SCALE_COVER, SCALE_STRETCH, SCALE_CENTER}) @interface ScaleType {} public static final int SCALE_CONTAIN = 0; public static final int SCALE_COVER = 1; public static final int SCALE_STRETCH = 2; public static final int SCALE_CENTER = 3; public static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT; public static final float DEFAULT_BORDER_RADIUS = 0f; private static RequestListener<Uri, GlideDrawable> requestListener = new WebImageViewRequestListener(); private Uri mUri; private @ScaleType int mScaleType = SCALE_CONTAIN; private BoxMetrics mBoxMetrics; private @ColorInt int mBorderColor = DEFAULT_BORDER_COLOR; private @ColorInt int[] mBorderColors = new int[]{DEFAULT_BORDER_COLOR, DEFAULT_BORDER_COLOR, DEFAULT_BORDER_COLOR, DEFAULT_BORDER_COLOR}; private float mBorderRadius = DEFAULT_BORDER_RADIUS; private float[] mBorderRadii = new float[]{YogaConstants.UNDEFINED, YogaConstants.UNDEFINED, YogaConstants.UNDEFINED, YogaConstants.UNDEFINED}; private Drawable mImgDrawable; private IBorder mBorder; public WebImageView(Context context) { super(context); mBoxMetrics = new BoxMetrics(mScaleType); configureBounds(); } public void setImageDrawable(Drawable drawable) { if (mImgDrawable != drawable) { int oldWidth = 0; int oldHeight = 0; if (mImgDrawable != null) { oldWidth = mImgDrawable.getIntrinsicWidth(); oldHeight = mImgDrawable.getIntrinsicHeight(); mImgDrawable.setCallback(null); unscheduleDrawable(mImgDrawable); } mImgDrawable = drawable; int mImgDrawableWidth = 0; int mImgDrawableHeight = 0; if (drawable != null) { drawable.setCallback(this); drawable.setVisible(getVisibility() == VISIBLE, true); mImgDrawableWidth = drawable.getIntrinsicWidth(); mImgDrawableHeight = drawable.getIntrinsicHeight(); } mBoxMetrics.setImageSize(mImgDrawableWidth, mImgDrawableHeight); configureBounds(); if (oldWidth != mImgDrawableWidth || oldHeight != mImgDrawableHeight) { requestLayout(); } invalidate(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (changed) { configureBounds(); } super.onLayout(changed, left, top, right, bottom); } private void configureBounds() { if (mImgDrawable == null) return; mImgDrawable.setBounds(mBoxMetrics.getContentBounds()); final float tl = YogaConstants.isUndefined(mBorderRadii[0]) ? mBorderRadius : mBorderRadii[0]; final float tr = YogaConstants.isUndefined(mBorderRadii[1]) ? mBorderRadius : mBorderRadii[1]; final float br = YogaConstants.isUndefined(mBorderRadii[2]) ? mBorderRadius : mBorderRadii[2]; final float bl = YogaConstants.isUndefined(mBorderRadii[3]) ? mBorderRadius : mBorderRadii[3]; mBoxMetrics.setRadii(tl, tr, br, bl); if (hasBorder()) { if (hasMonoBorder()) { MonoBorder monoBorder = null; if (mBorder instanceof MonoBorder) monoBorder = (MonoBorder)mBorder; if (monoBorder == null) { monoBorder = new MonoBorder(); } monoBorder.setColor(mBorderColors[0] == Color.TRANSPARENT ? mBorderColor : mBorderColors[0]); mBorder = monoBorder; } else { MulticolorBorder multicolorBorder = null; if (mBorder instanceof MulticolorBorder) multicolorBorder = (MulticolorBorder) mBorder; if (multicolorBorder == null) { multicolorBorder = new MulticolorBorder(); } final int lc = mBorderColors[0] == Color.TRANSPARENT ? mBorderColor : mBorderColors[0]; final int tc = mBorderColors[1] == Color.TRANSPARENT ? mBorderColor : mBorderColors[1]; final int rc = mBorderColors[2] == Color.TRANSPARENT ? mBorderColor : mBorderColors[2]; final int bc = mBorderColors[3] == Color.TRANSPARENT ? mBorderColor : mBorderColors[3]; multicolorBorder.setColors(lc, tc, rc, bc); mBorder = multicolorBorder; } mBorder.setMetrics(mBoxMetrics); } else { // no borders mBorder = null; } } public void setScaleType(@ScaleType int scaleType) { if (mScaleType == scaleType) { return; } mScaleType = scaleType; mBoxMetrics.setScaleType(scaleType); setWillNotCacheDrawing(mScaleType == SCALE_CENTER); requestLayout(); invalidate(); } public @ScaleType int getScaleType() { return mScaleType; } void setImageUri(Uri uri) { if (uri.equals(mUri)) return; mUri = uri; // TODO(vovkasm): use ThemedReactContext#getCurrentActivity so glide can follow lifecycle Glide.with(getContext()).load(mUri).listener(requestListener).into(new WebImageViewTarget(this)); } public void setBorderColor(@ColorInt int color) { if (mBorderColor == color) return; mBorderColor = color; invalidate(); } public void setBorderColor(@ColorInt int color, int side) { if (mBorderColors[side] == color) return; mBorderColors[side] = color; invalidate(); } public void setBorderRadius(float radius) { if (FloatUtil.floatsEqual(mBorderRadius,radius)) return; mBorderRadius = radius; invalidate(); } public void setBorderRadius(float radius, int index) { if (FloatUtil.floatsEqual(mBorderRadii[index], radius)) return; mBorderRadii[index] = radius; invalidate(); } public void setBoxMetrics(ShadowBoxMetrics shadowMetrics) { mBoxMetrics.setShadowMetrics(shadowMetrics); configureBounds(); requestLayout(); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mImgDrawable == null) return; int saveCount = canvas.getSaveCount(); canvas.save(); if (mBorder != null) { mBorder.draw(canvas); } canvas.clipPath(mBoxMetrics.getContentPath()); final Matrix contentMatrix = mBoxMetrics.getContentMatrix(); if (contentMatrix != null) { canvas.concat(contentMatrix); } mImgDrawable.draw(canvas); canvas.restoreToCount(saveCount); } private boolean hasBorder() { return mBoxMetrics != null && mBoxMetrics.hasBorder(); } private boolean hasMonoBorder() { return (mBorderColors[0] == mBorderColors[1] && mBorderColors[1] == mBorderColors[2] && mBorderColors[2] == mBorderColors[3]); } private static class WebImageViewRequestListener implements RequestListener<Uri,GlideDrawable> { @Override public boolean onException(Exception e, Uri uri, Target<GlideDrawable> target, boolean isFirstResource) { if (!(target instanceof WebImageViewTarget)) return false; WebImageView view = ((WebImageViewTarget) target).getView(); WritableMap event = Arguments.createMap(); event.putString("error", e.getMessage()); event.putString("uri", uri.toString()); ThemedReactContext context = (ThemedReactContext) view.getContext(); context.getJSModule(RCTEventEmitter.class).receiveEvent(view.getId(), "onWebImageError", event); return false; } @Override public boolean onResourceReady(GlideDrawable resource, Uri uri, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { return false; } } private static class WebImageViewTarget extends ViewTarget<WebImageView, GlideDrawable> { WebImageViewTarget(WebImageView view) { super(view); } @Override public void onResourceReady(GlideDrawable drawable, GlideAnimation<? super GlideDrawable> glideAnimation) { this.view.setImageDrawable(drawable); } public WebImageView getView() { return view; } } }
package org.wiztools.restclient.xml; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import nu.xom.ParsingException; import org.wiztools.restclient.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import nu.xom.Attribute; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.Serializer; import org.wiztools.restclient.test.TestFailureResultBean; import org.wiztools.restclient.test.TestResultBean; /** * * @author rsubramanian */ public final class XMLUtil { private XMLUtil() { } private static final Logger LOG = Logger.getLogger(XMLUtil.class.getName()); private static final String[] VERSIONS = new String[]{ "2.0", "2.1", "2.2a1", "2.2a2", "2.2", RCConstants.VERSION }; public static final String XML_MIME = "application/xml"; public static final String XML_DEFAULT_ENCODING = "UTF-8"; static { // Sort the version array for binary search Arrays.sort(VERSIONS); } private static void checkIfVersionValid(final String restVersion) throws XMLException { if (restVersion == null) { throw new XMLException("Attribute `version' not available for root element <rest-client>"); } int res = Arrays.binarySearch(VERSIONS, restVersion); if (res == -1) { throw new XMLException("Version not supported"); } } public static Document request2XML(final RequestBean bean) throws XMLException { try { Element reqRootElement = new Element("rest-client"); // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); reqRootElement.addAttribute(versionAttributes); Element reqChildElement = new Element("request"); Element reqChildSubElement = null; Element reqChildSubSubElement = null; // HTTP Version reqChildSubElement = new Element("http-version"); reqChildSubElement.appendChild(bean.getHttpVersion().versionNumber()); reqChildElement.appendChild(reqChildSubElement); // creating the URL child element reqChildSubElement = new Element("URL"); reqChildSubElement.appendChild(bean.getUrl().toString()); reqChildElement.appendChild(reqChildSubElement); // creating the method child element reqChildSubElement = new Element("method"); reqChildSubElement.appendChild(bean.getMethod()); reqChildElement.appendChild(reqChildSubElement); // creating the auth-methods child element List<String> authMethods = bean.getAuthMethods(); if (authMethods.size() > 0) { if (authMethods != null && authMethods.size() > 0) { reqChildSubElement = new Element("auth-methods"); String methods = ""; for (String authMethod : authMethods) { methods = methods + authMethod + ","; } String authenticationMethod = methods.substring(0, methods.length() == 0 ? 0 : methods.length() - 1); reqChildSubElement.appendChild(authenticationMethod); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-preemptive child element Boolean authPreemptive = bean.isAuthPreemptive(); if (authPreemptive != null) { reqChildSubElement = new Element("auth-preemptive"); reqChildSubElement.appendChild(authPreemptive.toString()); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-host child element String authHost = bean.getAuthHost(); if (authHost != null) { reqChildSubElement = new Element("auth-host"); reqChildSubElement.appendChild(authHost); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-realm child element String authRealm = bean.getAuthRealm(); if (authRealm != null) { reqChildSubElement = new Element("auth-realm"); reqChildSubElement.appendChild(authRealm); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-username child element String authUsername = bean.getAuthUsername(); if (authUsername != null) { reqChildSubElement = new Element("auth-username"); reqChildSubElement.appendChild(authUsername); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-password child element String authPassword = null; if (bean.getAuthPassword() != null) { authPassword = new String(bean.getAuthPassword()); String encPassword = Base64.encodeObject(authPassword); reqChildSubElement = new Element("auth-password"); reqChildSubElement.appendChild(encPassword); reqChildElement.appendChild(reqChildSubElement); } } // Creating SSL elements String sslTruststore = bean.getSslTrustStore(); if (!Util.isStrEmpty(sslTruststore)) { // 1. Create truststore entry reqChildSubElement = new Element("ssl-truststore"); reqChildSubElement.appendChild(sslTruststore); reqChildElement.appendChild(reqChildSubElement); // 2. Create password entry String sslPassword = new String(bean.getSslTrustStorePassword()); String encPassword = Base64.encodeObject(sslPassword); reqChildSubElement = new Element("ssl-truststore-password"); reqChildSubElement.appendChild(encPassword); reqChildElement.appendChild(reqChildSubElement); } // creating the headers child element Map<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { reqChildSubElement = new Element("headers"); for (String key : headers.keySet()) { String value = headers.get(key); reqChildSubSubElement = new Element("header"); reqChildSubSubElement.addAttribute(new Attribute("key", key)); reqChildSubSubElement.addAttribute(new Attribute("value", value)); reqChildSubElement.appendChild(reqChildSubSubElement); } reqChildElement.appendChild(reqChildSubElement); } // creating the body child element ReqEntityBean rBean = bean.getBody(); if (rBean != null) { reqChildSubElement = new Element("body"); String contentType = rBean.getContentType(); String charSet = rBean.getCharSet(); String body = rBean.getBody(); reqChildSubElement.addAttribute(new Attribute("content-type", contentType)); reqChildSubElement.addAttribute(new Attribute("charset", charSet)); reqChildSubElement.appendChild(body); reqChildElement.appendChild(reqChildSubElement); } // creating the test-script child element String testScript = bean.getTestScript(); if (testScript != null) { reqChildSubElement = new Element("test-script"); reqChildSubElement.appendChild(testScript); reqChildElement.appendChild(reqChildSubElement); } reqRootElement.appendChild(reqChildElement); Document xomDocument = new Document(reqRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } private static Map<String, String> getHeadersFromHeaderNode(final Element node) throws XMLException { Map<String, String> m = new LinkedHashMap<String, String>(); for (int i = 0; i < node.getChildElements().size(); i++) { Element headerElement = node.getChildElements().get(i) ; if (!"header".equals(headerElement.getQualifiedName())) { throw new XMLException("<headers> element should contain only <header> elements"); } m.put(headerElement.getAttributeValue("key"), headerElement.getAttributeValue("value")); } return m; } public static RequestBean xml2Request(final Document doc) throws MalformedURLException, XMLException { RequestBean requestBean = new RequestBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version checkIfVersionValid(rootNode.getAttributeValue("version")); // assign rootnode to current node and also finding 'request' node Element tNode = null; Element requestNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <request>"); } // minimum one request element is present in xml if (rootNode.getFirstChildElement("request") == null) { throw new XMLException("The child node of <rest-client> should be <request>"); } requestNode = rootNode.getFirstChildElement("request"); for (int i = 0; i < requestNode.getChildElements().size(); i++) { tNode = requestNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("http-version".equals(nodeName)) { String t = tNode.getValue(); HTTPVersion httpVersion = "1.1".equals(t) ? HTTPVersion.HTTP_1_1 : HTTPVersion.HTTP_1_0; requestBean.setHttpVersion(httpVersion); } else if ("URL".equals(nodeName)) { URL url = new URL(tNode.getValue()); requestBean.setUrl(url); } else if ("method".equals(nodeName)) { requestBean.setMethod(tNode.getValue()); } else if ("auth-methods".equals(nodeName)) { String[] authenticationMethods = tNode.getValue().split(","); for (int j = 0; j < authenticationMethods.length; j++) { requestBean.addAuthMethod(authenticationMethods[j]); } } else if ("auth-preemptive".equals(nodeName)) { if (tNode.getValue().equals("true")) { requestBean.setAuthPreemptive(true); } else { requestBean.setAuthPreemptive(false); } } else if ("auth-host".equals(nodeName)) { requestBean.setAuthHost(tNode.getValue()); } else if ("auth-realm".equals(nodeName)) { requestBean.setAuthRealm(tNode.getValue()); } else if ("auth-username".equals(nodeName)) { requestBean.setAuthUsername(tNode.getValue()); } else if ("auth-password".equals(nodeName)) { String password = (String) Base64.decodeToObject(tNode.getValue()); requestBean.setAuthPassword(password.toCharArray()); } else if ("ssl-truststore".equals(nodeName)) { String sslTrustStore = tNode.getValue(); requestBean.setSslTrustStore(sslTrustStore); } else if ("ssl-truststore-password".equals(nodeName)) { String sslTrustStorePassword = (String) Base64.decodeToObject(tNode.getValue()); requestBean.setSslTrustStorePassword(sslTrustStorePassword.toCharArray()); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { requestBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { requestBean.setBody(new ReqEntityBean(tNode.getValue(), tNode.getAttributeValue("content-type"), tNode.getAttributeValue("charset"))); } else if ("test-script".equals(nodeName)) { requestBean.setTestScript(tNode.getValue()); } else { throw new XMLException("Invalid element encountered: <" + nodeName + ">"); } } return requestBean; } public static Document response2XML(final ResponseBean bean) throws XMLException { try { Element respRootElement = new Element("rest-client"); Element respChildElement = new Element("response"); Element respChildSubElement = null; Element respChildSubSubElement = null; // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); respRootElement.addAttribute(versionAttributes); // adding first sub child element - execution-time and append to response child element respChildSubElement = new Element("execution-time"); respChildSubElement.appendChild(String.valueOf(bean.getExecutionTime())); respChildElement.appendChild(respChildSubElement); // adding second sub child element - status and code attributes and append to response child element respChildSubElement = new Element("status"); Attribute codeAttributes = new Attribute("code", String.valueOf(bean.getStatusCode())); respChildSubElement.addAttribute(codeAttributes); respChildSubElement.appendChild(bean.getStatusLine()); respChildElement.appendChild(respChildSubElement); // adding third sub child element - headers Map<String, String> xomHeaders = bean.getHeaders(); if (!xomHeaders.isEmpty()) { Attribute keyAttribute = null; Attribute valueAttribute = null; // creating sub child-child element respChildSubElement = new Element("headers"); for (String key : xomHeaders.keySet()) { String value = xomHeaders.get(key); respChildSubSubElement = new Element("header"); keyAttribute = new Attribute("key", key); valueAttribute = new Attribute("value", value); respChildSubSubElement.addAttribute(keyAttribute); respChildSubSubElement.addAttribute(valueAttribute); respChildSubElement.appendChild(respChildSubSubElement); } // add response child element - headers respChildElement.appendChild(respChildSubElement); } String xomResponseBody = bean.getResponseBody(); if (xomResponseBody != null) { //creating the body child element and append to response child element respChildSubElement = new Element("body"); respChildSubElement.appendChild(xomResponseBody); respChildElement.appendChild(respChildSubElement); } // test result TestResultBean xomTestResult = bean.getTestResult(); if (xomTestResult != null) { //creating the test-result child element respChildSubElement = new Element("test-result"); // Counts: Element e_runCount = new Element("run-coun"); e_runCount.appendChild(String.valueOf(xomTestResult.getRunCount())); Element e_failureCount = new Element("failure-coun"); e_failureCount.appendChild(String.valueOf(xomTestResult.getFailureCount())); Element e_errorCount = new Element("error-coun"); e_errorCount.appendChild(String.valueOf(xomTestResult.getErrorCount())); respChildSubElement.appendChild(e_runCount); respChildSubElement.appendChild(e_failureCount); respChildSubElement.appendChild(e_errorCount); // Failures if (xomTestResult.getFailureCount() > 0) { Element e_failures = new Element("failures"); List<TestFailureResultBean> l = xomTestResult.getFailures(); for (TestFailureResultBean b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_failure = new Element("failure"); e_failure.appendChild(e_message); e_failure.appendChild(e_line); e_failures.appendChild(e_failure); } respChildSubElement.appendChild(e_failures); } //Errors if (xomTestResult.getFailureCount() > 0) { Element e_errors = new Element("errors"); List<TestFailureResultBean> l = xomTestResult.getErrors(); for (TestFailureResultBean b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_error = new Element("error"); e_error.appendChild(e_message); e_error.appendChild(e_line); e_errors.appendChild(e_error); } respChildSubElement.appendChild(e_errors); } // Trace Element e_trace = new Element("trace"); e_trace.appendChild(xomTestResult.toString()); respChildSubElement.appendChild(e_trace); respChildElement.appendChild(respChildSubElement); } respRootElement.appendChild(respChildElement); Document xomDocument = new Document(respRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } public static ResponseBean xml2Response(final Document doc) throws XMLException { ResponseBean responseBean = new ResponseBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version checkIfVersionValid(rootNode.getAttributeValue("version")); // assign rootnode to current node and also finding 'response' node Element tNode = null; Element responseNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <response>"); } // minimum one response element is present in xml if (rootNode.getFirstChildElement("response") == null) { throw new XMLException("The child node of <rest-client> should be <response>"); } responseNode = rootNode.getFirstChildElement("response"); for (int i = 0; i < responseNode.getChildElements().size(); i++) { tNode = responseNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("execution-time".equals(nodeName)) { responseBean.setExecutionTime(Long.parseLong(tNode.getValue())); } else if ("status".equals(nodeName)) { responseBean.setStatusLine(tNode.getValue()); responseBean.setStatusCode(Integer.parseInt(tNode.getAttributeValue("code"))); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { responseBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { responseBean.setResponseBody(tNode.getValue()); } else if ("test-result".equals(nodeName)) { //responseBean.setTestResult(node.getTextContent()); TODO TestResultBean testResultBean = new TestResultBean(); for (int j = 0; j < tNode.getChildCount(); j++) { String nn = tNode.getQualifiedName(); if ("run-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failure-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("error-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failures".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("errors".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } } responseBean.setTestResult(testResultBean); } else { throw new XMLException("Unrecognized element found: <" + nodeName + ">"); } } return responseBean; } public static void writeXML(final Document doc, final File f) throws IOException, XMLException { try { OutputStream out = new FileOutputStream(f); out = new BufferedOutputStream(out); Serializer serializer = new Serializer(out, "UTF-8"); serializer.setIndent(1); serializer.setMaxLength(69); serializer.write(doc); out.close(); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } public static Document xomGetDocumentFromFile(final File f) throws IOException, XMLException { try { Builder parser = new Builder(); Document doc = parser.build(f); return doc; } catch (ParsingException ex) { throw new XMLException(ex.getMessage(), ex); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } public static String getDocumentCharset(final File f) throws IOException, XMLException { Document doc = xomGetDocumentFromFile(f); return doc.toXML(); } public static void writeRequestXML(final RequestBean bean, final File f) throws IOException, XMLException { Document doc = request2XML(bean); writeXML(doc, f); } public static void writeResponseXML(final ResponseBean bean, final File f) throws IOException, XMLException { Document doc = response2XML(bean); writeXML(doc, f); } /*public static void writeXMLRequest(final File f, RequestBean bean) throws IOException, XMLException { Document doc = getDocumentFromFile(f); bean = xml2Request(doc); }*/ /*public static void writeXMLResponse(final File f, ResponseBean bean) throws IOException, XMLException { Document doc = getDocumentFromFile(f); bean = xml2Response(doc); }*/ public static RequestBean getRequestFromXMLFile(final File f) throws IOException, XMLException { Document doc = xomGetDocumentFromFile(f); return xml2Request(doc); } public static ResponseBean getResponseFromXMLFile(final File f) throws IOException, XMLException { Document doc = xomGetDocumentFromFile(f); return xml2Response(doc); } public static String indentXML(final String in) throws XMLException, IOException { try { Builder parser = new Builder(); Document doc = parser.build(in, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Serializer serializer = new Serializer(baos); serializer.setIndent(4); serializer.setMaxLength(69); serializer.write(doc); return new String(baos.toByteArray()); } catch (ParsingException ex) { // LOG.log(Level.SEVERE, null, ex); throw new XMLException("XML indentation failed.", ex); } } }
package com.transloadit.sdk; import org.apache.commons.codec.binary.Hex; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; /** * This class serves as a client interface to the Transloadit API */ public class Transloadit { private String key; private String secret; private String expires; /** * A new instance to transloadit client * * @param key User's transloadit key * @param secret User's transloadit secret */ public Transloadit(String key, String secret, long duration) { this.key = key; this.secret = secret; Instant expiryTime = Instant.now().plusSeconds(duration); DateTimeFormatter formatter = DateTimeFormatter .ofPattern("Y/M/dd HH:mm:ss+00:00") .withZone(ZoneOffset.UTC); expires = formatter.format(expiryTime); } /** * * @return an assemblyApi instance ({@link AssemblyApi} ) tied with the transloadit client. */ public AssemblyApi assemblyApi() { return new AssemblyApi(this); } /** * * @return Map containing authentication key and the time it expires */ Map<String, String> getAuthData() { Map<String, String> authData = new HashMap<>(); authData.put("key", key); authData.put("expires", expires); return authData; } /** * * @param message String data that needs to be encrypted. * @return signature generate based on the message passed and the transloadit secret. */ String getSignature(String message) { byte[] kSecret = secret.getBytes(StandardCharsets.UTF_8); byte[] rawHmac = HmacSHA1(kSecret, message); byte[] hexBytes = new Hex().encode(rawHmac); return new String(hexBytes, StandardCharsets.UTF_8); } private byte[] HmacSHA1(byte[] key, String data) { final String ALGORITHM = "HmacSHA1"; Mac mac = null; try { mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(key, ALGORITHM)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); } }
package org.opencms.gwt.client; import org.opencms.gwt.client.rpc.CmsLog; import org.opencms.gwt.client.ui.CmsNotification; import org.opencms.gwt.client.ui.css.I_CmsImageBundle; import org.opencms.gwt.client.ui.css.I_CmsInputLayoutBundle; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import org.opencms.gwt.client.ui.css.I_CmsToolbarButtonLayoutBundle; import org.opencms.gwt.client.util.CmsClientStringUtil; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; /** * Handles exception handling and more for entry points.<p> * * @author Michael Moossen * * @version $Revision: 1.24 $ * * @since 8.0.0 * * @see org.opencms.gwt.CmsLogService * @see org.opencms.gwt.shared.rpc.I_CmsLogService * @see org.opencms.gwt.shared.rpc.I_CmsLogServiceAsync */ public abstract class A_CmsEntryPoint implements EntryPoint { /** Flag which indicates whether initClasses() has already been called. */ private static boolean initializedClasses; /** * Default constructor.<p> */ protected A_CmsEntryPoint() { // just for subclassing } /** * @see com.google.gwt.core.client.EntryPoint#onModuleLoad() */ public void onModuleLoad() { enableRemoteExceptionHandler(); I_CmsLayoutBundle.INSTANCE.buttonCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.contextmenuCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.dialogCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.notificationCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.dragdropCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.floatDecoratedPanelCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.generalCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.headerCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.highlightCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.iconsCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.listTreeCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.stateCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.toolbarCss().ensureInjected(); I_CmsLayoutBundle.INSTANCE.listItemCss().ensureInjected(); I_CmsInputLayoutBundle.INSTANCE.inputCss().ensureInjected(); I_CmsImageBundle.INSTANCE.style().ensureInjected(); I_CmsInputLayoutBundle.INSTANCE.inputCss().ensureInjected(); I_CmsToolbarButtonLayoutBundle.INSTANCE.style().ensureInjected(); I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().ensureInjected(); initClasses(); } /** * Enables client exception logging on the server.<p> */ protected void enableRemoteExceptionHandler() { if (!GWT.isScript()) { // In hosted mode, uncaught exceptions are easier to debug return; } GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() { /** * @see com.google.gwt.core.client.GWT.UncaughtExceptionHandler#onUncaughtException(java.lang.Throwable) */ public void onUncaughtException(Throwable t) { String message = CmsClientStringUtil.getMessage(t); CmsNotification.get().send(CmsNotification.Type.WARNING, message); CmsLog.log(message + "\n" + CmsClientStringUtil.getStackTrace(t, "\n")); } }); } /** * Helper method for initializing the classes implementing {@link I_CmsHasInit}.<p> * * Calling this method more than once will have no effect.<p> */ private void initClasses() { if (!initializedClasses) { I_CmsClassInitializer initializer = GWT.create(I_CmsClassInitializer.class); initializer.initClasses(); initializedClasses = true; } } }
package annotator.find; import annotator.Main; import java.io.*; import java.util.*; import javax.tools.*; import com.sun.source.tree.*; import com.sun.source.util.*; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.tree.JCTree.*; import javax.lang.model.element.Modifier; import com.google.common.collect.*; import plume.Pair; /** * A {@code TreeScanner} that is able to locate program elements in an * AST based on {@code Criteria}. {@link #getPositions(Tree,List)} * scans a tree and returns a * mapping of source positions (as character offsets) to insertion text. */ public class TreeFinder extends TreeScanner<Void, List<Insertion>> { public static boolean debug = false; private static Integer arrayLocationInParent = null; private static void debug(String message) { if (debug) System.out.println(message); } private static void debug(String message, Object... args) { if (debug) { System.out.printf(message, args); if (! message.endsWith("%n")) { System.out.println(); } } } public static TreePath largestContainingArray(TreePath p) { if (p.getLeaf().getKind() != Tree.Kind.ARRAY_TYPE) { return null; } while (p.getParentPath().getLeaf().getKind() == Tree.Kind.ARRAY_TYPE) { p = p.getParentPath(); } assert p.getLeaf().getKind() == Tree.Kind.ARRAY_TYPE; return p; } /** * Determines the insertion position for type annotations on various * elements. For instance, type annotations for a declaration should be * placed before the type rather than the variable name. */ private static class TypePositionFinder extends TreeScanner<Integer, Void> { private CompilationUnitTree tree; public TypePositionFinder(CompilationUnitTree tree) { super(); this.tree = tree; } /** @param t an expression for a type */ private JCTree leftmostIdentifier(JCTree t) { while (true) { switch (t.getKind()) { case IDENTIFIER: case PRIMITIVE_TYPE: return t; case MEMBER_SELECT: t = ((JCFieldAccess) t).getExpression(); break; case ARRAY_TYPE: t = ((JCArrayTypeTree) t).elemtype; break; case PARAMETERIZED_TYPE: t = ((JCTypeApply) t).getTypeArguments().get(0); break; case EXTENDS_WILDCARD: case SUPER_WILDCARD: t = ((JCWildcard) t).inner; break; case UNBOUNDED_WILDCARD: // This is "?" as in "List<?>". ((JCWildcard) t).inner is null. // There is nowhere to attach the annotation, so for now return // the "?" tree itself. return t; default: throw new RuntimeException(String.format("Unrecognized type (kind=%s, class=%s): %s", t.getKind(), t.getClass(), t)); } } } @Override public Integer visitVariable(VariableTree node, Void p) { JCTree jt = ((JCVariableDecl) node).getType(); // System.out.printf("visitVariable: %s %s%n", jt, jt.getClass()); if (jt instanceof JCTypeApply) { JCTypeApply vt = (JCTypeApply) jt; return vt.clazz.pos; } JCExpression type = (JCExpression) (((JCVariableDecl)node).getType()); return leftmostIdentifier(type).pos; } // When a method is visited, it is visited for the receiver, not the // return value and not the declaration itself. @Override public Integer visitMethod(MethodTree node, Void p) { super.visitMethod(node, p); // System.out.println("node: " + node); // System.out.println("return: " + node.getReturnType()); // location for the receiver annotation int receiverLoc; JCMethodDecl jcnode = (JCMethodDecl) node; List<JCExpression> throwsExpressions = jcnode.thrown; JCBlock body = jcnode.getBody(); List<JCTypeAnnotation> receiverAnnotations = jcnode.receiverAnnotations; if (! throwsExpressions.isEmpty()) { // has a throws expression IdentifierTree it = (IdentifierTree) leftmostIdentifier(throwsExpressions.get(0)); receiverLoc = this.visitIdentifier(it, p); receiverLoc -= 7; // for the 'throws' clause // Search backwards for the close paren. Hope for no problems with // comments. JavaFileObject jfo = tree.getSourceFile(); try { String s = String.valueOf(jfo.getCharContent(true)); for (int i = receiverLoc; i >= 0; i if (s.charAt(i) == ')') { receiverLoc = i + 1; break; } } } catch(IOException e) { throw new RuntimeException(e); } } else if (body != null) { // has a body receiverLoc = body.pos; } else if (! receiverAnnotations.isEmpty()) { // has receiver annotations. After them would be better, but for // now put the new one at the front. receiverLoc = receiverAnnotations.get(0).pos; } else { // try the last parameter, or failing that the return value List<? extends VariableTree> params = jcnode.getParameters(); if (! params.isEmpty()) { VariableTree lastParam = params.get(params.size()-1); receiverLoc = ((JCVariableDecl) lastParam).pos; } else { receiverLoc = jcnode.restype.pos; } // Search forwards for the close paren. Hope for no problems with // comments. JavaFileObject jfo = tree.getSourceFile(); try { String s = String.valueOf(jfo.getCharContent(true)); for (int i = receiverLoc; i < s.length(); i++) { if (s.charAt(i) == ')') { receiverLoc = i + 1; break; } } } catch(IOException e) { throw new RuntimeException(e); } } // TODO: //debugging: System.out.println("result: " + receiverLoc); return receiverLoc; } /** Returns the position of the first bracket at or after the given position. */ // To do: skip over comments private int getFirstBracketAfter(int i) { try { CharSequence s = tree.getSourceFile().getCharContent(true); // return index of first '[' for (int j=i; j < s.length(); j++) { if (s.charAt(j) == '[') { return j; } } } catch(Exception e) { throw new RuntimeException(e); } return -1; } /** Returns the position of the first bracket at or before the given position. */ // To do: skip over comments private int getLastBracketBefore(int i) { try { CharSequence s = tree.getSourceFile().getCharContent(true); // return index of first '[' for (int j=i; j >= 0; j if (s.charAt(j) == '[') { return j; } } } catch(Exception e) { throw new RuntimeException(e); } return -1; } static Map<Pair<CompilationUnitTree,Tree>,TreePath> getPathCache1 = new HashMap<Pair<CompilationUnitTree,Tree>,TreePath>(); /** * An alternative to TreePath.getPath(CompilationUnitTree,Tree) that * caches its results. */ public static TreePath getPath(CompilationUnitTree unit, Tree target) { Pair<CompilationUnitTree,Tree> args = Pair.of(unit, target); if (getPathCache1.containsKey(args)) { return getPathCache1.get(args); } TreePath result = TreePath.getPath(unit, target); getPathCache1.put(args, result); return result; } static Map<Pair<TreePath,Tree>,TreePath> getPathCache2 = new HashMap<Pair<TreePath,Tree>,TreePath>(); /** * An alternative to TreePath.getPath(TreePath,Tree) that * caches its results. */ public static TreePath getPath(TreePath path, Tree target) { Pair<TreePath,Tree> args = Pair.of(path, target); if (getPathCache2.containsKey(args)) { return getPathCache2.get(args); } TreePath result = TreePath.getPath(path, target); getPathCache2.put(args, result); return result; } private Tree parent(Tree node) { return getPath(tree, node).getParentPath().getLeaf(); } @Override public Integer visitIdentifier(IdentifierTree node, Void p) { // for arrays, need to indent inside array, not right before type Tree parent = parent(node); Integer i = null; if (parent instanceof NewArrayTree) { debug("TypePositionFinder.visitIdentifier: recognized array"); JCNewArray na = (JCNewArray) parent; int dimLoc = na.dims.get(0).getPreferredPosition(); i = getLastBracketBefore(dimLoc); } else { i = ((JCIdent) node).pos; } debug("visitIdentifier (parent (" + parent.getClass() + ") = " + parent + ") => " + i); return i; } @Override public Integer visitPrimitiveType(PrimitiveTypeTree node, Void p) { // want exact same logistics as with visitIdentifier Tree parent = parent(node); Integer i = null; if (parent instanceof ArrayTypeTree) { // ArrayTypeTree att = (ArrayTypeTree) parent; JCTree jcid = (JCTree) node; i = jcid.pos; } else { i = ((JCTree) node).pos; } // JCPrimitiveTypeTree pt = (JCPrimitiveTypeTree) node; // JCTree jt = (JCTree) node; return i; } @Override public Integer visitParameterizedType(ParameterizedTypeTree node, Void p) { Tree parent = parent(node); debug("TypePositionFinder.visitParameterizedType %s parent=%s%n", node, parent); Integer i = null; if (parent instanceof ArrayTypeTree) { // want to annotate the first level of this array ArrayTypeTree att = (ArrayTypeTree) parent; Tree baseType = att.getType(); i = leftmostIdentifier(((JCTypeApply) node).getType()).pos; debug("BASE TYPE: " + baseType.toString()); } else { i = leftmostIdentifier(((JCTypeApply)node).getType()).pos; } return i; } // @Override // public Integer visitBlock(BlockTree node, Void p) { // //debugging: System.out.println("visitBlock"); // int rightBeforeBlock = ((JCBlock) node).pos; // // Will be adjusted if a throws statement exists. // int afterParamList = -1; // Tree parent = parent(node); // if (!(methodTree.getKind() == Tree.Kind.METHOD)) { // throw new RuntimeException("BlockTree has non-method parent"); // MethodTree mt = (MethodTree) methodTree; // // TODO: figure out how to better place reciever annotation!!! // // List<? extends VariableTree> vars = mt.getParameters(); // // VariableTree vt = vars.get(0); // // vt.getName().length(); // List<? extends ExpressionTree> throwsExpressions = mt.getThrows(); // if (throwsExpressions.isEmpty()) { // afterParamList = rightBeforeBlock; // } else { // ExpressionTree et = throwsExpressions.get(0); // while (afterParamList == -1) { // switch (et.getKind()) { // case IDENTIFIER: // afterParamList = this.visitIdentifier((IdentifierTree) et, p); // afterParamList -= 7; // for the 'throws' clause // JavaFileObject jfo = tree.getSourceFile(); // try { // String s = String.valueOf(jfo.getCharContent(true)); // for (int i = afterParamList; i >= 0; i--) { // if (s.charAt(i) == ')') { // afterParamList = i + 1; // break; // } catch(IOException e) { // throw new RuntimeException(e); // break; // case MEMBER_SELECT: // et = ((MemberSelectTree) et).getExpression(); // break; // default: // throw new RuntimeException("Unrecognized throws (kind=" + et.getKind() + "): " + et); // // TODO: // //debugging: System.out.println("result: " + afterParamList); // return afterParamList; /** * Returns the number of array levels that are in the given array type tree, * or 0 if the given node is not an array type tree. */ private int arrayLevels(Tree node) { int result = 0; while (node.getKind() == Tree.Kind.ARRAY_TYPE) { result++; node = ((ArrayTypeTree) node).getType(); } return result; } public ArrayTypeTree largestContainingArray(Tree node) { TreePath p = getPath(tree, node); Tree result = TreeFinder.largestContainingArray(p).getLeaf(); assert result.getKind() == Tree.Kind.ARRAY_TYPE; return (ArrayTypeTree) result; } private int arrayStartPos(Tree node) { assert node.getKind() == Tree.Kind.ARRAY_TYPE; while (node.getKind() == Tree.Kind.ARRAY_TYPE) { node = ((ArrayTypeTree) node).getType(); } return ((JCTree) node).getPreferredPosition(); } @Override public Integer visitArrayType(ArrayTypeTree node, Void p) { debug("TypePositionFinder.visitArrayType"); JCArrayTypeTree att = (JCArrayTypeTree) node; debug("TypePositionFinder.visitArrayType(%s) preferred = %s%n", node, att.getPreferredPosition()); int pos = arrayStartPos(node); ArrayTypeTree largest = largestContainingArray(node); assert arrayStartPos(node) == pos; int largestLevels = arrayLevels(largest); int levels = arrayLevels(node); pos = getFirstBracketAfter(pos+1); debug(" levels=%d largestLevels=%d%n", levels, largestLevels); for (int i=levels; i<largestLevels; i++) { pos = getFirstBracketAfter(pos+1); debug(" pos %d at i=%d%n", pos, i); } return pos; } @Override public Integer visitCompilationUnit(CompilationUnitTree node, Void p) { JCCompilationUnit cu = (JCCompilationUnit) node; JCTree.JCExpression pid = cu.pid; while (pid instanceof JCTree.JCFieldAccess) { pid = ((JCTree.JCFieldAccess) pid).selected; } JCTree.JCIdent firstComponent = (JCTree.JCIdent) pid; int result = firstComponent.getPreferredPosition(); // Now back up over the word "package" and the preceding newline JavaFileObject jfo = tree.getSourceFile(); String fileContent; try { fileContent = String.valueOf(jfo.getCharContent(true)); } catch(IOException e) { throw new RuntimeException(e); } while (java.lang.Character.isWhitespace(fileContent.charAt(result-1))) { result } result -= 7; String packageString = fileContent.substring(result, result+7); assert "package".equals(packageString) : "expected 'package', got: " + packageString; assert result == 0 || java.lang.Character.isWhitespace(fileContent.charAt(result-1)); return result; } @Override public Integer visitClass(ClassTree node, Void p) { JCClassDecl cd = (JCClassDecl) node; if (cd.mods != null) { return cd.mods.getPreferredPosition(); } else { return cd.getPreferredPosition(); } } @Override public Integer visitNewArray(NewArrayTree node, Void p) { JCNewArray na = (JCNewArray) node; // We need to know what array dimension to return. This is gross. int dim = ((arrayLocationInParent == null) ? 0 : arrayLocationInParent.intValue() + 1); // System.out.printf("visitNewArray: dim=%d (arrayLocationInParent=%s)%n", dim, arrayLocationInParent); if (dim == na.dims.size()) { return na.elemtype.getPreferredPosition(); } int argPos = na.dims.get(dim).getPreferredPosition(); return getLastBracketBefore(argPos); } } /** * Determine the insertion position for declaration annotations on * various elements. For instance, method declaration annotations should * be placed before all the other modifiers and annotations. */ private static class DeclarationPositionFinder extends TreeScanner<Integer, Void> { private CompilationUnitTree tree; public DeclarationPositionFinder(CompilationUnitTree tree) { super(); this.tree = tree; } // When a method is visited, it is visited for the declaration itself. @Override public Integer visitMethod(MethodTree node, Void p) { super.visitMethod(node, p); // System.out.printf("DeclarationPositionFinder.visitMethod()%n"); ModifiersTree mt = node.getModifiers(); // actually List<JCAnnotation>. List<? extends AnnotationTree> annos = mt.getAnnotations(); // Set<Modifier> flags = mt.getFlags(); JCTree before; if (annos.size() > 1) { before = (JCAnnotation) annos.get(0); } else if (node.getReturnType() != null) { before = (JCTree) node.getReturnType(); } else { // if we're a constructor, we have null return type, so we use the constructor's position // rather than the return type's position before = (JCTree) node; } int declPos = TreeInfo.getStartPos(before); // There is no source code location information for Modifiers, so // cannot iterate through the modifiers. But we don't have to. int modsPos = ((JCModifiers)mt).pos().getStartPosition(); if (modsPos != -1) { declPos = Math.min(declPos, modsPos); } return declPos; } @Override public Integer visitCompilationUnit(CompilationUnitTree node, Void p) { JCCompilationUnit cu = (JCCompilationUnit) node; JCTree.JCExpression pid = cu.pid; while (pid instanceof JCTree.JCFieldAccess) { pid = ((JCTree.JCFieldAccess) pid).selected; } JCTree.JCIdent firstComponent = (JCTree.JCIdent) pid; int result = firstComponent.getPreferredPosition(); // Now back up over the word "package" and the preceding newline JavaFileObject jfo = tree.getSourceFile(); String fileContent; try { fileContent = String.valueOf(jfo.getCharContent(true)); } catch(IOException e) { throw new RuntimeException(e); } while (java.lang.Character.isWhitespace(fileContent.charAt(result-1))) { result } result -= 7; String packageString = fileContent.substring(result, result+7); assert "package".equals(packageString) : "expected 'package', got: " + packageString; assert result == 0 || java.lang.Character.isWhitespace(fileContent.charAt(result-1)); return result; } @Override public Integer visitClass(ClassTree node, Void p) { JCClassDecl cd = (JCClassDecl) node; int result; if (cd.mods != null && (cd.mods.flags != 0 || cd.mods.annotations.size() > 0)) { result = cd.mods.getPreferredPosition(); assert result >= 0 : String.format("%d %d %d%n", cd.getStartPosition(), cd.getPreferredPosition(), cd.pos); } else { result = cd.getPreferredPosition(); assert result >= 0 : String.format("%d %d %d%n", cd.getStartPosition(), cd.getPreferredPosition(), cd.pos); } return result; } } /** * A comparator for sorting integers in reverse */ public static class ReverseIntegerComparator implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { return o1.compareTo(o2) * -1; } } private Map<Tree, TreePath> paths; private TypePositionFinder tpf; private DeclarationPositionFinder dpf; private CompilationUnitTree tree; private SetMultimap<Integer, Insertion> positions; /** * Creates a {@code TreeFinder} from a source tree. * * @param tree the source tree to search */ public TreeFinder(CompilationUnitTree tree) { this.tree = tree; this.positions = LinkedHashMultimap.create(); this.tpf = new TypePositionFinder(tree); this.dpf = new DeclarationPositionFinder(tree); this.paths = new HashMap<Tree, TreePath>(); } boolean handled(Tree node) { return (node instanceof CompilationUnitTree || node instanceof ClassTree || node instanceof MethodTree || node instanceof VariableTree || node instanceof IdentifierTree || node instanceof NewArrayTree || node instanceof ParameterizedTypeTree || node instanceof BlockTree || node instanceof ArrayTypeTree || node instanceof PrimitiveTypeTree); } /** * Scans this tree, using the list of insertions to generate the source * position to insertion text mapping. */ @Override public Void scan(Tree node, List<Insertion> p) { if (node == null) { return null; } if (! handled(node)) { // System.out.printf("Not handled, skipping (%s): %s%n", node.getClass(), node); // nothing to do return super.scan(node, p); } TreePath path; if (paths.containsKey(tree)) path = paths.get(tree); else path = TreePath.getPath(tree, node); assert path == null || path.getLeaf() == node : String.format("Mismatch: '%s' '%s' '%s' '%s'%n", path, tree, paths.containsKey(tree), node); // To avoid annotating existing annotations right before // the element you wish to annotate, skip anything inside of // an annotation. if (path != null) { for (Tree t : path) { if (t.getKind() == Tree.Kind.ANNOTATION) { return super.scan(node, p); } } } for (Iterator<Insertion> it = p.iterator(); it.hasNext(); ) { Insertion i = it.next(); if (debug) { debug("Considering insertion at tree:"); debug(" " + i); debug(" " + Main.firstLine(node.toString())); debug(" " + node.getClass()); } if (!i.getCriteria().isSatisfiedBy(path, node)) { debug(" ... not satisfied"); continue; } else { debug(" ... satisfied!"); debug(" " + Main.firstLine(node.toString())); debug(" " + node.getClass()); } // Don't insert a duplicate if this particular annotation is already // present at this location. List<? extends AnnotationTree> alreadyPresent = null; if (path != null) { for (Tree n : path) { if (n instanceof ClassTree) { alreadyPresent = ((ClassTree) n).getModifiers().getAnnotations(); break; } else if (n instanceof MethodTree) { alreadyPresent = ((MethodTree) n).getModifiers().getAnnotations(); break; } else if (n instanceof VariableTree) { alreadyPresent = ((VariableTree) n).getModifiers().getAnnotations(); break; } else if (n instanceof TypeCastTree) { Tree type = ((TypeCastTree) n).getType(); if (type instanceof AnnotatedTypeTree) { alreadyPresent = ((AnnotatedTypeTree) type).getAnnotations(); } break; } else if (n instanceof InstanceOfTree) { Tree type = ((InstanceOfTree) n).getType(); if (type instanceof AnnotatedTypeTree) { alreadyPresent = ((AnnotatedTypeTree) type).getAnnotations(); } break; } else if (n instanceof NewClassTree) { JCNewClass nc = (JCNewClass) n; if (nc.clazz instanceof AnnotatedTypeTree) { alreadyPresent = ((AnnotatedTypeTree) nc.clazz).getAnnotations(); } break; } } } // System.out.printf("alreadyPresent = %s for %s%n", alreadyPresent, node.getKind()); // printPath(path); if (alreadyPresent != null) { for (AnnotationTree at : alreadyPresent) { // Compare the to-be-inserted annotation to the existing // annotation, ignoring its arguments (duplicate annotations are // never allowed even if they differ in arguments). If we did // have to compare our arguments, we'd have to deal with enum // arguments potentially being fully qualified or not: // @Retention(java.lang.annotation.RetentionPolicy.CLASS) vs // @Retention(RetentionPolicy.CLASS) String ann = at.getAnnotationType().toString(); String iann = Main.removeArgs(i.getText()).a.substring(1); // strip off the leading @ String iannNoPackage = Main.removePackage(iann).b; // System.out.printf("Comparing: %s %s %s%n", ann, iann, iannNoPackage); if (ann.equals(iann) || ann.equals(iannNoPackage)) { if (debug) { System.out.printf("Already present, not reinserting: %s%n", ann); } it.remove(); return super.scan(node, p); } } } // If this is a method, then it might have been selected because of // the receiver, or because of the return value. Distinguish those. // One way would be to set a global variable here. Another would be // to look for a particular different node. I will do the latter. Integer pos; debug("node: %s%ncritera: %s%n", node, i.getCriteria()); if ((node instanceof MethodTree) && (i.getCriteria().isOnReturnType())) { // looking for the return type pos = tpf.scan(((MethodTree)node).getReturnType(), null); assert handled(node); debug("pos = %d at return type node: %s%n", pos, ((JCMethodDecl)node).getReturnType().getClass()); } else { boolean typeScan = true; if (node instanceof MethodTree) { // looking for the receiver or the declaration typeScan = i.getCriteria().isOnReceiver(); } else if (node instanceof ClassTree) { typeScan = ! i.getSeparateLine(); // hacky check } if (typeScan) { // looking for the type { // handle finding a particular array level. Yuck! GenericArrayLocationCriterion galc = i.getCriteria().getGenericArrayLocation(); if (galc != null) { arrayLocationInParent = galc.locationInParent; // System.out.printf("Set arrayLocationInParent to %s%n", arrayLocationInParent); } else { arrayLocationInParent = null; // System.out.printf("No arrayLocationInParent%n"); } } // System.out.printf("Calling tpf.scan(%s: %s)%n", node.getClass(), node); pos = tpf.scan(node, null); assert handled(node); debug("pos = %d at type: %s (%s)%n", pos, node.toString(), node.getClass()); } else { // looking for the declaration pos = dpf.scan(node, null); assert pos != null; debug("pos = %d at declaration: %s%n", pos, node.getClass()); } } debug(" ... satisfied! at %d for node of type %s: %s", pos, node.getClass(), Main.treeToString(node)); if (pos != null) { assert pos >= 0 : String.format("pos: %s%nnode: %s%ninsertion: %s%n", pos, node, i); positions.put(pos, i); } it.remove(); } return super.scan(node, p); } /** * Scans the given tree with the given insertion list and returns the * mapping from source position to insertion text. The positions are sorted * in decreasing order of index, so that inserting one doesn't throw * off the index for a subsequent one. * * <p> * <i>N.B.:</i> This method calls {@code scan()} internally. * </p> * * @param node the tree to scan * @param p the list of insertion criteria * @return the source position to insertion text mapping */ public SetMultimap<Integer, Insertion> getPositions(Tree node, List<Insertion> p) { List<Insertion> uninserted = new LinkedList<Insertion>(p); this.scan(node, uninserted); // This needs to be optional, because there may be many extra // annotations in a .jaif file. if (debug) { // Output every insertion that was not given a position: for (Insertion i : uninserted) { System.err.println("Unable to insert: " + i); } } if (debug) { System.out.printf("getPositions => %d positions%n", positions.size()); } return Multimaps.unmodifiableSetMultimap(positions); } private static void printPath(TreePath path) { System.out.printf(" if (path != null) { for (Tree t : path) { System.out.printf("%s %s%n", t.getKind(), t); } } System.out.printf(" } }
package org.owasp.dependencycheck; import org.junit.Before; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestName; import org.owasp.dependencycheck.analyzer.AnalysisPhase; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.utils.Settings; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Assume; import org.owasp.dependencycheck.dependency.EvidenceType; import org.owasp.dependencycheck.utils.FileUtils; /** * @author Mark Rekveld */ public class EngineModeIT extends BaseTest { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Rule public TestName testName = new TestName(); private String originalDataDir = null; @Before @Override public void setUp() throws Exception { super.setUp(); // Have to use System properties as the Settings object pulls from the // system properties before configured properties originalDataDir = getSettings().getString(Settings.KEYS.DATA_DIRECTORY); System.setProperty(Settings.KEYS.DATA_DIRECTORY, tempDir.newFolder().getAbsolutePath()); } @After @Override public void tearDown() throws Exception { try { //delete temp files FileUtils.delete(getSettings().getDataDirectory()); //Reset system property to original value just to be safe for other tests. System.setProperty(Settings.KEYS.DATA_DIRECTORY, originalDataDir); System.clearProperty(Settings.KEYS.H2_DATA_DIRECTORY); } catch (IOException ex) { throw new RuntimeException(ex); } finally { super.tearDown(); } } @Test public void testEvidenceCollectionAndEvidenceProcessingModes() throws Exception { Dependency[] dependencies; try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION, getSettings())) { engine.openDatabase(); //does nothing in the current mode assertDatabase(false); for (AnalysisPhase phase : Engine.Mode.EVIDENCE_COLLECTION.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); } for (AnalysisPhase phase : Engine.Mode.EVIDENCE_PROCESSING.getPhases()) { assertThat(engine.getAnalyzers(phase), is(nullValue())); } File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar"); engine.scan(file); engine.analyzeDependencies(); dependencies = engine.getDependencies(); assertThat(dependencies.length, is(1)); Dependency dependency = dependencies[0]; assertTrue(dependency.getEvidence(EvidenceType.VENDOR).toString().toLowerCase().contains("apache")); assertTrue(dependency.getVendorWeightings().contains("apache")); assertTrue(dependency.getVulnerabilities().isEmpty()); } try (Engine engine = new Engine(Engine.Mode.EVIDENCE_PROCESSING, getSettings())) { engine.openDatabase(); assertDatabase(true); for (AnalysisPhase phase : Engine.Mode.EVIDENCE_PROCESSING.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); } for (AnalysisPhase phase : Engine.Mode.EVIDENCE_COLLECTION.getPhases()) { assertThat(engine.getAnalyzers(phase), is(nullValue())); } engine.addDependency(dependencies[0]); engine.analyzeDependencies(); Dependency dependency = dependencies[0]; assertFalse(dependency.getVulnerabilities().isEmpty()); } } @Test public void testStandaloneMode() throws Exception { try (Engine engine = new Engine(Engine.Mode.STANDALONE, getSettings())) { engine.openDatabase(); assertDatabase(true); for (AnalysisPhase phase : Engine.Mode.STANDALONE.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); } File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar"); engine.scan(file); engine.analyzeDependencies(); Dependency[] dependencies = engine.getDependencies(); assertThat(dependencies.length, is(1)); Dependency dependency = dependencies[0]; assertTrue(dependency.getEvidence(EvidenceType.VENDOR).toString().toLowerCase().contains("apache")); assertTrue(dependency.getVendorWeightings().contains("apache")); assertFalse(dependency.getVulnerabilities().isEmpty()); } } private void assertDatabase(boolean exists) throws Exception { Assume.assumeThat(getSettings().getString(Settings.KEYS.DB_DRIVER_NAME), is("org.h2.Driver")); Path directory = getSettings().getDataDirectory().toPath(); assertThat(Files.exists(directory), is(true)); assertThat(Files.isDirectory(directory), is(true)); Path database = directory.resolve(getSettings().getString(Settings.KEYS.DB_FILE_NAME)); assertThat(Files.exists(database), is(exists)); } }
package permafrost.tundra.lang; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataUtil; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.data.transform.Transformer; import permafrost.tundra.data.transform.string.Uncontroller; import permafrost.tundra.io.InputOutputHelper; import permafrost.tundra.io.InputStreamHelper; import permafrost.tundra.io.ReaderHelper; import permafrost.tundra.math.BigDecimalHelper; import permafrost.tundra.math.BigIntegerHelper; import permafrost.tundra.math.NumberHelper; import permafrost.tundra.time.DateTimeHelper; import permafrost.tundra.util.regex.PatternHelper; import permafrost.tundra.util.regex.ReplacementHelper; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A collection of convenience methods for working with String objects. */ public final class StringHelper { /** * The pattern used to find runs of one or more whitespace characters in a string. */ private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); /** * Disallow instantiation of this class. */ private StringHelper() {} /** * Normalizes the given byte[] as a string. * * @param bytes A byte[] to be converted to a string. * @return A string representation of the given byte[]. */ public static String normalize(byte[] bytes) { return normalize(bytes, null); } /** * Converts the given byte[] as a string. * * @param bytes A byte[] to be converted to a string. * @param charset The character set to use. * @return A string representation of the given byte[]. */ public static String normalize(byte[] bytes, Charset charset) { if (bytes == null) return null; return new String(bytes, CharsetHelper.normalize(charset)); } /** * Converts the given java.io.InputStream as a String, and closes the stream. * * @param inputStream A java.io.InputStream to be converted to a string. * @return A string representation of the given java.io.InputStream. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(InputStream inputStream) throws IOException { return normalize(inputStream, CharsetHelper.DEFAULT_CHARSET); } /** * Converts the given java.io.InputStream as a String, and closes the stream. * * @param inputStream A java.io.InputStream to be converted to a string. * @param charset The character set to use. * @return A string representation of the given java.io.InputStream. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String normalize(InputStream inputStream, Charset charset) throws IOException { if (inputStream == null) return null; Writer writer = new StringWriter(); InputOutputHelper.copy(new InputStreamReader(InputStreamHelper.normalize(inputStream), CharsetHelper.normalize(charset)), writer); return writer.toString(); } /** * Normalizes the given String, byte[], or java.io.InputStream object to a String. * * @param object The object to be normalized to a string. * @return A string representation of the given object. * @throws IOException If the given encoding is unsupported, or if there is an error reading from the * java.io.InputStream. */ public static String normalize(Object object) throws IOException { return normalize(object, null); } /** * Normalizes the given String, byte[], or java.io.InputStream object to a String. * * @param object The object to be normalized to a string. * @param charset The character set to use. * @return A string representation of the given object. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String normalize(Object object, Charset charset) throws IOException { String value = null; if (object instanceof String) { value = (String)object; } else if (object instanceof Boolean) { value = BooleanHelper.emit((Boolean)object); } else if (object instanceof BigDecimal) { value = BigDecimalHelper.emit((BigDecimal)object); } else if (object instanceof Number) { value = NumberHelper.emit((Number) object); } else if (object instanceof Date) { value = DateTimeHelper.emit((Date) object); } else if (object instanceof Calendar) { value = DateTimeHelper.emit((Calendar)object); } else if (object instanceof InputStream) { value = normalize((InputStream)object, charset); } else if (object instanceof byte[]) { value = normalize((byte[])object, charset); } else if (object instanceof Reader) { value = ReaderHelper.read((Reader)object); } else if (object instanceof Class) { value = ((Class)object).getName(); } else if (object instanceof Charset) { value = ((Charset)object).displayName(); } else if (object != null) { value = object.toString(); } return value; } /** * Normalizes the list of String, byte[], or InputStream to a String list. * * @param array The array of objects to be normalized. * @param charset The character set to use. * @return The resulting String list representing the given array. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String[] normalize(Object[] array, Charset charset) throws IOException { if (array == null) return null; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = normalize(array[i], charset); } return output; } /** * Normalizes the list of String, byte[], or InputStream to a String list. * * @param array The array of objects to be normalized. * @param charsetName The character set to use. * @return The resulting String list representing the given array. * @throws IOException If there is an error reading from the java.io.InputStream. */ public static String[] normalize(Object[] array, String charsetName) throws IOException { return normalize(array, CharsetHelper.normalize(charsetName)); } /** * Returns the given string in lower case. * * @param input The string to be converted. * @return The given string in lower case. */ public static String lowercase(String input) { return lowercase(input, null); } /** * Returns the given string in lower case. * * @param input The string to be converted. * @param locale The locale to be used. * @return The given string in lower case. */ public static String lowercase(String input, Locale locale) { if (input == null) return null; return input.toLowerCase(LocaleHelper.normalize(locale)); } /** * Returns the given string list in lower case. * * @param array The string list to be converted. * @return The given string list in lower case. */ public static String[] lowercase(String[] array) { return lowercase(array, null); } /** * Returns the given string list in lower case. * * @param array The string list to be converted. * @param locale The locale to be used. * @return The given string list in lower case. */ public static String[] lowercase(String[] array, Locale locale) { if (array == null) return null; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = lowercase(array[i], locale); } return output; } /** * Returns the given string table in lower case. * * @param table The string table to be converted. * @return The given string list in lower case. */ public static String[][] lowercase(String[][] table) { return lowercase(table, null); } /** * Returns the given string table in lower case. * * @param table The string table to be converted. * @param locale The locale to be used. * @return The given string list in lower case. */ public static String[][] lowercase(String[][] table, Locale locale) { if (table == null) return null; String[][] output = new String[table.length][]; for (int i = 0; i < table.length; i++) { output[i] = lowercase(table[i], locale); } return output; } /** * Returns the given string in upper case. * * @param input The string to be converted. * @return The given string in upper case. */ public static String uppercase(String input) { return uppercase(input, null); } /** * Returns the given string in upper case. * * @param input The string to be converted. * @param locale The locale to be used. * @return The given string in upper case. */ public static String uppercase(String input, Locale locale) { if (input == null) return null; return input.toUpperCase(LocaleHelper.normalize(locale)); } /** * Returns the given string list in upper case. * * @param array The string list to be converted. * @return The given string list in upper case. */ public static String[] uppercase(String[] array) { return uppercase(array, null); } /** * Returns the given string list in upper case. * * @param array The string list to be converted. * @param locale The locale to be used. * @return The given string list in upper case. */ public static String[] uppercase(String[] array, Locale locale) { if (array == null) return null; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = uppercase(array[i], locale); } return output; } /** * Returns the given string table in upper case. * * @param table The string table to be converted. * @return The given string list in upper case. */ public static String[][] uppercase(String[][] table) { return uppercase(table, null); } /** * Returns the given string table in upper case. * * @param table The string table to be converted. * @param locale The locale to be used. * @return The given string list in upper case. */ public static String[][] uppercase(String[][] table, Locale locale) { if (table == null) return null; String[][] output = new String[table.length][]; for (int i = 0; i < table.length; i++) { output[i] = uppercase(table[i], locale); } return output; } /** * Returns a substring starting at the given index for the given length. * * @param input The string to be sliced. * @param index The zero-based starting index of the slice. * @param length The length in characters of the slice. * @return The resulting substring. */ public static String slice(String input, int index, int length) { if (input == null || input.equals("")) return input; int inputLength = input.length(), endIndex = 0; // support reverse length if (length < 0) { // support reverse indexing if (index < 0) { endIndex = index + inputLength + 1; } else { if (index >= inputLength) index = inputLength - 1; endIndex = index + 1; } index = endIndex + length; } else { // support reverse indexing if (index < 0) index += inputLength; endIndex = index + length; } String output; if (index < inputLength && endIndex > 0) { if (index < 0) index = 0; if (endIndex > inputLength) endIndex = inputLength; output = input.substring(index, endIndex); } else { output = ""; } return output; } /** * Truncates the given string to the given length. If the string length is less than or equal to the desired * length it is returned unmodified, otherwise it is truncated to the desired length. * * @param input The string to be truncated. * @param length The length to truncate the string to. * @return The truncated string. */ public static String truncate(String input, int length) { return truncate(input, length, false); } /** * Truncates the given string to the given length. If the string length is less than or equal to the desired * length it is returned unmodified, otherwise it is truncated to the desired length. * * @param input The string to be truncated. * @param length The length to truncate the string to. * @param ellipsis If true, the returned string is suffixed with an ellipsis character when truncated. * @return The truncated string. */ public static String truncate(String input, int length, boolean ellipsis) { if (input == null || input.equals("")) return input; if (input.length() > Math.abs(length)) { if (ellipsis && length != 0) { if (length > 0) { input = slice(input, 0, length - 1) + "…"; } else { input = "…" + slice(input, -1, length + 1); } } else if (length < 0) { input = slice(input, -1, length); } else { input = slice(input, 0, length); } } return input; } /** * Truncates the given strings to the given length. If a string's length is less than or equal to the desired * length it is returned unmodified, otherwise it is truncated to the desired length. * * @param input The strings to be truncated. * @param length The length to truncate the strings to. * @param ellipsis If true, the returned strings are suffixed with an ellipsis character when truncated. * @return The truncated strings. */ public static String[] truncate(String[] input, int length, boolean ellipsis) { if (input == null) return null; String output[] = new String[input.length]; for(int i = 0; i < input.length; i++) { output[i] = truncate(input[i], length, ellipsis); } return output; } /** * Truncates the given strings to the given length. If a string's length is less than or equal to the desired * length it is returned unmodified, otherwise it is truncated to the desired length. * * @param input The strings to be truncated. * @param length The length to truncate the strings to. * @param ellipsis If true, the returned strings are suffixed with an ellipsis character when truncated. * @return The truncated strings. */ public static String[][] truncate(String[][] input, int length, boolean ellipsis) { if (input == null) return null; String output[][] = new String[input.length][]; for(int i = 0; i < input.length; i++) { output[i] = truncate(input[i], length, ellipsis); } return output; } /** * Converts a null input string to an empty string, or returns the string unmodified if not null. * * @param input The string to be converted to an empty string if null. * @return If input is null then empty string, otherwise input string unmodified. */ public static String blankify(String input) { return blankify(input, true); } /** * Converts a null input string to an empty string, or returns the string unmodified if not null. * * @param input The string to be converted to an empty string if null. * @param blankify If true, nulls will be converted to empty strings, else no conversion will occur. * @return If blankify is true and input is null then empty string, otherwise input string unmodified. */ public static String blankify(String input, boolean blankify) { if (!blankify) return input; return input == null ? "" : input; } /** * Converts any null strings to empty strings, or returns the strings unmodified if not null. * * @param input The list of strings to be converted to an empty strings if null. * @return The list of strings converted to empty strings if they were null. */ public static String[] blankify(String[] input) { return blankify(input, true); } /** * Converts any null strings to empty strings, or returns the strings unmodified if not null. * * @param input The list of strings to be converted to an empty strings if null. * @param blankify If true, nulls will be converted to empty strings, else no conversion will occur. * @return The list of strings converted to empty strings if they were null. */ public static String[] blankify(String input[], boolean blankify) { if (!blankify || input == null) return input; String output[] = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = blankify(input[i], blankify); } return output; } /** * Capitalizes the first character in either the first word or all words in the given string. * * @param string The string to capitalize. * @param firstWordOnly Whether only the first word should be capitalized, or all words. * @return The capitalized string. */ public static String capitalize(String string, boolean firstWordOnly) { if (string == null) return null; char[] characters = string.toCharArray(); boolean capitalize = true; for (int i = 0; i < characters.length; i++) { char character = characters[i]; if (Character.isWhitespace(character)) { capitalize = true; } else if (capitalize) { characters[i] = Character.toTitleCase(character); capitalize = false; if (firstWordOnly) break; } } return new String(characters); } /** * Capitalizes the first character in either the first word or all words in each of the given * strings. * * @param input The strings to capitalize. * @param firstWordOnly Whether only the first word should be capitalized, or all words. * @return The capitalized strings. */ public static String[] capitalize(String[] input, boolean firstWordOnly) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = capitalize(input[i], firstWordOnly); } return output; } /** * Returns the given string as a list of characters. * * @param string The string. * @return The characters in the given string. */ public static Character[] characters(String string) { if (string == null) return null; char[] chars = string.toCharArray(); Character[] characters = new Character[chars.length]; for (int i = 0; i < chars.length; i++) { characters[i] = chars[i]; } return characters; } /** * Concatenates all non-null string leaf values in the given IData document. * * @param operands An IData document containing strings to be concatenated. * @return All string leaf values in the IData document concatenated together. */ public static String concatenate(IData operands) { return concatenate(operands, null); } /** * Concatenates all non-null string leaf values in the given IData document, separated by the given separator * string. * * @param operands An IData document containing strings to be concatenated. * @param separator An optional separator string to be used between items of the array. * @return All string leaf values in the IData document concatenated together. */ public static String concatenate(IData operands, String separator) { return concatenate(operands, separator, Sanitization.REMOVE_NULLS); } /** * Concatenates all string leaf values in the given IData document, separated by the given separator string. * * @param operands An IData document containing strings to be concatenated. * @param separator An optional separator string to be used between items of the array. * @param sanitization How nulls and blank values should be treated. * @return All string leaf values in the IData document concatenated together. */ @SuppressWarnings("unchecked") public static String concatenate(IData operands, String separator, Sanitization sanitization) { return concatenate(separator, false, IDataHelper.getLeaves(IDataHelper.sanitize(operands, sanitization), String.class)); } /** * Concatenates all given non-null strings. * * @param strings A list of strings to be concatenated. * @return All given strings concatenated together. */ public static String concatenate(String ...strings) { return concatenate(null, false, strings); } /** * Concatenates all given strings, separated by the given separator string. * * @param separator An optional separator string to be used between items of the array. * @param strings A list of strings to be concatenated. * @return All given strings concatenated together. */ public static String concatenate(String separator, String ...strings) { return concatenate(separator, false, strings); } /** * Concatenates all given strings, separated by the given separator string. * * @param separator An optional separator string to be used between items of the array. * @param includeNulls If true, null values will be included in the output string, otherwise they are ignored. * @param strings A list of strings to be concatenated. * @return All given strings concatenated together. */ public static String concatenate(String separator, boolean includeNulls, String ...strings) { if (strings == null || strings.length == 0) return includeNulls ? "" : null; if (includeNulls || containsValues(strings)) { return build(null, separator, includeNulls, strings).toString(); } else { return null; } } /** * Returns true if any of the given strings is not null. * * @param strings The list of strings to check. * @return True if any of the given strings are not null. */ public static boolean containsValues(String ...strings) { boolean containsValues = false; if (strings != null) { for (String string : strings) { if (string != null) { containsValues = true; break; } } } return containsValues; } /** * Appends the strings in the given IData to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param operands An IData object containing strings. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, IData operands) { return build(builder, operands, null); } /** * Appends the strings in the given IData to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param operands An IData object containing strings. * @param separator Optional separator to be used between each string. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, IData operands, String separator) { return build(builder, operands, separator, false); } /** * Appends the strings in the given IData to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param operands An IData object containing strings. * @param separator Optional separator to be used between each string. * @param includeNulls Whether nulls should be appended. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, IData operands, String separator, boolean includeNulls) { return build(builder, separator, includeNulls, IDataHelper.getLeaves(operands, String.class)); } /** * Appends the given strings to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param strings The strings to be appended. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, String ...strings) { return build(builder, null, strings); } /** * Appends the given strings to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param separator Optional separator to be used between each string. * @param strings The strings to be appended. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, String separator, String ...strings) { return build(builder, separator, false, strings); } /** * Appends the given strings to the given StringBuilder. * * @param builder The StringBuilder to append to. If null, a new StringBuilder is created. * @param separator Optional separator to be used between each string. * @param includeNulls Whether nulls should be appended. * @param strings The strings to be appended. * @return The StringBuilder appended to. */ public static StringBuilder build(StringBuilder builder, String separator, boolean includeNulls, String ...strings) { if (builder == null) builder = new StringBuilder(); if (strings != null && strings.length > 0) { boolean separatorRequired = false; for (String string : strings) { boolean includeItem = includeNulls || string != null; if (separator != null && separatorRequired && includeItem) builder.append(separator); if (includeItem) { builder.append(string); separatorRequired = true; } } } return builder; } /** * Returns the given string with leading and trailing whitespace removed. * * @param string The string to be trimmed. * @return The trimmed string. */ public static String trim(String string) { String output = null; if (string != null) output = string.trim(); return output; } /** * Trims each item in the given String[] of leading and trailing whitespace. * * @param input The String[] to be trimmed. * @return A new String[] contained the trimmed versions of the items in the given input. */ public static String[] trim(String[] input) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { String item = input[i]; if (item != null) output[i] = input[i].trim(); } return output; } /** * Trims each item in the given String[][] of leading and trailing whitespace. * * @param input The String[][] to be trimmed. * @return A new String[][] contained the trimmed versions of the items in the given input. */ public static String[][] trim(String[][] input) { if (input == null) return null; String[][] output = new String[input.length][]; for (int i = 0; i < input.length; i++) { output[i] = trim(input[i]); } return output; } /** * Returns the length or number of characters of the string. * * @param string The string to be measured. * @return The length of the given string. */ public static int length(String string) { return string == null ? 0 : string.length(); } /** * Returns all the groups captured by the given regular expression pattern in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return The capture groups from the regular expression pattern match against the string. */ public static IData[] capture(String string, String pattern) { return capture(string, pattern, false); } /** * Returns all the groups captured by the given regular expression pattern in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return The capture groups from the regular expression pattern match against the string. */ public static IData[] capture(String string, String pattern, boolean literal) { return capture(string, PatternHelper.compile(pattern, literal)); } /** * Returns all the groups captured by the given regular expression pattern in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return The capture groups from the regular expression pattern match against the string. */ public static IData[] capture(String string, Pattern pattern) { if (string == null || pattern == null) return null; List<IData> captures = new ArrayList<IData>(); Matcher matcher = pattern.matcher(string); while (matcher.find()) { int count = matcher.groupCount(); List<IData> groups = new ArrayList<IData>(count); for (int i = 0; i <= count; i++) { int index = matcher.start(i); int length = matcher.end(i) - index; String content = matcher.group(i); boolean captured = index >= 0; IData group = IDataFactory.create(); IDataCursor groupCursor = group.getCursor(); IDataUtil.put(groupCursor, "captured?", "" + captured); if (captured) { IDataUtil.put(groupCursor, "index", "" + index); IDataUtil.put(groupCursor, "length", "" + length); IDataUtil.put(groupCursor, "content", content); } groupCursor.destroy(); groups.add(group); } IData capture = IDataFactory.create(); IDataCursor captureCursor = capture.getCursor(); IDataUtil.put(captureCursor, "groups", groups.toArray(new IData[0])); IDataUtil.put(captureCursor, "groups.length", "" + groups.size()); captureCursor.destroy(); captures.add(capture); } return captures.toArray(new IData[0]); } /** * Returns true if the given regular expression pattern is found anywhere in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the regular expression pattern was found anywhere in the given string. */ public static boolean find(String string, String pattern) { return find(string, pattern, false); } * /** Returns true if the given pattern is found anywhere in the given string. * * @param string The string to match against the regular expression. * @param pattern The literal of regular expression pattern. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return True if the pattern was found anywhere in the given string. */ public static boolean find(String string, String pattern, boolean literal) { return find(string, PatternHelper.compile(pattern, literal)); } * /** Returns true if the given pattern is found anywhere in the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the pattern was found anywhere in the given string. */ public static boolean find(String string, Pattern pattern) { return string != null && pattern != null && pattern.matcher(string).find(); } /** * Returns true if the given regular expression pattern matches the entirety of the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the regular expression matches the entirety of the given string. */ public static boolean match(String string, String pattern) { return match(string, pattern, false); } /** * Returns true if the pattern matches the entirety of the given string. * * @param string The string to match against the regular expression. * @param pattern The literal or regular expression pattern. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return True if the pattern matches the entirety of the given string. */ public static boolean match(String string, String pattern, boolean literal) { return match(string, PatternHelper.compile(pattern, literal)); } /** * Returns true if the pattern matches the entirety of the given string. * * @param string The string to match against the regular expression. * @param pattern The regular expression pattern. * @return True if the pattern matches the entirety of the given string. */ public static boolean match(String string, Pattern pattern) { return string != null && pattern != null && pattern.matcher(string).matches(); } /** * Removes all occurrences of the given regular expression in the given string. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @return The given string with all occurrences of the given pattern removed. */ public static String remove(String string, String pattern) { return remove(string, pattern, false); } /** * Removes either the first or all occurrences of the given regular expression in the given string. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param literal Whether the replacement string is literal and therefore requires quoting. * @return The given string with either the first or all occurrences of the given pattern removed. */ public static String remove(String string, String pattern, boolean literal) { return remove(string, pattern, literal, false); } /** * Removes either the first or all occurrences of the given regular expression in the given string. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is removed, otherwise all occurrences are removed. * @return The given string with either the first or all occurrences of the given pattern removed. */ public static String remove(String string, String pattern, boolean literal, boolean firstOnly) { return remove(string, PatternHelper.compile(pattern, literal), firstOnly); } /** * Removes either the first or all occurrences of the given regular expression in the given string list. * * @param string The string to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param firstOnly If true, only the first occurrence is removed, otherwise all occurrences are removed. * @return The given string list with either the first or all occurrences of the given pattern removed. */ public static String remove(String string, Pattern pattern, boolean firstOnly) { return replace(string, pattern, "", firstOnly); } /** * Removes either the first or all occurrences of the given regular expression in the given string. * * @param array The string list to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is removed, otherwise all occurrences are removed. * @return The given string with either the first or all occurrences of the given pattern removed. */ public static String[] remove(String[] array, String pattern, boolean literal, boolean firstOnly) { return remove(array, PatternHelper.compile(pattern, literal), firstOnly); } /** * Removes either the first or all occurrences of the given regular expression in the given string list. * * @param array The string list to remove the pattern from. * @param pattern The regular expression pattern to be removed. * @param firstOnly If true, only the first occurrence is removed, otherwise all occurrences are removed. * @return The given string list with either the first or all occurrences of the given pattern removed. */ public static String[] remove(String[] array, Pattern pattern, boolean firstOnly) { if (array == null || pattern == null) return array; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = remove(array[i], pattern, firstOnly); } return output; } /** * Replaces all occurrences of the given regular expression in the given string with the given replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @return The replaced string. */ public static String replace(String string, String pattern, String replacement, boolean literal) { return replace(string, pattern, replacement, literal, false); } /** * Replaces either the first or all occurrences of the given regular expression in the given string with the given * replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The replaced string. */ public static String replace(String string, String pattern, String replacement, boolean literal, boolean firstOnly) { return replace(string, pattern, false, replacement, literal, firstOnly); } /** * Replaces either the first or all occurrences of the given regular expression in the given string with the given * replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param literalPattern Whether the pattern string is literal and therefore requires quoting. * @param replacement The replacement string. * @param literalReplacement Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The replaced string. */ public static String replace(String string, String pattern, boolean literalPattern, String replacement, boolean literalReplacement, boolean firstOnly) { return replace(string, PatternHelper.compile(pattern, literalPattern), ReplacementHelper.quote(replacement, literalReplacement), firstOnly); } /** * Replaces all occurrences of the given regular expression in the given string with the given replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @return The replaced string. */ public static String replace(String string, Pattern pattern, String replacement) { return replace(string, pattern, replacement, false); } /** * Replaces either the first or all occurrences of the given regular expression in the given string with the given * replacement. * * @param string The string to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The replaced string. */ public static String replace(String string, Pattern pattern, String replacement, boolean firstOnly) { if (string == null || pattern == null || replacement == null) return string; Matcher matcher = pattern.matcher(string); if (firstOnly) { string = matcher.replaceFirst(replacement); } else { string = matcher.replaceAll(replacement); } return string; } /** * Replaces either the first or all occurrences of the given regular expression in the given string array elements * with the given replacement. * * @param array The string array whose elements are to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string array with replaced string elements. */ public static String[] replace(String[] array, String pattern, String replacement, boolean literal, boolean firstOnly) { return replace(array, pattern, false, replacement, literal, firstOnly); } /** * Replaces either the first or all occurrences of the given regular expression in the given string array elements * with the given replacement. * * @param array The string array whose elements are to be replaced. * @param pattern The regular expression pattern. * @param literalPattern Whether the pattern string is literal and therefore requires quoting. * @param replacement The replacement string. * @param literalReplacement Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string array with replaced string elements. */ public static String[] replace(String[] array, String pattern, boolean literalPattern, String replacement, boolean literalReplacement, boolean firstOnly) { return replace(array, PatternHelper.compile(pattern, literalPattern), ReplacementHelper.quote(replacement, literalReplacement), firstOnly); } /** * Replaces either the first or all occurrences of the given regular expression in the given string array elements * with the given replacement. * * @param array The string array whose elements are to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string array with replaced string elements. */ public static String[] replace(String[] array, Pattern pattern, String replacement, boolean firstOnly) { if (array == null || pattern == null || replacement == null) return array; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = replace(array[i], pattern, replacement, firstOnly); } return output; } /** * Replaces either the first or all occurrences of the given regular expression in the given string table elements * with the given replacement. * * @param table The string table whose elements are to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param literal Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string table with replaced string elements */ public static String[][] replace(String[][] table, String pattern, String replacement, boolean literal, boolean firstOnly) { return replace(table, pattern, false, replacement, literal, firstOnly); } /** * Replaces either the first or all occurrences of the given regular expression in the given string table elements * with the given replacement. * * @param table The string table whose elements are to be replaced. * @param pattern The regular expression pattern. * @param literalPattern Whether the pattern string is literal and therefore requires quoting. * @param replacement The replacement string. * @param literalReplacement Whether the replacement string is literal and therefore requires quoting. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string table with replaced string elements */ public static String[][] replace(String[][] table, String pattern, boolean literalPattern, String replacement, boolean literalReplacement, boolean firstOnly) { return replace(table, PatternHelper.compile(pattern, literalPattern), ReplacementHelper.quote(replacement, literalReplacement), firstOnly); } /** * Replaces either the first or all occurrences of the given regular expression in the given string table elements * with the given replacement. * * @param table The string table whose elements are to be replaced. * @param pattern The regular expression pattern. * @param replacement The replacement string. * @param firstOnly If true, only the first occurrence is replaced, otherwise all occurrences are replaced. * @return The string table with replaced string elements. */ public static String[][] replace(String[][] table, Pattern pattern, String replacement, boolean firstOnly) { if (table == null || pattern == null || replacement == null) return table; String[][] output = new String[table.length][]; for (int i = 0; i < table.length; i++) { output[i] = replace(table[i], pattern, replacement, firstOnly); } return output; } /** * Splits a string around each match of the given regular expression pattern. * * @param string The string to be split. * @param pattern The regular expression pattern to split around. * @return The array of strings computed by splitting the given string around matches of this pattern. */ public static String[] split(String string, String pattern) { return split(string, pattern, false); } /** * Splits a string around each match of the given pattern. * * @param string The string to be split. * @param pattern The literal or regular expression pattern to split around. * @param literal Whether the pattern is a literal pattern or a regular expression. * @return The array of strings computed by splitting the given string around matches of this pattern. */ public static String[] split(String string, String pattern, boolean literal) { return split(string, PatternHelper.compile(pattern, literal)); } /** * Splits a string around each match of the given pattern. * * @param string The string to be split. * @param pattern The literal or regular expression pattern to split around. * @return The array of strings computed by splitting the given string around matches of this pattern. */ public static String[] split(String string, Pattern pattern) { String[] output = null; if (string != null && pattern != null) { output = pattern.split(string); } else if (string != null) { output = new String[1]; output[0] = string; } return output; } /** * Returns all the lines in the given string as an array. * * @param string The string to be split into lines. * @return The array of lines from the given string. */ public static String[] lines(String string) { return split(string, "\r?\n"); } /** * Replaces runs of whitespace characters with a single space character, then trims leading and trailing whitespace. * * @param string The string to be condensed. * @return The condensed string. */ public static String condense(String string) { if (string == null) return null; return replace(string, WHITESPACE_PATTERN, " ").trim(); } /** * Replaces runs of whitespace characters with a single space character, then trims leading and trailing whitespace. * * @param array The string array to be condensed. * @return The condensed string array. */ public static String[] condense(String[] array) { if (array == null || array.length == 0) return array; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = condense(array[i]); } return output; } /** * Replaces runs of whitespace characters with a single space character, then trims leading and trailing whitespace. * * @param table The string array to be condensed. * @return The condensed string array. */ public static String[][] condense(String[][] table) { if (table == null || table.length == 0) return table; String[][] output = new String[table.length][]; for (int i = 0; i < table.length; i++) { output[i] = condense(table[i]); } return output; } /** * Trims the given string of leading and trailing whitespace, and converts an empty string to null. * * @param string The string to be squeezed. * @return The squeezed string. */ public static String squeeze(String string) { if (string == null) return null; string = string.trim(); return string.equals("") ? null : string; } /** * Trims the given string of leading and trailing whitespace, and converts empty strings to null. * * @param array The string list to be squeezed. * @return The squeezed string list. */ public static String[] squeeze(String[] array) { if (array == null) return null; String[] output = new String[array.length]; for (int i = 0; i < array.length; i++) { output[i] = squeeze(array[i]); } return output; } /** * Trims the given string table of leading and trailing whitespace, and converts empty strings to null. * * @param table The string table to be squeezed. * @return The squeezed string table. */ public static String[][] squeeze(String[][] table) { if (table == null) return null; String[][] output = new String[table.length][]; for (int i = 0; i < table.length; i++) { output[i] = squeeze(table[i]); } return output; } /** * Pads a string with the given character to the given length. * * @param string The string to pad. * @param length The desired length of the string. If less than 0 the string is padded right to left, otherwise * it is padded from left to right. * @param character The character to pad the string with. * @return The padded string. */ public static String pad(String string, int length, char character) { if (string == null) string = ""; boolean left = length >= 0; if (length < 0) length = length * -1; if (string.length() >= length) return string; StringBuilder builder = new StringBuilder(length); if (!left) builder.append(string); for (int i = string.length(); i < length; i++) { builder.append(character); } if (left) builder.append(string); return builder.toString(); } /** * Pads each string in the given list with the given character to the given length. * * @param input The list of strings to be padded. * @param length The desired length of the strings. If less than 0 the strings are padded right to left, otherwise * they are padded from left to right. * @param character The character to pad the strings with. * @return The list of padded strings. */ public static String[] pad(String[] input, int length, char character) { if (input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = pad(input[i], length, character); } return output; } /** * Compares two strings lexicographically. * * @param string1 The first string to compare. * @param string2 The second string to compare. * @return Less than 0 if the first string is less than the second string, equal to 0 if the two strings are equal, * or greater than 0 if the first string is greater than the second string. */ public static int compare(String string1, String string2) { return compare(string1, string2, false, false); } /** * Compares two strings lexicographically. * * @param string1 The first string to compare. * @param string2 The second string to compare. * @param caseInsensitive Whether the comparison should be case insensitive. * @return Less than 0 if the first string is less than the second string, equal to 0 if the two strings are equal, * or greater than 0 if the first string is greater than the second string. */ public static int compare(String string1, String string2, boolean caseInsensitive) { return compare(string1, string2, caseInsensitive, false); } /** * Compares two strings lexicographically. * * @param string1 The first string to compare. * @param string2 The second string to compare. * @param caseInsensitive Whether the comparison should be case insensitive. * @param whitespaceInsensitive Whether the comparison should be whitespace insensitive. * @return Less than 0 if the first string is less than the second string, equal to 0 if the two strings are equal, * or greater than 0 if the first string is greater than the second string. */ public static int compare(String string1, String string2, boolean caseInsensitive, boolean whitespaceInsensitive) { if (string1 == null && string2 == null) return 0; if (string1 == null) return -1; if (string2 == null) return 1; if (whitespaceInsensitive) { string1 = string1.replaceAll("\\s", ""); string2 = string2.replaceAll("\\s", ""); } if (caseInsensitive) { return string1.compareToIgnoreCase(string2); } else { return string1.compareTo(string2); } } public static String format(Locale locale, String pattern, IData[] arguments, IData scope) { return format(locale, pattern, arguments, null, scope); } public static String format(Locale locale, String pattern, IData[] arguments, IData scope, int index) { return format(locale, pattern, arguments, null, scope, 0); } public static String format(Locale locale, String pattern, IData[] arguments, IData pipeline, IData scope) { return format(locale, pattern, arguments, pipeline, scope, 0); } public static String format(Locale locale, String pattern, IData[] arguments, IData pipeline, IData scope, int index) { if (pattern == null || arguments == null || scope == null) return null; List<Object> args = new ArrayList<Object>(arguments == null? 0 : arguments.length); for (IData argument : arguments) { if (argument != null) { IDataCursor cursor = argument.getCursor(); String key = IDataUtil.getString(cursor, "key"); Object value = IDataUtil.get(cursor, "value"); String type = IDataUtil.getString(cursor, "type"); String argPattern = IDataUtil.getString(cursor, "pattern"); boolean blankify = BooleanHelper.parse(IDataUtil.getString(cursor, "blankify?")); cursor.destroy(); if (key != null && value == null) { value = IDataHelper.get(pipeline, scope, key); if (value == null) { if (key.equals("$index")) { value = index; } else if (key.equals("$iteration")) { value = index + 1; } } } if (value != null) { if (type == null || type.equalsIgnoreCase("string")) { value = value.toString(); } else if (type.equalsIgnoreCase("integer")) { value = BigIntegerHelper.normalize(value); } else if (type.equalsIgnoreCase("decimal")) { value = BigDecimalHelper.normalize(value); } else if (type.equalsIgnoreCase("datetime")) { value = DateTimeHelper.normalize(value, argPattern); } } else if (blankify) { if (type == null || type.equalsIgnoreCase("string")) { value = ""; } else if (type.equalsIgnoreCase("integer")) { value = BigInteger.ZERO; } else if (type.equalsIgnoreCase("decimal")) { value = BigDecimal.ZERO; } } args.add(value); } } return String.format(locale, pattern, args.toArray(new Object[0])); } public static String format(Locale locale, String pattern, IData[] arguments, String recordSeparator, IData ... records) { return format(locale, pattern, arguments, null, recordSeparator, records); } public static String format(Locale locale, String pattern, IData[] arguments, IData pipeline, String recordSeparator, IData ... records) { if (pattern == null || arguments == null || records == null) return null; StringBuilder builder = new StringBuilder(); for (int i = 0; i < records.length; i++) { builder.append(format(locale, pattern, arguments, pipeline, records[i], i)); if (recordSeparator != null) builder.append(recordSeparator); } return builder.toString(); } /** * Returns null if the given string only contains whitespace characters. * * @param input The string to be nullified. * @return Null if the given string only contains whitespace characters, otherwise the given string unmodified. */ public static String nullify(String input) { return nullify(input, true); } /** * Returns null if the given string only contains whitespace characters. * * @param input The string to be nullified. * @param nullify If true, the string will be nullified. * @return Null if the given string only contains whitespace characters, otherwise the given string unmodified. */ public static String nullify(String input, boolean nullify) { return (nullify && (input == null || input.trim().equals(""))) ? null : input; } /** * Converts each string in the given list to null if it only contains whitespace characters. * * @param input The string list to be nullified. * @return The nullified list of strings. */ public static String[] nullify(String[] input) { return nullify(input, true); } /** * Converts each string in the given list to null if it only contains whitespace characters. * * @param input The string list to be nullified. * @param nullify If true, the list will be nullified. * @return The nullified list of strings. */ public static String[] nullify(String[] input, boolean nullify) { if (!nullify || input == null) return null; String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) { output[i] = nullify(input[i], nullify); } return output; } /** * Repeats the given string atom the given count times, returning the result. * * @param atom A string to be repeated. * @param count The number of times to repeat the string. * @return A new string containing the given string atom repeated the given number of times. */ public static String repeat(String atom, int count) { if (atom == null) return null; if (count < 0) throw new IllegalArgumentException("count must be >= 0"); // short-circuit when only 1 repeat is required if (count == 1) return atom; StringBuilder builder = new StringBuilder(); for (int i = 0; i < count; i++) { builder.append(atom); } return builder.toString(); } /** * Reverses the given string. * * @param input A string to be reversed. * @return The reverse of the given string. */ public static String reverse(String input) { return input == null ? null : new StringBuilder(input).reverse().toString(); } private static final char JAVA_IDENTIFIER_ILLEGAL_CHARACTER_REPLACEMENT = '_'; public static String legalize(String input) { if (input == null) return null; char[] characters = input.toCharArray(); StringBuilder output = new StringBuilder(); for (int i = 0; i < characters.length; i++) { char character = characters[i]; if ((i == 0 && !Character.isJavaIdentifierStart(character)) || (i > 0 && !Character.isJavaIdentifierPart(character))) { character = JAVA_IDENTIFIER_ILLEGAL_CHARACTER_REPLACEMENT; } output.append(character); } return output.toString(); } /** * Wraps the given string at the given character width, returning an array of strings containing each line. * * @param input The string to be wrapped. * @param length The number of characters allowed per line. * @return An array of strings containing each resulting line. */ public static String[] wrap(String input, int length) { if (length < 1) throw new IllegalArgumentException("length must be >= 1"); if (input == null) return null; if (!input.endsWith("\n")) input = input + "\n"; Pattern pattern = Pattern.compile("(?m)(.{1," + length + "})\\s|(.{" + length + "})|(.*)$"); Matcher matcher = pattern.matcher(input); List<String> output = new ArrayList<String>(); while(matcher.find()) { output.add(matcher.group(0).trim()); } if (output.size() > 0) output.remove(output.size() - 1); return output.toArray(new String[0]); } /** * Removes all ISO control characters from the given string. * * A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' * or in the range '\u007F' through '\u009F'. * * @param input The string to remove control characters from. * @return The given string with all control characters removed. */ public static String uncontrol(String input) { if (input == null) return null; StringBuilder builder = new StringBuilder(); for (char c : input.toCharArray()) { if (!Character.isISOControl(c)) { builder.append(c); } } return builder.toString(); } /** * Removes all ISO control characters from all string values in the given IData document. * * A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' * or in the range '\u007F' through '\u009F'. * * @param document The IData document to process. * @return A new IData document whose string values contain no control characters. */ public static IData uncontrol(IData document) { return Transformer.transform(document, new Uncontroller()); } /** * Removes all ISO control characters from all string values in the given IData document. * * A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' * or in the range '\u007F' through '\u009F'. * * @param array The IData[] document list to process. * @return A new IData[] document list whose string values contain no control characters. */ public static IData[] uncontrol(IData[] array) { return Transformer.transform(array, new Uncontroller()); } }
package com.wizzardo.tools.http; import com.wizzardo.tools.misc.WrappedException; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.*; import java.util.Iterator; import java.util.List; import java.util.Map; public class Request extends RequestArguments<Request> { protected String url; protected HttpSession session; public Request(String url) { this.url = url; } @Override public Request createRequest(String url) { return super.createRequest(url).setSession(session); } public String getUrl() { try { return createURL(url, params); } catch (UnsupportedEncodingException e) { return url; } } public Response connect() throws IOException { return connect(0); } public Response get() throws IOException { setMethod(ConnectionMethod.GET); return connect(0); } public Response post() throws IOException { setMethod(ConnectionMethod.POST); return connect(0); } protected Request setSession(HttpSession session) { this.session = session; return this; } @Override protected Request self() { return this; } private Response connect(int retryNumber) throws IOException { try { String url = this.url; if (method == ConnectionMethod.GET || (method == ConnectionMethod.POST && data != null)) { url = createURL(url, params); } URL u = new URL(url); HttpURLConnection c; if (proxy != null) { c = (HttpURLConnection) u.openConnection(proxy); } else { c = (HttpURLConnection) u.openConnection(); } c.setInstanceFollowRedirects(false); c.setRequestMethod(method.toString()); for (Map.Entry<String, String> header : headers.entrySet()) { c.setRequestProperty(header.getKey(), header.getValue()); } if (hostnameVerifier != null && url.startsWith("https")) { HttpsURLConnection https = (HttpsURLConnection) c; https.setHostnameVerifier(hostnameVerifier); } if (sslFactory != null && url.startsWith("https")) { HttpsURLConnection https = (HttpsURLConnection) c; https.setSSLSocketFactory(sslFactory); } if (method.equals(ConnectionMethod.POST)) { c.setDoOutput(true); if (!multipart) { if (data == null) { c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); data = createPostParameters(params, charsetForEncoding).getBytes(charsetForEncoding); } c.addRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream out = c.getOutputStream(); out.write(data); out.flush(); out.close(); } else { c.setRequestProperty("Connection", "Keep-Alive"); c.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryZzaC4MkAfrAMfJCJ"); c.setRequestProperty("Content-Length", String.valueOf(getLength())); // c.setChunkedStreamingMode(10240); OutputStream out = c.getOutputStream(); for (Map.Entry<String, List<String>> param : params.entrySet()) { for (String value : param.getValue()) { out.write(" String type = dataTypes.get(param.getKey()) != null ? dataTypes.get(param.getKey()) : ContentType.BINARY.text; if (value.startsWith("file: File f = new File(value.substring(7)); out.write(("Content-Disposition: form-data; name=\"" + param.getKey() + "\"; filename=\"" + f.getName() + "\"\r\n").getBytes()); out.write(("Content-Type: " + type + "\r\n").getBytes()); out.write("\r\n".getBytes()); FileInputStream in = new FileInputStream(f); int r = 0; byte[] b = new byte[10240]; // long rr = 0; while ((r = in.read(b)) != -1) { out.write(b, 0, r); out.flush(); // rr += r; // System.out.println(100f * rr / f.length()); } in.close(); } else if (value.startsWith("array: out.write(("Content-Disposition: form-data; name=\"" + param.getKey() + "\"; filename=\"" + value.substring(8) + "\"\r\n").getBytes()); out.write(("Content-Type: " + type + "\r\n").getBytes()); out.write("\r\n".getBytes()); out.write(dataArrays.get(param.getKey())); } else { out.write(("Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + "\r\n\r\n").getBytes()); out.write(value.getBytes()); } out.write("\r\n".getBytes()); } } out.write(" out.flush(); out.close(); } } if (redirects && (c.getResponseCode() == 301 || c.getResponseCode() == 302)) { Response r = new Response(c, session); return session.createRequest(r.getHeader("Location")).get(); } return new Response(c, session); } catch (SocketTimeoutException e) { if (retryNumber < maxRetryCount) { try { Thread.sleep(pauseBetweenRetries); } catch (InterruptedException ex1) { throw new WrappedException(ex1); } return connect(++retryNumber); } } throw new SocketTimeoutException(); } private int getLength() { int l = 0; l += " for (Map.Entry<String, List<String>> en : params.entrySet()) { for (String value : en.getValue()) { if (value.startsWith("file://") || value.startsWith("array://")) { String type = dataTypes.get(en.getKey()) != null ? dataTypes.get(en.getKey()) : ContentType.BINARY.text; l += ("Content-Type: " + type + "\r\n").length(); if (value.startsWith("file: l += "Content-Disposition: form-data; name=\"\"; filename=\"\"\r\n\r\n\r\n".length() + en.getKey().getBytes().length + new File(value.substring(7)).getName().getBytes().length + value.length(); } else { l += "Content-Disposition: form-data; name=\"\"; filename=\"\"\r\n\r\n\r\n".length() + en.getKey().getBytes().length + dataArrays.get(en.getKey()).length + value.length(); } } else { l += "Content-Disposition: form-data; name=\"\"\r\n\r\n\r\n".length() + en.getKey().getBytes().length + value.getBytes().length; } } } // System.out.println(l); return l; } private String createPostParameters(Map<String, List<String>> params, String urlEncoding) throws UnsupportedEncodingException { if (params == null || params.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<String, List<String>>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, List<String>> entry = iter.next(); boolean and = false; for (String value : entry.getValue()) { if (and) sb.append('&'); else and = true; if (urlEncoding != null) { sb.append(URLEncoder.encode(entry.getKey(), urlEncoding)).append("="); sb.append(URLEncoder.encode(value, urlEncoding)); } else { sb.append(URLEncoder.encode(entry.getKey(), "utf-8")).append("="); sb.append(URLEncoder.encode(value, "utf-8")); } } if (iter.hasNext()) { sb.append("&"); } } return sb.toString(); } private String createURL(String url, Map<String, List<String>> params) throws UnsupportedEncodingException { if (params == null || params.isEmpty()) { return url; } StringBuilder sb = new StringBuilder(url); if (!params.isEmpty()) sb.append("?").append(createPostParameters(params, null).replace("+", "%20")); return sb.toString(); } }
package org.eclipse.che.ide.ext.datasource.client.ssl; import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale; import com.google.gwt.i18n.client.Messages; @DefaultLocale("en") public interface SslMessages extends Messages { @DefaultMessage("Cancel") String cancelButton(); @DefaultMessage("Upload") String uploadButton(); @DefaultMessage("Key/Cert files") String fileNameFieldTitle(); @DefaultMessage("Alias") String keyAlias(); @DefaultMessage("Alias can not be empty") String aliasValidationError(); @DefaultMessage("Upload Private Key") String uploadClientSslKey(); @DefaultMessage("Upload Trust Certificate") String uploadServerSslCert(); @DefaultMessage("SSL Keystore") String sslManagerTitle(); @DefaultMessage("Keys") String sslManagerCategory(); @DefaultMessage("Do you want to delete ssh keys for <b>{0}</b>") String deleteSslKeyQuestion(String alias); @DefaultMessage("Upload SSL client key") String dialogUploadSslKeyTitle(); @DefaultMessage("Upload SSL server trust certificate") String dialogUploadSslTrustCertTitle(); @DefaultMessage("SSL Trust Certificates") String headerTrustList(); @DefaultMessage("SSL Private Key Store") String headerKeyList(); }
package io.spacedog.examples; import java.util.Optional; import java.util.Random; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.spacedog.client.SpaceClient; import io.spacedog.client.SpaceRequest; import io.spacedog.client.SpaceTarget; import io.spacedog.utils.DataPermission; import io.spacedog.utils.Json; import io.spacedog.utils.JsonGenerator; import io.spacedog.utils.Schema; public class Caremen extends SpaceClient { static final Backend DEV = new Backend( "caredev", "caredev", "hi caredev", "david@spacedog.io"); private Backend backend; private JsonGenerator generator = new JsonGenerator(); private Random random = new Random(); @Test public void initCaremenBackend() { backend = DEV; SpaceRequest.configuration().target(SpaceTarget.production); // resetBackend(backend); // initInstallations(); // initVehiculeTypes(); // setSchema(buildCourseSchema(), backend); // setSchema(buildDriverSchema(), backend); // setSchema(buildCustomerSchema(), backend); // setSchema(buildCourseLogSchema(), backend); // createCustomers(); // createDrivers(); } void createCustomers() { Schema schema = buildCustomerSchema(); createCustomer("flavien", schema); createCustomer("aurelien", schema); createCustomer("david", schema); createCustomer("philippe", schema); } User createCustomer(String username, Schema schema) { String password = "hi " + username; String email = "david@spacedog.io"; Optional<User> optional = SpaceClient.login(backend.backendId, username, password, 200, 401); User credentials = optional.isPresent() ? optional.get() : SpaceClient.newCredentials(backend, username, password, email); SpaceRequest.put("/1/credentials/" + credentials.id + "/roles/customer") .adminAuth(backend).go(200); ObjectNode customer = generator.gen(schema, 0); customer.put("credentialsId", credentials.id); customer.put("firstname", credentials.username); customer.put("lastname", credentials.username.charAt(0) + "."); customer.put("phone", "0033662627520"); SpaceRequest.post("/1/data/customer").userAuth(credentials).body(customer).go(201); return credentials; } static Schema buildCustomerSchema() { return Schema.builder("customer") .acl("user", DataPermission.create, DataPermission.search, DataPermission.update) .acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .object("billing") .text("name").french().examples("In-tact SARL") .text("street").french().examples("9 rue Titon") .string("zipcode").examples("75011") .text("town").examples("Paris") .close() .close() .build(); } void initInstallations() { SpaceRequest.delete("/1/schema/installation").adminAuth(backend).go(200, 404); SpaceRequest.put("/1/schema/installation").adminAuth(backend).go(201); Schema schema = SpaceClient.getSchema("installation", backend); schema.acl("key", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("user", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all); SpaceClient.setSchema(schema, backend); } static Schema buildCourseSchema() { return Schema.builder("course") .acl("user", DataPermission.create, DataPermission.read, DataPermission.search, DataPermission.update) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("status").examples("requested") .string("requestedVehiculeType").examples("classic") .timestamp("requestedPickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("pickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("dropoffTimestamp").examples("2016-07-12T14:00:00.000Z") .text("noteForDriver") .floatt("fare").examples(23.82)// in euros .longg("time").examples(1234567)// in millis .integer("distance").examples(12345)// in meters .string("customerId") .object("customer") .string("id") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .close() .object("from") .text("address").french().examples("8 rue Titon 75011 Paris") .geopoint("geopoint") .close() .object("to") .text("address").french().examples("8 rue Pierre Dupont 75010 Paris") .geopoint("geopoint") .close() .object("driver") .string("driverId").examples("robert") .floatt("gain").examples("10.23") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .string("licencePlate").examples("BM-500-FG") .close() .close() .build(); } void createDrivers() { Schema schema = buildDriverSchema(); createDriver("marcel", schema); createDriver("gerard", schema); createDriver("robert", schema); createDriver("suzanne", schema); } void createDriver(String username, Schema schema) { String password = "hi " + username; String email = (username.startsWith("driver") ? "driver" : username) + "@caremen.com"; Optional<User> optional = SpaceClient.login(backend.backendId, username, password, 200, 401); User credentials = optional.isPresent() ? optional.get() : SpaceClient.newCredentials(backend, username, password, email); SpaceRequest.put("/1/credentials/" + credentials.id + "/roles/driver").adminAuth(backend).go(200); ObjectNode driver = generator.gen(schema, 0); driver.put("status", "working"); driver.put("credentialsId", credentials.id); driver.put("firstname", credentials.username); driver.put("lastname", credentials.username.charAt(0) + "."); JsonNode where = Json.object("lat", 48.844 + (random.nextFloat() / 10), "lon", 2.282 + (random.nextFloat() / 10)); Json.set(driver, "lastLocation.where", where); SpaceRequest.post("/1/data/driver").adminAuth(backend).body(driver).go(201); } static Schema buildDriverSchema() { return Schema.builder("driver") .acl("user", DataPermission.search) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("status").examples("working") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .text("homeAddress").french().examples("52 rue Michel Ange 75016 Paris") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("lastLocation") .geopoint("where") .timestamp("when") .close() .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .string("licencePlate").examples("BM-500-RF") .close() .object("RIB") .text("bankName").french().examples("Société Générale") .string("bankCode").examples("SOGEFRPP") .string("accountIBAN").examples("FR568768757657657689") .close() .close() .build(); } static Schema buildCourseLogSchema() { return Schema.builder("courselog") .acl("driver", DataPermission.create) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.delete_all) .string("courseId") .string("driverId") .string("status") .geopoint("where") .close() .build(); } void initVehiculeTypes() { ObjectNode node = Json.objectBuilder() .object("classic") .put("type", "classic") .put("name", "Berline Classic") .put("description", "Standard") .put("minimumPrice", 10) .put("passengers", 4) .end() .object("premium") .put("type", "premium") .put("name", "Berline Premium") .put("description", "Haut de gamme") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("green") .put("type", "green") .put("name", "GREEN BERLINE") .put("description", "Electric cars") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("break") .put("type", "break") .put("name", "BREAK") .put("description", "Grand coffre") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("van") .put("type", "van") .put("name", "VAN") .put("description", "Mini bus") .put("minimumPrice", 15) .put("passengers", 6) .end() .build(); SpaceRequest.put("/1/settings/vehiculeTypes") .adminAuth(backend).body(node).go(201); } }
package org.realityforge.arez; import java.lang.reflect.Field; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public abstract class AbstractArezTest { @BeforeMethod protected void beforeTest() throws Exception { final ArezConfig.DynamicProvider provider = getConfigProvider(); provider.setEnableNames( true ); provider.setVerboseErrorMessages( true ); provider.setCheckInvariants( true ); provider.setPurgeReactionsWhenRunawayDetected( false ); provider.setEnforceTransactionType( true ); getProxyLogger().setLogger( new TestLogger() ); } @AfterMethod protected void afterTest() throws Exception { final ArezConfig.DynamicProvider provider = getConfigProvider(); provider.setEnableNames( false ); provider.setVerboseErrorMessages( false ); provider.setCheckInvariants( false ); provider.setPurgeReactionsWhenRunawayDetected( true ); provider.setEnforceTransactionType( false ); getProxyLogger().setLogger( null ); } @Nonnull final TestLogger getTestLogger() { return (TestLogger) getProxyLogger().getLogger(); } @Nonnull private ArezLogger.ProxyLogger getProxyLogger() { return (ArezLogger.ProxyLogger) ArezLogger.getLogger(); } @Nonnull final ArezConfig.DynamicProvider getConfigProvider() { return (ArezConfig.DynamicProvider) ArezConfig.getProvider(); } @Nonnull private Field getField( @Nonnull final Class<?> type, @Nonnull final String fieldName ) throws NoSuchFieldException { Class clazz = type; while ( null != clazz && Object.class != clazz ) { try { final Field field = clazz.getDeclaredField( fieldName ); field.setAccessible( true ); return field; } catch ( final Throwable t ) { clazz = clazz.getSuperclass(); } } Assert.fail(); throw new IllegalStateException(); } @SuppressWarnings( "SameParameterValue" ) final void setField( @Nonnull final Object object, @Nonnull final String fieldName, @Nullable final Object value ) throws NoSuchFieldException, IllegalAccessException { getField( object.getClass(), fieldName ).set( object, value ); } /** * Typically called to stop observer from being deactivate or stop invariant checks failing. */ @Nonnull final Observer ensureDerivationHasObserver( @Nonnull final Observer observer ) { final Observer randomObserver = newReadOnlyObserver( observer.getContext() ); observer.getDerivedValue().addObserver( randomObserver ); randomObserver.getDependencies().add( observer.getDerivedValue() ); return randomObserver; } @Nonnull final Observer newReadWriteObserver( @Nonnull final ArezContext context ) { return new Observer( context, ValueUtil.randomString(), TransactionMode.READ_WRITE, new TestReaction() ); } @Nonnull final Observer newDerivation( @Nonnull final ArezContext context ) { return new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ).getObserver(); } @Nonnull final Observer newReadOnlyObserverWithNoReaction( @Nonnull final ArezContext context ) { return new Observer( context, ValueUtil.randomString(), TransactionMode.READ_ONLY, null ); } @Nonnull final Observer newReadOnlyObserver( @Nonnull final ArezContext context ) { return new Observer( context, ValueUtil.randomString(), TransactionMode.READ_ONLY, new TestReaction() ); } final void setCurrentTransaction( @Nonnull final ArezContext context ) { setCurrentTransaction( newReadOnlyObserver( context ) ); } final void setCurrentTransaction( @Nonnull final Observer observer ) { final ArezContext context = observer.getContext(); context.setTransaction( new Transaction( context, null, ValueUtil.randomString(), observer.getMode(), observer ) ); } }
package sc.iview.commands.demo; import cleargl.GLVector; import com.jogamp.opengl.math.Quaternion; import graphics.scenery.*; import graphics.scenery.backends.ShaderType; import net.imagej.mesh.Mesh; import org.scijava.command.Command; import org.scijava.command.CommandService; import org.scijava.io.IOService; import org.scijava.log.LogService; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import sc.iview.SciView; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; import static sc.iview.commands.MenuWeights.DEMO; import static sc.iview.commands.MenuWeights.DEMO_MESH; /** * A demo of particle movement. * * @author Kyle Harrington */ @Plugin(type = Command.class, label = "Particle Demo", menuRoot = "SciView", menu = { @Menu(label = "Demo", weight = DEMO), @Menu(label = "Particle", weight = DEMO_MESH+100) }) public class ParticleDemo implements Command { @Parameter private IOService io; @Parameter private LogService log; @Parameter private SciView sciView; @Parameter private CommandService commandService; @Parameter private int numAgents=10; @Override public void run() { List<Node> agents = new ArrayList<>(); Random rng = new Random(17); float dt = 0.5f; float maxX = 10; float maxY = 10; float maxZ = 10; float maxL2 = maxX * maxX + maxY * maxY + maxZ * maxZ; Node master = new Cone(5, 10, 25, new GLVector(0,0,1)); //Material mat = ShaderMaterial.fromFiles("DefaultDeferredInstanced.vert", "DefaultDeferred.frag"); List<ShaderType> sList = new ArrayList<>(); sList.add(ShaderType.VertexShader); sList.add(ShaderType.FragmentShader); //Material mat = ShaderMaterial.fromClass(ParticleDemo.class, sList); Material mat = ShaderMaterial.fromClass(ParticleDemo.class, sList); mat.setAmbient(new GLVector(0.1f, 0f, 0f)); mat.setDiffuse(new GLVector(0.8f, 0.7f, 0.7f)); mat.setDiffuse(new GLVector(0.05f, 0f, 0f)); mat.setMetallic(0.01f); mat.setRoughness(0.5f); master.setMaterial(mat); master.setName("Agent_Master"); master.getInstancedProperties().put("ModelMatrix", master::getModel); master.getInstancedProperties().put("Color", () -> new GLVector(0.5f, 0.5f, 0.5f, 1.0f)); //master.getInstancedProperties().put("Material", master::getMaterial); sciView.addNode(master); for( int k = 0; k < numAgents; k++ ) { //Node n = new Cone(5, 10, 25, new GLVector(0,0,1)); Node n = new graphics.scenery.Mesh(); n.setName("agent_" + k); n.getInstancedProperties().put("ModelMatrix", n::getWorld); //n.getInstancedProperties().put("Material", n::getMaterial); float x = rng.nextFloat()*maxX; float y = rng.nextFloat()*maxY; float z = rng.nextFloat()*maxZ; GLVector vel = new GLVector(rng.nextFloat(),rng.nextFloat(),rng.nextFloat()); final GLVector col = new GLVector(rng.nextFloat(),rng.nextFloat(), ((float) k) / ((float) numAgents), 1.0f); n.getInstancedProperties().put("Color", () -> col); n.setMaterial(master.getMaterial()); n.setPosition(new GLVector(x,y,z)); faceNodeAlongVelocity(n, vel); master.getInstances().add(n); //sciView.addNode(n); agents.add(n); } sciView.animate(30, new Thread(() -> { GLVector vel; Random threadRng = new Random(); for( Node agent : agents ) { GLVector pos = agent.getPosition(); if( pos.length2() > maxL2 ) { // Switch velocity to point toward center + some random perturbation GLVector perturb = new GLVector(threadRng.nextFloat() - 0.5f, threadRng.nextFloat() - 0.5f, threadRng.nextFloat() - 0.5f); vel = pos.times(-1).plus(perturb).normalize(); faceNodeAlongVelocity(agent, vel); } else { vel = (GLVector) agent.getMetadata().get("velocity"); } agent.setPosition(pos.plus(vel.times(dt))); agent.setNeedsUpdate(true); } })); sciView.getFloor().setVisible(false); sciView.centerOnNode( agents.get(0) ); } private void faceNodeAlongVelocity(Node n, GLVector vel) { n.getMetadata().put("velocity",vel); Quaternion newRot = new Quaternion(); float[] dir = new float[]{vel.x(), vel.y(), vel.z()}; float[] up = new float[]{0f, 1f, 0f}; newRot.setLookAt(dir, up, new float[3], new float[3], new float[3]).normalize(); n.setRotation(newRot); } }
package org.nnsoft.shs; import org.nnsoft.shs.http.Response.Status; /** * The Server configuration. * * It has been designed as interface so users are free to implement their proxies on * Properties, XML, JSON, YAML, ... */ public interface HttpServerConfigurator { /** * Configure the host name or the textual representation of its IP address the server has to be bound. * * @param host the host name or the textual representation of its IP address. */ void bindServerToHost( String host ); /** * Configure the port number where binding the server. * * @param port the port number where binding the server. */ void bindServerToPort( int port ); /** * Configure the number of threads that will serve the HTTP requests. * * @param threads the number of threads that will serve the HTTP requests. */ void serveRequestsWithThreads( int threads ); /** * Configure the maximum number of seconds of life of HTTP Sessions. * * @param sessionMaxAge the maximum number of seconds of life of HTTP Sessions. */ void sessionsHaveMagAge( int sessionMaxAge ); /** * Configure the connections keep-alive timeout, in seconds. * * @param keepAliveTimeOut the connections keep-alive timeout, in seconds. */ void keepAliveConnectionsHaveTimeout( int keepAliveTimeOut ); /** * Starts binding a request path, can be expressed using the {@code web.xml} grammar, * to a {@link org.nnsoft.shs.http.RequestHandler}. * * @param path the path for handling calls. * @return the builder to associate a request dispatcher. */ RequestHandlerBuilder serve( String path ); /** * Allows defining the default response has to be shown when * replying to clients with specified status. * * @param status the status the server is replying to clients * @return the builder to associate a fixed file to the given status */ DefaultResponseBuilder when( Status status ); }
package org.pocketcampus.plugin.freeroom.android.adapter; import java.util.List; import java.util.Map; import org.pocketcampus.plugin.freeroom.R; import org.pocketcampus.plugin.freeroom.android.FreeRoomModel; import org.pocketcampus.plugin.freeroom.android.views.FreeRoomHomeView; import org.pocketcampus.plugin.freeroom.shared.FRRoom; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; /** * //TODO: NOT USED as of 2014.04.04, REPLACED BY ExpandableListViewAdapter * <p> * still used for now, may be need a few refactoring! :) * <p> * Simple adapter to use with ExpandableListView, Headers are Strings, Childs * are FRRooms. * * @author FreeRoom Project Team (2014/05) * @author Julien WEBER <julien.weber@epfl.ch> * @author Valentin MINDER <valentin.minder@epfl.ch> * */ public class ExpandableListViewFavoriteAdapter extends ExpandableAbstractListViewAdapter<FRRoom> { FreeRoomHomeView home; public ExpandableListViewFavoriteAdapter(Context c, List<String> header, Map<String, List<FRRoom>> data, FreeRoomModel model, FreeRoomHomeView home) { super(c, header, data, model); this.home = home; } @Override public Object getChild(int groupPosition, int childPosition) { FRRoom child = this.getChildObject(groupPosition, childPosition); if (child != null) { return child.getDoorCode(); } return null; } /** * This method returns the child's object. It is not suitable for display, * use getChild(int, int) instead. * * @param groupPosition * The group id * @param childPosition * The child id * @return The child object FRRoom associated. */ @Override public FRRoom getChildObject(int groupPosition, int childPosition) { if (groupPosition >= headers.size()) { return null; } List<FRRoom> groupList = data.get(headers.get(groupPosition)); if (childPosition >= groupList.size() || groupList == null) { return null; } return groupList.get(childPosition); } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (groupPosition >= headers.size()) { return null; } ViewHolderChild vholder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.freeroom_layout_room_favorites, null); vholder = new ViewHolderChild(); vholder.setTextView((TextView) convertView .findViewById(R.id.freeroom_layout_favlist_text)); vholder.setImageViewMap((ImageView) convertView .findViewById(R.id.freeroom_layout_favlist_map)); vholder.setImageViewStar((ImageView) convertView .findViewById(R.id.freeroom_layout_favlist_fav)); convertView.setTag(vholder); } else { vholder = (ViewHolderChild) convertView.getTag(); } final FRRoom room = this.getChildObject(groupPosition, childPosition); TextView tv = vholder.getTextView(); tv.setText(room.getDoorCode()); final ImageView star = vholder.getImageViewStar(); ImageView map = vholder.getImageViewMap(); map.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri mUri = Uri .parse("pocketcampus://map.plugin.pocketcampus.org/search"); Uri.Builder mbuild = mUri.buildUpon().appendQueryParameter("q", room.getDoorCode()); Intent i = new Intent(Intent.ACTION_VIEW, mbuild.build()); context.startActivity(i); } }); final boolean isFav = mModel.isFavorite(room); if (isFav) { star.setImageResource(R.drawable.ic_action_remove); } else { star.setImageResource(R.drawable.ic_action_favorite_disabled); } star.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (isFav) { star.setImageResource(android.R.drawable.star_big_off); mModel.removeFavorite(room); } else { star.setImageResource(android.R.drawable.star_big_on); mModel.addFavorite(room); } home.updateFavoritesSummary(); notifyDataSetChanged(); } }); vholder.setStarCheck(false); return convertView; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (groupPosition >= headers.size()) { return null; } ViewHolderGroup vholder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.freeroom_layout_building_header_fav, null); vholder = new ViewHolderGroup(); vholder.setTextView((TextView) convertView .findViewById(R.id.freeroom_layout_building_header_fav_title)); vholder.setTextViewExpand((TextView) convertView .findViewById(R.id.freeroom_layout_building_header_fav_show_more_txt)); vholder.setImageViewExpand((ImageView) convertView .findViewById(R.id.freeroom_layout_building_header_fav_show_more)); convertView.setTag(vholder); } else { vholder = (ViewHolderGroup) convertView.getTag(); } String text = (String) headers.get(groupPosition); TextView tv = vholder.getTextView(); tv.setText(text); TextView tv_expand = vholder.getTextViewExpand(); int size = data.get(text).size(); tv_expand.setText(home.getResources().getQuantityString( R.plurals.freeroom_results_room_header, size, size)); ImageView iv_expand = vholder.getImageViewExpand(); if (isExpanded) { iv_expand.setImageResource(R.drawable.ic_action_collapse); } else { iv_expand.setImageResource(R.drawable.ic_action_expand); } return convertView; } /** * Class used to keep a view, it saves ressources by avoiding multiple * inflate and findViewById operations. * */ private class ViewHolderChild { private TextView tv = null; private ImageView map = null; private ImageView star = null; private boolean starChecked = false; public void setTextView(TextView tv) { this.tv = tv; } public TextView getTextView() { return this.tv; } public void setImageViewStar(ImageView iv) { this.star = iv; } public ImageView getImageViewStar() { return this.star; } public void setImageViewMap(ImageView iv) { this.map = iv; } public ImageView getImageViewMap() { return this.map; } public boolean isStarChecked() { return starChecked; } public void setStarCheck(boolean check) { starChecked = check; } } /** * Class used to keep a view, it saves ressources by avoiding multiple * inflate and findViewById operations. * */ private class ViewHolderGroup { private TextView tv = null; private TextView tv_expand = null; private ImageView iv_expand = null; public void setTextView(TextView tv) { this.tv = tv; } public TextView getTextView() { return this.tv; } public void setTextViewExpand(TextView tv) { this.tv_expand = tv; } public TextView getTextViewExpand() { return this.tv_expand; } public void setImageViewExpand(ImageView iv) { this.iv_expand = iv; } public ImageView getImageViewExpand() { return this.iv_expand; } } }
package orca.ahab.libndl.ndl; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.UUID; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.rdf.model.Resource; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.Pair; import orca.ahab.libndl.LIBNDL; import orca.ahab.libndl.SliceGraph; import orca.ahab.libndl.resources.common.ModelResource; import orca.ahab.libndl.resources.request.BroadcastNetwork; import orca.ahab.libndl.resources.request.ComputeNode; import orca.ahab.libndl.resources.request.Interface; import orca.ahab.libndl.resources.request.InterfaceNode2Net; import orca.ahab.libndl.resources.request.Network; import orca.ahab.libndl.resources.request.Node; import orca.ahab.libndl.resources.request.RequestResource; import orca.ahab.libndl.resources.request.StitchPort; import orca.ahab.libndl.resources.request.StorageNode; import orca.ndl.NdlCommons; import orca.ndl.NdlException; import orca.ndl.NdlGenerator; public class NewSliceModel extends NDLModel { public NewSliceModel(){ super(); } public void init(SliceGraph sliceGraph){ try{ String nsGuid = UUID.randomUUID().toString(); ngen = new NdlGenerator(nsGuid, LIBNDL.logger()); reservation = ngen.declareReservation(); Individual term = ngen.declareTerm(); Date start = new Date(); Individual tStart = ngen.declareTermBeginning(start); ngen.addBeginningToTerm(tStart, term); Individual duration = ngen.declareTermDuration(1,0,0); // days, hours, mins ngen.addDurationToTerm(duration, term); ngen.addTermToReservation(term, reservation); } catch (NdlException e) { logger().error("NewSliceModel: " + e.getStackTrace()); } } public void init(SliceGraph sliceGraph, String rdf) { logger().debug("NewSliceModel"); RequestLoader loader = new RequestLoader(sliceGraph, this); loader.load(rdf); //NdlCommons request = loader.load(rdf); try { ngen = loader.getGenerator(); reservation = ngen.declareReservation(); } catch (NdlException e) { logger().error("NewSliceModel: " + e.getStackTrace()); } } public boolean isNewSlice(){ return true; }; @Override public void add(ComputeNode cn, String name) { logger().debug("NewSliceModel:add(ComputeNode)"); try { Individual ni = null; //if (cn.getNodeCount() > 0){ // if (cn.getSplittable()) // ni = ngen.declareServerCloud(name, cn.getSplittable()); // else // ni = ngen.declareServerCloud(name); //} else {sp.getName() ni = ngen.declareComputeElement(name); ngen.addGuid(ni, UUID.randomUUID().toString()); ngen.addVMDomainProperty(ni); mapRequestResource2ModelResource(cn, ni); ngen.addResourceToReservation(reservation, ni); } catch (NdlException e) { logger().error("NewSliceModel:add(ComputeNode):" + e.getStackTrace()); } } @Override public void add(BroadcastNetwork bn, String name) { logger().debug("NewSliceModel:add(BroadcastNetwork)" + name); try { Individual ci = ngen.declareBroadcastConnection(name);; ngen.addGuid(ci, UUID.randomUUID().toString()); ngen.addLayerToConnection(ci, "ethernet", "EthernetNetworkElement"); ngen.addBandwidthToConnection(ci, (long)10000000); //TODO: Should be constant default value mapRequestResource2ModelResource(bn, ci); ngen.addResourceToReservation(reservation, ci); } catch (NdlException e) { logger().error("NewSliceModel:add(ComputeNode):" + e.getStackTrace()); } } @Override public void add(StitchPort sp, String name, String label, String port) { // TODO Auto-generated method stub logger().debug("add(StitchPort sp) sp: " + sp); Individual ni = null; try{ //Add the stitchport ni = ngen.declareStitchingNode(name); mapRequestResource2ModelResource(sp, ni); ngen.addResourceToReservation(reservation, ni); ngen.addGuid(ni, UUID.randomUUID().toString()); //Add a link to the stitchport Individual ei = ngen.declareNetworkConnection(name+"-net"); ngen.addGuid(ei, UUID.randomUUID().toString()); if (reservation != null) ngen.addResourceToReservation(reservation, ei); if (sp.getBandwidth() > 0) ngen.addBandwidthToConnection(ei, sp.getBandwidth()); ngen.addLabelToIndividual(ei, label); ngen.addLayerToConnection(ei, "ethernet", "EthernetNetworkElement"); //processNodeAndLink(pn.getFirst(), e, ei); logger().debug("add(StitchPort sp) port: " + port); logger().debug("add(StitchPort sp) label: " + label); Individual spIface = ngen.declareStitchportInterface(port, label); ngen.addInterfaceToIndividual(spIface, ei); ngen.addInterfaceToIndividual(spIface, ni); } catch (NdlException e){ logger().error("ERROR: NewSliceModel::add(StitchPort) " ); e.printStackTrace(); } } @Override public void add(InterfaceNode2Net i) { Resource r = this.getModelResource(i); Node node = i.getNode(); Network net = i.getLink(); try{ Individual blI = null; //ngen.getRequestIndividual(net.getName()+"-net"); //not sure this is right Individual nodeI = ngen.getRequestIndividual(node.getName()); Individual intI; if (net instanceof StitchPort) { //StitchPort sp = (StitchPort)net; blI = ngen.getRequestIndividual(net.getName()+"-net"); //if ((sp.getLabel() == null) || (sp.getLabel().length() == 0)) // throw new NdlException("URL and label must be specified in StitchPort"); //intI = ngen.declareStitchportInterface(sp.getPort(), sp.getLabel()); } else { blI = ngen.getRequestIndividual(net.getName()); } intI = ngen.declareInterface(net.getName()+"-"+node.getName()); ngen.addInterfaceToIndividual(intI, blI); if (nodeI == null) throw new NdlException("Unable to find or create individual for node " + node); if (intI == null) throw new NdlException("Unable to find or create individual for node " + node); ngen.addInterfaceToIndividual(intI, nodeI); // see if there is an IP address for this link on this node // if (node.getIp(link) != null) { // // create IP object, attach to interface // Individual ipInd = ngen.addUniqueIPToIndividual(n.getIp(l), oc.getName()+"-"+n.getName(), intI); // if (n.getNm(l) != null) // ngen.addNetmaskToIP(ipInd, netmaskIntToString(Integer.parseInt(n.getNm(l)))); ngen.addResourceToReservation(reservation, nodeI); this.mapRequestResource2ModelResource(i, intI); } catch (NdlException e){ logger().error("ERROR: NewSliceModel::add(InterfaceNode2Net) " ); e.printStackTrace(); } } @Override public void add(StorageNode sn, String name) { // TODO Auto-generated method stub } @Override public void remove(ComputeNode cn) { // TODO Auto-generated method stub } @Override public void remove(BroadcastNetwork bn) { // TODO Auto-generated method stub } @Override public void remove(StitchPort sp) { // TODO Auto-generated method stub } @Override public void remove(InterfaceNode2Net i) { // TODO Auto-generated method stub } @Override public void remove(StorageNode sn) { // TODO Auto-generated method stub } @Override public String getRequest() { RequestGenerator saver = new RequestGenerator(ngen); return saver.getRequest(); } }
package se.cybercom.rest.doc; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.CodeSource; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import org.slf4j.Logger; /** * * @author Peter Ivarsson Peter.Ivarsson@cybercom.com */ @Startup @Singleton public class RestDocHandler { private static final Logger logger = org.slf4j.LoggerFactory.getLogger( RestDocHandler.class.getName() ); public static RestInfo restInfo = new RestInfo(); @PostConstruct private void init() { restInfo.setClassInfo( new ArrayList<>() ); restInfo.setDataModelInfo( new ArrayList<>() ); String filePath = System.getProperty( "rest-doc.properties.filepath" ); if( filePath != null ) { final File propsFile = new File( filePath + "/rest-doc.properties" ); if( propsFile.exists() ) { // Only do this if the file rest-doc.properties exists CodeSource src = RestDocHandler.class.getProtectionDomain().getCodeSource(); if( src != null ) { URL jar = src.getLocation(); try { Files.walk( Paths.get( jar.getPath() ) ) .filter( Files::isRegularFile ) .forEach( ( path ) -> { checkClassFilesForPathAnnotations( path ); } ); } catch( IOException ioe ) { logger.debug( "IOException reading war file: " + ioe.getMessage() ); } } } } } private void checkClassFilesForPathAnnotations( Path classNamePath ) { logger.debug( "Class file: " + classNamePath.getFileName().toString() ); ClassInfo classInfo = getFullClassName( classNamePath ); if( classInfo == null ) { // Skipp this file return; } if( classInfo.getPackageAndClassName().startsWith("se.cybercom.rest.doc" ) ) { // Skipp this file, Internal documention Classes return; } try { Class clazz = Class.forName( classInfo.getPackageAndClassName() ); Annotation[] annotations = clazz.getAnnotations(); for( Annotation annotation: annotations ) { if( annotation instanceof javax.ws.rs.Path ) { String pathValue = ((javax.ws.rs.Path) annotation).value(); // We found a class with Path annotation addClassInfoToRestInfoList( classInfo, (javax.ws.rs.Path) annotation ); } } checkClassMethodsForPathInformation( classInfo, clazz ); } catch( ClassNotFoundException cnfe ) { logger.debug( "ClassNotFoundException: " + cnfe.getMessage() ); } } private ClassInfo getFullClassName( Path classNamePath ) { String pathName; String className = ""; int classIndex; StringBuilder packetAndclassName = new StringBuilder(); boolean addDot = false; boolean addPackageName = false; int pathCount = classNamePath.getNameCount(); for( int i = 0; i < pathCount; i++ ) { if( addDot == true ) { packetAndclassName.append( "." ); } pathName = classNamePath.getName( i ).toString(); if( addPackageName == true ) { classIndex = pathName.indexOf( ".class" ); if( classIndex > 0 ) { className = pathName.substring( 0, classIndex ); packetAndclassName.append( className ); } else { packetAndclassName.append( pathName ); addDot = true; } } else { if( pathName.equals( "classes" ) ) { addPackageName = true; } } } if( className.contains( "$" ) ) { // Probarbly an enum value return null; } ClassInfo classInfo = new ClassInfo(); classInfo.setClassName( className ); classInfo.setPackageAndClassName( packetAndclassName.toString() ); return classInfo; } private void addClassInfoToRestInfoList( ClassInfo classInfo, javax.ws.rs.Path annotation ) { String pathValue = annotation.value(); classInfo.setClassRootPath( pathValue ); restInfo.getClassInfo().add( classInfo ); } private void checkClassMethodsForPathInformation( ClassInfo classInfo, Class clazz ) { Method[] methods = clazz.getDeclaredMethods(); for( Method method: methods ) { Annotation[] methodAnnotations = method.getAnnotations(); for( Annotation annotation: methodAnnotations ) { if( annotation instanceof javax.ws.rs.Path ) { // We found a method with Path annotation addMethodInfoToRestInfoList( classInfo, (javax.ws.rs.Path) annotation, method ); } } } } private void addMethodInfoToRestInfoList( ClassInfo classInfo, javax.ws.rs.Path annotation, Method method ) { if( classInfo.getClassRootPath() == null ) { // Add to restInfoList classInfo.setClassRootPath( "" ); restInfo.getClassInfo().add( classInfo ); } List<MethodInfo> methodInfoList = classInfo.getMethodInfo(); if( methodInfoList == null ) { classInfo.setMethodInfo( new ArrayList<>() ); } String pathValue; if( classInfo.getClassRootPath().length() > 0 ) { pathValue = classInfo.getClassRootPath() + "/" + annotation.value(); } else { pathValue = annotation.value(); } ReturnInfo returnInfo = new ReturnInfo(); MethodInfo methodInfo = new MethodInfo(); methodInfo.setReturnInfo( returnInfo ); methodInfo.setMethodName( method.getName() ); methodInfo.setRestPath( pathValue ); classInfo.getMethodInfo().add( methodInfo ); addMethodsPathMethod( methodInfo, returnInfo, method ); addMethodReturnType( methodInfo, returnInfo, method ); addMethodParameters( methodInfo, method ); } private void addMethodsPathMethod( MethodInfo methodInfo, ReturnInfo returnInfo, Method method ) { StringBuilder producesTypes = new StringBuilder(); boolean firstProduceType = true; StringBuilder consumeTypes = new StringBuilder(); boolean firstConsumeType = true; logger.debug( "Method: " + method.toGenericString() ); Annotation[] methodAnnotations = method.getAnnotations(); for( Annotation annotation: methodAnnotations ) { logger.debug( "Method Annotation: " + annotation.annotationType().toGenericString() ); if( annotation instanceof javax.ws.rs.GET ) { methodInfo.setHttpRequestType( "GET" ); } else { if( annotation instanceof javax.ws.rs.POST ) { methodInfo.setHttpRequestType( "POST" ); } else { if( annotation instanceof javax.ws.rs.PUT ) { methodInfo.setHttpRequestType( "PUT" ); } else { if( annotation instanceof javax.ws.rs.DELETE ) { methodInfo.setHttpRequestType( "DELETE" ); } else { if( annotation instanceof javax.ws.rs.Produces ) { javax.ws.rs.Produces produces = (javax.ws.rs.Produces) annotation; for( String returnType: produces.value() ) { if( firstProduceType == true ) { firstProduceType = false; } else { producesTypes.append( ", " ); } producesTypes.append( returnType ); } methodInfo.setProducesType(producesTypes.toString() ); } else { if( annotation instanceof javax.ws.rs.Consumes ) { javax.ws.rs.Consumes consumes = (javax.ws.rs.Consumes) annotation; for( String consumeType: consumes.value() ) { if( firstConsumeType == true ) { firstConsumeType = false; } else { consumeTypes.append( ", " ); } consumeTypes.append( consumeType ); } methodInfo.setConsumeType( consumeTypes.toString() ); } else { if( annotation instanceof se.cybercom.rest.doc.DocReturnType ) { se.cybercom.rest.doc.DocReturnType returnType = (se.cybercom.rest.doc.DocReturnType) annotation; addAnnotatedReturnType( returnInfo, returnType.key() ); } } } } } } } } } private void addMethodReturnType( MethodInfo methodInfo, ReturnInfo returnInfo, Method method ) { returnInfo.setReturnClassName( method.getReturnType().getName() ); } private void addAnnotatedReturnType( ReturnInfo returnInfo, String returnTypeClassName ) { returnInfo.setAnnotatedReturnType( returnTypeClassName ); addDomainDataInfo( returnTypeClassName ); } private void addDomainDataInfo( String className ) { try { Class clazz = Class.forName( className ); DataModelInfo dataModelInfo = new DataModelInfo(); dataModelInfo.setFields( new ArrayList<>() ); Method[] methods = clazz.getMethods(); for( Method method : methods ) { if( isGetter( method ) ) { String fieldType = method.getReturnType().getName(); if( ! fieldType.equals( "java.lang.Class" ) ) { FieldInfo fieldInfo = new FieldInfo(); char c[] = method.getName().substring( 3 ).toCharArray(); c[0] = Character.toLowerCase( c[0] ); fieldInfo.setFieldName( new String(c) ); fieldInfo.setFieldType( fieldType ); dataModelInfo.getFields().add( fieldInfo ); } } } if( ! dataModelInfo.getFields().isEmpty() ) { dataModelInfo.setPackageAndClassName( className ); restInfo.getDataModelInfo().add( dataModelInfo ); } } catch( ClassNotFoundException cnfe ) { logger.debug( "ClassNotFoundException: " + cnfe.getMessage() ); } } private void addMethodParameters( MethodInfo methodInfo, Method method ) { ParameterInfo parameterInfo; if( methodInfo.getParameterInfo() == null ) { methodInfo.setParameterInfo( new ArrayList<>() ); } for( Parameter parameter: method.getParameters() ) { Annotation[] annotations = parameter.getAnnotations(); for( Annotation annotation: annotations ) { if( annotation instanceof javax.ws.rs.PathParam ) { javax.ws.rs.PathParam pathParam = (javax.ws.rs.PathParam) annotation; parameterInfo = new ParameterInfo(); parameterInfo.setParameterType( "javax.ws.rs.PathParam" ); parameterInfo.setParameterAnnotationName( pathParam.value() ); parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); } else { if( annotation instanceof javax.ws.rs.HeaderParam ) { javax.ws.rs.HeaderParam headerParam = (javax.ws.rs.HeaderParam) annotation; parameterInfo = new ParameterInfo(); parameterInfo.setParameterType( "javax.ws.rs.HeaderParam" ); parameterInfo.setParameterAnnotationName( headerParam.value() ); parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); } } } if( annotations.length == 0 ) { // This parameter has no annotation parameterInfo = new ParameterInfo(); if( methodInfo.getConsumeType().isEmpty() ) { parameterInfo.setParameterType( "-" ); } else { parameterInfo.setParameterType( methodInfo.getConsumeType() ); } if( parameter.getName().startsWith( "arg" ) ) { switch( parameter.getName().charAt( 3 ) ) { case '0': parameterInfo.setParameterAnnotationName( "First argument" ); break; case '1': parameterInfo.setParameterAnnotationName( "Second argument" ); break; case '2': parameterInfo.setParameterAnnotationName( "Third argument" ); break; case '3': parameterInfo.setParameterAnnotationName( "Fourth argument" ); break; case '4': parameterInfo.setParameterAnnotationName( "Fifth argument" ); break; case '5': parameterInfo.setParameterAnnotationName( "Sixth argument" ); break; case '6': parameterInfo.setParameterAnnotationName( "Seventh argument" ); break; case '7': parameterInfo.setParameterAnnotationName( "Eighth argument" ); break; case '8': parameterInfo.setParameterAnnotationName( "Ninth argument" ); break; case '9': parameterInfo.setParameterAnnotationName( "Tenth argument" ); break; default: parameterInfo.setParameterAnnotationName( "-" ); break; } } else { parameterInfo.setParameterAnnotationName( parameter.getName() ); } parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); addDomainDataInfo(parameter.getType().getName() ); logger.debug( "Parameter without annotation: " + parameter.getName() + " Type: " + parameter.getType().getName() ); } } } private boolean isGetter( Method method ) { if( ! method.getName().startsWith( "get" ) ) return false; if( method.getParameterTypes().length != 0 ) return false; return ! method.getReturnType().equals( void.class ); } }
package com.lsm; import java.util.Arrays; public interface ListSortMerger { static int[] createResultArray(InsertPosition insertPosition, int[] left, int[] right) { if (insertPosition == InsertPosition.BACK) { // result array = left + right int[] result = Arrays.copyOf(left, left.length + right.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } if (insertPosition == InsertPosition.FRONT) { // result array = right + left int[] result = Arrays.copyOf(right, left.length + right.length); System.arraycopy(left, 0, result, right.length, left.length); return result; } // result array = left/2 + right + left/2 assert insertPosition == InsertPosition.MIDDLE : insertPosition; int[] result = new int[left.length + right.length]; int splitPos = left.length / 2; System.arraycopy(left, 0, result, 0, splitPos); System.arraycopy(right, 0, result, splitPos, right.length); System.arraycopy(left, splitPos, result, splitPos + right.length, splitPos); return result; } /** * Takes two arrays, combines and sorts them * Assumption: "left" array is already sorted * * @param left the "left" array * @param right the "right" array * @return left appended with right, sorted */ int[] sortMerge(int[] left, int[] right); String getName(); }
package org.whattf.checker; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class UsemapChecker extends Checker { private final Map<String, Locator> usemapLocationsById = new LinkedHashMap<String, Locator>(); private final Set<String> mapIds = new HashSet<String>(); private Locator locator = null; public UsemapChecker() { } /** * @see org.whattf.checker.Checker#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("http: if ("map" == localName) { String id = atts.getValue("", "id"); if (id != null && !"".equals(id)) { mapIds.add(id); } String name = atts.getValue("", "id"); if (name != null && !"".equals(name)) { mapIds.add(name); } } else if ("img" == localName || "object" == localName) { String usemap = atts.getValue("", "usemap"); if (usemap != null) { int hashIndex = usemap.indexOf(' if (hashIndex > -1) { // XXX not complaining about bad values here as // the schema takes care of that. if (hashIndex < usemap.length() - 1) { String ref = usemap.substring(hashIndex + 1); usemapLocationsById.put(ref, new LocatorImpl(locator)); } } } } } } /** * @see org.xml.sax.helpers.XMLFilterImpl#endDocument() */ @Override public void endDocument() throws SAXException { for (Map.Entry<String, Locator> entry : usemapLocationsById.entrySet()) { if (!mapIds.contains(entry.getKey())) { err("The hashed ID reference in attribute \u201Cusemap\u201D referred to \u201C" + entry.getKey() + "\u201D, but there is no \u201Cmap\u201D element with that \u201Cid\u201D or \u201Cname\u201D.", entry.getValue()); } } usemapLocationsById.clear(); mapIds.clear(); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startDocument() */ @Override public void startDocument() throws SAXException { usemapLocationsById.clear(); mapIds.clear(); } /** * @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui.bgs; import pythagoras.f.IDimension; import playn.core.ImmediateLayer; import playn.core.PlayN; import playn.core.Surface; import tripleplay.ui.Background; /** * A background that displays a bevel around a solid color. */ public class BeveledBackground extends Background { public BeveledBackground (int bgColor, int ulColor, int brColor) { _bgColor = bgColor; _ulColor = ulColor; _brColor = brColor; } @Override protected Instance instantiate (final IDimension size) { return new LayerInstance( PlayN.graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); float bot = height, right=width; surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_ulColor). drawLine(0, 0, right, 0, 2).drawLine(0, 0, 0, bot, 2); surf.setFillColor(_brColor). drawLine(right, 0, right, bot, 1).drawLine(1, bot-1, right-1, bot-1, 1). drawLine(0, bot, right, bot, 1).drawLine(right-1, 1, right-1, bot-1, 1); } })); } protected final int _bgColor, _ulColor, _brColor; }
package com.twotoasters.jazzylistview; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Point; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import com.nineoldandroids.view.ViewPropertyAnimator; public class JazzyListView extends ListView implements OnScrollListener { public enum TransitionEffect { Standard, Grow, Curl, Wave, Flip, Helix, Fan, Zipper, Fade } private static final String TAG = "Jazzy"; private static final boolean IS_AT_LEAST_HC = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; private static final boolean IS_AT_LEAST_ICS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; public static final int DURATION = 600; public static final int OPAQUE = 255, TRANSPARENT = 0; private TransitionEffect mEffect = TransitionEffect.Standard; private boolean mIsScrolling = false; private int mFirstVisibleItem = -1; private int mLastVisibleItem = -1; public JazzyListView(Context context) { this(context, null); } public JazzyListView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public JazzyListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setOnScrollListener(this); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.JazzyListView); String strEffect = null; try { strEffect = a.getString(R.styleable.JazzyListView_effect); TransitionEffect effect = TransitionEffect.valueOf(strEffect); setTransitionEffect(effect); } catch (IllegalArgumentException e) { Log.w(TAG, "Invalid jazzy list view transition effect: " + strEffect); } a.recycle(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { Log.v(TAG, String.format("onScroll() - [firstVis: %d, visItemCount: %d, totItemCount: %d]", firstVisibleItem, visibleItemCount, totalItemCount)); boolean shouldAnimateItems = (mFirstVisibleItem != -1 && mLastVisibleItem != -1); int lastVisibleItem = firstVisibleItem + visibleItemCount - 1; if (IS_AT_LEAST_HC && mIsScrolling && shouldAnimateItems) { int indexAfterFirst = 0; while(firstVisibleItem + indexAfterFirst < mFirstVisibleItem) { Log.v(TAG, "Scrolled to reveal new item(s) ABOVE"); View item = view.getChildAt(indexAfterFirst); doJazziness(item, firstVisibleItem+indexAfterFirst, -1); indexAfterFirst++; } int indexBeforeLast = 0; while(lastVisibleItem - indexBeforeLast > mLastVisibleItem) { Log.v(TAG, "Scrolled to reveal new item(s) BELOW"); View item = view.getChildAt(lastVisibleItem - firstVisibleItem - indexBeforeLast); doJazziness(item, lastVisibleItem, 1); indexBeforeLast++; } } mFirstVisibleItem = firstVisibleItem; mLastVisibleItem = lastVisibleItem; } /** * Initializes the item view and triggers the animation. * @param item The view to be animated. * @param position The index of the view in the list. * @param scrollDirection Positive number indicating scrolling down, or negative number indicating scrolling up. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void doJazziness(View item, int position, int scrollDirection) { if (mIsScrolling) { ViewPropertyAnimator animator = com.nineoldandroids.view.ViewPropertyAnimator .animate(item) .setDuration(DURATION) .setInterpolator(new AccelerateDecelerateInterpolator()); int itemWidth = item.getWidth(); int itemHeight = item.getHeight(); scrollDirection = scrollDirection > 0 ? 1 : -1; switch (mEffect) { case Standard: break; case Grow: item.setPivotX(itemWidth / 2); item.setPivotY(itemHeight / 2); item.setScaleX(0.01f); item.setScaleY(0.01f); animator.scaleX(1).scaleY(1); break; case Curl: item.setPivotX(0); item.setPivotY(itemHeight / 2); item.setRotationY(90); animator.rotationY(0); break; case Wave: item.setTranslationX(-itemWidth); animator.translationX(0); break; case Flip: item.setPivotX(itemWidth / 2); item.setPivotY(itemHeight / 2); item.setRotationX(-90 * scrollDirection); animator.rotationXBy(90 * scrollDirection); break; case Helix: item.setRotationY(180); animator.rotationYBy(180 * scrollDirection); break; case Fan: item.setPivotX(0); item.setPivotY(0); item.setRotation(70 * scrollDirection); animator.rotationBy(-70 * scrollDirection); break; case Zipper: boolean isEven = position % 2 == 0; item.setTranslationX((isEven ? -1 : 1) * itemWidth); animator.translationX(0); break; case Fade: item.setAlpha(TRANSPARENT); animator.setDuration(animator.getDuration()*5); animator.alpha(OPAQUE); break; default: break; } animator.start(); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch(scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: mIsScrolling = false; break; case OnScrollListener.SCROLL_STATE_FLING: case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: mIsScrolling = true; break; default: break; } Log.v(TAG, String.format("isScrolling: %s", Boolean.valueOf(mIsScrolling))); } public void setTransitionEffect(TransitionEffect effect) { mEffect = effect; } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private Point getScreenDimensions(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); if(IS_AT_LEAST_ICS) { display.getSize(point); } else { point.set(display.getWidth(), display.getHeight()); } return point; } }
package com.opencsv; import com.lmax.disruptor.*; public abstract interface RowHandler<T> extends EventHandler<T>,LifecycleAware { }
package us.myles.ViaVersion.api; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.protocol.Protocol; import us.myles.ViaVersion.protocols.base.ProtocolInfo; import java.util.UUID; @Getter(AccessLevel.PROTECTED) @RequiredArgsConstructor public abstract class ViaListener implements Listener { private final ViaVersionPlugin plugin; private final Class<? extends Protocol> requiredPipeline; private boolean registered = false; /** * Get the UserConnection from a player * * @param player Player object * @return The UserConnection */ protected UserConnection getUserConnection(@NonNull Player player) { return getUserConnection(player.getUniqueId()); } /** * Get the UserConnection from an UUID * * @param uuid UUID object * @return The UserConnection */ protected UserConnection getUserConnection(@NonNull UUID uuid) { if (!plugin.isPorted(uuid)) return null; return plugin.getConnection(uuid); } /** * Checks if the player is on the selected pipe * * @param player Player Object * @return True if on pipe */ protected boolean isOnPipe(Player player) { return isOnPipe(player.getUniqueId()); } /** * Checks if the UUID is on the selected pipe * * @param uuid UUID Object * @return True if on pipe */ protected boolean isOnPipe(UUID uuid) { UserConnection userConnection = getUserConnection(uuid); return userConnection != null && userConnection.get(ProtocolInfo.class).getPipeline().contains(requiredPipeline); } /** * Register as Bukkit event */ public void register() { if (registered) return; plugin.getServer().getPluginManager().registerEvents(this, plugin); registered = true; } }
package android.network.socket; import android.network.socket.codec.Decode; import android.network.socket.codec.Encode; import android.network.socket.codec.Handle; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class DramSocket implements Runnable { private InetSocketAddress address; private ExecutorService pool; private Socket socket; private WriteRunnable writeRunnable; private Encode encode; private Decode decode; private Handle handle; private boolean running; public void connect(String host, int port) { this.address = new InetSocketAddress(host, port); } public void connect(InetSocketAddress address) { this.address = address; } public <E, D> void processor(Encode<E> encode, Decode<D> decode, Handle<D> handle) { this.encode = encode; this.decode = decode; this.handle = handle; } public void start() { if (encode == null) { throw new NullPointerException(""); } if (decode == null) { throw new NullPointerException(""); } if (handle == null) { throw new NullPointerException(""); } if (address == null) { throw new NullPointerException(""); } if (running) { return; } if(pool != null){ if(!pool.isShutdown()){ pool.shutdown(); } pool = null; } pool = Executors.newFixedThreadPool(2); running = true; writeRunnable = new WriteRunnable(encode); pool.execute(this); } @Override public void run() { synchronized (this) { while (running) { try { socket = new Socket(); socket.connect(address); if (socket.isConnected()) { writeRunnable.setOutputStream(socket.getOutputStream()); pool.execute(writeRunnable); handle.onStatus(Handle.STATUS_CONNECTED); read(socket, decode, handle); } } catch (Exception e) { e.printStackTrace(); try { handle.onStatus(Handle.STATUS_FAIL); socket = null; if (running) { this.wait(6000); } } catch (InterruptedException ie) { ie.printStackTrace(); } } } } } public void send(Object data) { if (writeRunnable != null) { writeRunnable.send(data); } } public void stop() { running = false; if (writeRunnable != null) { writeRunnable.stop(); writeRunnable = null; } if (socket != null) { shutdownInput(socket); shutdownOutput(socket); close(socket); socket = null; if (handle != null) { handle.onStatus(Handle.STATUS_DISCONNECT); } } if (pool != null && !pool.isShutdown()) { pool.shutdown(); } } private <D> void read(Socket socket, Decode<D> decode, Handle<D> handle) throws Exception { final ByteBuffer buffer = ByteBuffer.allocate(102400);//buffer byte[] bytes = new byte[buffer.capacity()]; byte[] cache = new byte[buffer.capacity()]; byte[] swap = new byte[buffer.capacity()]; int cacheLength = 0; int readLength; InputStream stream = socket.getInputStream(); while ((readLength = stream.read(bytes)) > 0) { System.arraycopy(bytes, 0, cache, cacheLength, readLength); cacheLength += readLength; buffer.clear();//ByteBuffer buffer.put(cache, 0, cacheLength); buffer.flip(); buffer.mark();//reset D data; while (buffer.hasRemaining() && ((data = decode.decode(buffer)) != null)) {//ByteBuffer handle.onReceive(data);//Handler if (buffer.hasRemaining()) {//ByteBuffer int remaining = buffer.remaining();//ByteBuffer int position = buffer.position();//ByteBuffer System.arraycopy(cache, position, swap, 0, remaining); System.arraycopy(swap, 0, cache, 0, remaining); cacheLength = remaining; buffer.clear();//ByteBuffer buffer.put(cache, 0, cacheLength); buffer.flip(); } buffer.mark(); } buffer.reset();//make if (buffer.hasRemaining()) { int remaining = buffer.remaining(); buffer.get(cache, 0, remaining); cacheLength = remaining; } else { cacheLength = 0; } } } private static final class WriteRunnable<E> implements Runnable { private Vector<E> vector = new Vector<>(); private Encode<E> encode; private OutputStream stream; private boolean sending; private ByteBuffer buffer = ByteBuffer.allocate(102400); private WriteRunnable(Encode<E> encode) { this.encode = encode; } private void setOutputStream(OutputStream stream) { this.stream = stream; } @Override public void run() { synchronized (this) { sending = true; while (sending) { if (vector.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } while (vector.size() > 0) { E data = vector.remove(0); buffer.clear(); encode.encode(data, buffer); buffer.flip(); if (stream != null) { try { stream.write(buffer.array(), 0, buffer.limit()); stream.flush(); } catch (Exception e) { e.printStackTrace(); } } } } } } private void stop() { sending = false; this.stream = null; synchronized (this) { this.notify(); } } private void send(E data) { this.vector.add(data); synchronized (this) { this.notify(); } } } private static void shutdownInput(Socket socket) { if (socket != null && !socket.isInputShutdown()) { try { socket.shutdownInput(); } catch (IOException e) { e.printStackTrace(); } } } private static void shutdownOutput(Socket socket) { if (socket != null && !socket.isOutputShutdown()) { try { socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); } } } private static void close(Socket socket) { if (socket != null && !socket.isClosed()) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package com.rapid.core; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; public abstract class Process extends Thread { // protected instance variables protected ServletContext _servletContext; protected String _name; protected int _interval; protected JSONObject _parameters; protected boolean _stopped; // protected static variables protected Logger _logger; // constructor public Process(ServletContext servletContext, JSONObject parameters) throws JSONException { // store values _servletContext = servletContext; _parameters = parameters; _name = parameters.getString("name"); _interval = parameters.getInt("interval"); // get a logger for this class _logger = LogManager.getLogger(this.getClass()); } // abstract methods public abstract void doProcess(); // protected methods protected ServletContext getServletContext() { return _servletContext; } protected String getProcessName() { return _name; } protected int getInterval() { return _interval; } protected Applications getApplications() { return (Applications) _servletContext.getAttribute("applications"); } // override methods @Override public void start() { if (_interval > 0) { super.start(); // log that we've started _logger.info("Process " + _name + " has started, checking every " + _interval + " seconds"); } else { // set stopped _stopped = true; // log that we won't be started _logger.info("Process " + _name + " will not be started, interval must be greater than 0"); } } @Override public void run() { // loop until stopped while (!_stopped) { Date now = new Date(); DateFormat dateFormat = null; boolean runToday = false; try { // If days specified in the schema if (_parameters.has("days")) { _logger.trace("There are days in the xml"); JSONObject days = _parameters.getJSONObject("days"); dateFormat = new SimpleDateFormat("EEEE"); String today = (dateFormat.format(now)).toLowerCase(); // Check if Iam on the right day. if (days.has(today) && days.getBoolean(today)) { _logger.trace("I am currently on the right day!"); // we should run today runToday = true; } // otherwise today is not the right day //Otherwise, no days specified in the schema } else { // no days specified in the schema so run everyday runToday = true; } // If I am allowed to runToday (either I am in the right day, or no days were specified) if (runToday) { // Check if the duration are specified in the xml if (_parameters.has("duration")) { _logger.trace("Durations are specified!"); // get the duration JSONObject duration = _parameters.getJSONObject("duration"); // get the duration start and stop String start = duration.getString("start"); String stop = duration.getString("stop"); // Check whether the start/stop time has the 'seconds' portion. Add if not if (start.length() < 6) start += ":00"; if (stop.length() < 6) stop += ":00"; // get today's start and stop date objects using their time Date startTime = getTodayTimeDate(now, start); Date stopTime = getTodayTimeDate(now, stop); // calculate the difference between the currentTime and the 'start' time long millisToStart = startTime.getTime() - now.getTime(); // calculate the difference between the currentTime and // the 'stop' time plus a second so that the stop time // in seconds is inclusive i.e up to .999 millis long millisToStop = stopTime.getTime() - now.getTime() + 1000; // if stop is less or same as than start, and we haven't // run yet set to 0 so we run at least once if (millisToStop <= millisToStart) millisToStop = millisToStart + _interval * 1000 - 1; // If the currentTime is before the specified start time if (millisToStart > 0) { _logger.trace("Before process start time.. Should sleep for " + millisToStart / 1000 + " seconds"); // Sleep until the start time Thread.sleep(millisToStart); // If the currentTime is between the start and stop time } else if (millisToStart <= 0 && millisToStop > 0) { _logger.trace("Between process start and stop time..Should run the process. and then sleep for interval " + _interval); // run the abstract method doProcess(); // Then sleep at interval rate Thread.sleep(_interval * 1000); // Otherwise, the currentTime should be after the start/stop time } else { // In this case, sleep until tomorrow's start time Long millisToTomorrowStart = millisToStart + (24 * 60 * 60 * 1000); _logger.trace("After process start time and stop time.. Should sleep until tomorrow's start: for " + millisToTomorrowStart / 1000 + " seconds"); // Sleep until tomorrow's start time Thread.sleep(millisToTomorrowStart); } // Otherwise, no duration is provided in the schema } else { // run and sleep at interval rate continuously _logger.trace("No duration specified, run and sleep at interval rate"); // run the abstract method doProcess(); // Then sleep at interval rate Thread.sleep(_interval * 1000); } // Otherwise, I am not supposed to run today. Today is not the right day - days had to be provided } else { // Check if the duration is provided if (_parameters.has("duration")) { // Obtain the start time string String start = _parameters.getJSONObject("duration").getString("start"); // get the start time Date startTime = getTodayTimeDate(now, start); // calculate the difference between the currentTime and the 'start' time long millisToStart = startTime.getTime() - now.getTime(); // tomorrow start is today start + 24 hours milliseconds Long millisToTomorrowStart = millisToStart + (24 * 60 * 60 * 1000); _logger.trace("Not running today - sleep " + millisToStart/1000 + " secs until tomorrow's start"); // sleep until tomorrow's specified start Thread.sleep(millisToTomorrowStart); // Otherwise, no duration is provided in the schema. To be here, days had to be provided, but not today } else { // get the last second of today Date endOfToday = getTodayTimeDate(now, "23:59:59"); // get millis to end of today plus one second to get to midnight tomorrow Long millisToEndOfToday = endOfToday.getTime() - now.getTime() + 1000; _logger.trace("Days specified, but not today, and no duration specified, sleep " + millisToEndOfToday/1000 + " secs until the end of today"); // sleep to end of today Thread.sleep(millisToEndOfToday); } // duration check } // day check } catch (JSONException | ParseException ex) { _logger.error("Error in process " + _name, ex); _stopped = true; } catch (InterruptedException ex) { _logger.error("Process " + _name + " was interrupted!", ex); _stopped = true; } } // end of while // log stopped _logger.error("Process " + _name + " has stopped"); } // Returns a date object of today's date with given time private Date getTodayTimeDate(Date now, String time) throws ParseException { // Create a start and stop datetime string, to be parsed into date object DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); // append the time String timeString = dateFormat.format(now) + " " + time; // assume date format pattern without seconds String pattern = "dd/MM/yyyy HH:mm"; // if time contains seconds add to pattern if (time.length() > 5) pattern += ":ss"; // update the dateFormat to include time dateFormat = new SimpleDateFormat(pattern); // get the date Date todayTime = dateFormat.parse(timeString); // log _logger.trace("getTodayTimeDate " + now + " " + time + " = " + todayTime); // return the parsed date return todayTime; } @Override public void interrupt() { _stopped = true; super.interrupt(); } }
package org.deidentifier.arx.framework.data; import java.util.Arrays; /** * Encodes a data object consisting of a dictionary encoded two-dimensional * array, an associated dictionary, a header and a mapping to the columns in the * input data set * * @author Fabian Prasser * @author Florian Kohlmayer */ public class Data implements Cloneable{ /** The outliers mask */ public static final int OUTLIER_MASK = 1 << 31; /** The inverse outliers mask */ public static final int REMOVE_OUTLIER_MASK = ~OUTLIER_MASK; /** Row, Dimension. */ private final int[][] data; /** The header */ private final String[] header; /** The associated dictionary */ private final Dictionary dictionary; /** The associated map */ private final int[] map; /** * Creates a new data object. * * @param data * The int array * @param header * The header * @param map * The map * @param dictionary * The dictionary */ public Data(final int[][] data, final String[] header, final int[] map, final Dictionary dictionary) { this.data = data; this.header = header; this.dictionary = dictionary; this.map = map; } /** * Returns the data array * * @return */ public int[][] getArray() { return data; } /** * Returns the data * * @return */ public int[][] getData() { return data; } /** * Returns the number of rows. * * @return the data length */ public int getDataLength() { return data.length; } /** * Returns the dictionary * * @return */ public Dictionary getDictionary() { return dictionary; } /** * Returns the header * * @return */ public String[] getHeader() { return header; } /** * Returns the map * * @return */ public int[] getMap() { return map; } @Override public Data clone(){ int[][] newData = new int[data.length][]; for (int i=0; i < data.length; i++){ newData[i] = Arrays.copyOf(data[i], header.length); } return new Data(newData, header, map, dictionary); } }
package org.eclipse.birt.report.designer.internal.ui.views.actions; import java.util.Iterator; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.model.api.DesignFileException; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; public class RefreshModuleHandleAction extends AbstractViewAction { public static final String ID = "org.eclipse.birt.report.designer.internal.ui.views.actions.RefreshModuleHandleAction"; //$NON-NLS-1$ public static final String ACTION_TEXT = Messages.getString( "RefreshModuleHandleAction.Action.Text" ); //$NON-NLS-1$ /** * @param selectedObject */ public RefreshModuleHandleAction( Object selectedObject ) { super( selectedObject, ACTION_TEXT ); } /** * @param selectedObject * @param text */ public RefreshModuleHandleAction( Object selectedObject, String text ) { super( selectedObject, text ); } /* * (non-Javadoc) * * @see isEnabled() */ public boolean isEnabled( ) { if ( getSelection( ) instanceof ReportDesignHandle || getSelection( ) instanceof LibraryHandle ) { return true; } else return false; } /* * (non-Javadoc) * * @see org.eclipse.jface.action.Action#run() */ public void run( ) { Object obj = getSelection( ); if ( obj instanceof ReportDesignHandle || obj instanceof LibraryHandle ) { ModuleHandle moduleHandle = (ModuleHandle) obj; try { moduleHandle.reloadLibraries( ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } catch ( DesignFileException e ) { // TODO Auto-generated catch block ExceptionHandler.handle( e ); } } } }
package com.oasisfeng.android.base; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import com.oasisfeng.android.base.Scopes.Scope; import com.oasisfeng.android.content.CrossProcessSharedPreferences; import java.util.HashSet; import java.util.Set; /** @author Oasis */ public class Scopes { /* These preferences file should be included in backup configuration of your app */ public static final String KPrefsNameAppScope = "app.scope"; public static final String KPrefsNameVersionScope = "version.scope"; public interface Scope { boolean isMarked(@NonNull String tag); boolean mark(@NonNull String tag); boolean unmark(@NonNull String tag); } /** Throughout the whole lifecycle of this installed app, until uninstalled. (can also be extended to re-installation if configured with backup) */ public static Scope app(final Context context) { return new AppScope(context); } /** Throughout the current version (code) of this installed app, until the version changes. */ public static Scope version(final Context context) { return new VersionScope(context); } /** Throughout the current update of this installed app, until being updated by in-place re-installation. */ public static Scope update(final Context context) { return new UpdateScope(context); } /** Throughout the current running process of this installed app, until being terminated. */ public static Scope process() { return ProcessScope.mSingleton; } /** Throughout the time-limited session within current running process of this installed app, until session time-out. */ public static Scope session(final Activity activity) { if (SessionScope.mSingleton == null) SessionScope.mSingleton = new SessionScope(activity); return SessionScope.mSingleton; } private Scopes() {} } class SessionScope extends MemoryBasedScopeImpl { private static final int KSessionTimeout = 5 * 60 * 1000; // TODO: Configurable SessionScope(final Activity activity) { activity.getApplication().registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityResumed(final Activity a) { if (System.currentTimeMillis() >= mTimeLastSession + KSessionTimeout) mSeen.clear(); } @Override public void onActivityPaused(final Activity a) { mTimeLastSession = System.currentTimeMillis(); } @Override public void onActivityStopped(final Activity a) {} @Override public void onActivityStarted(final Activity a) {} @Override public void onActivitySaveInstanceState(final Activity a, final Bundle s) {} @Override public void onActivityCreated(final Activity a, final Bundle s) {} @Override public void onActivityDestroyed(final Activity a) {} }); } private long mTimeLastSession = 0; static SessionScope mSingleton; } class ProcessScope extends MemoryBasedScopeImpl { static final Scope mSingleton = new ProcessScope(); } class MemoryBasedScopeImpl implements Scope { @Override public boolean isMarked(@NonNull final String tag) { return mSeen.contains(tag); } @Override public boolean mark(@NonNull final String tag) { return mSeen.add(tag); } @Override public boolean unmark(@NonNull final String tag) { return mSeen.remove(tag); } final Set<String> mSeen = new HashSet<>(); } class UpdateScope extends SharedPrefsBasedScopeImpl { private static final String KPrefsKeyLastUpdateTime = "update-time"; UpdateScope(final Context context) { super(resetIfLastUpdateTimeChanged(context, CrossProcessSharedPreferences.get(context, "update.scope"))); } private static SharedPreferences resetIfLastUpdateTimeChanged(final Context context, final SharedPreferences prefs) { final long last_update_time = Versions.lastUpdateTime(context); if (last_update_time != prefs.getLong(KPrefsKeyLastUpdateTime, 0)) prefs.edit().clear().putLong(KPrefsKeyLastUpdateTime, last_update_time).apply(); return prefs; } } class VersionScope extends SharedPrefsBasedScopeImpl { private static final String KPrefsKeyVersionCode = "version-code"; VersionScope(final Context context) { super(resetIfVersionChanges(context, CrossProcessSharedPreferences.get(context, Scopes.KPrefsNameVersionScope))); } private static SharedPreferences resetIfVersionChanges(final Context context, final SharedPreferences prefs) { final int version = Versions.code(context); if (version != prefs.getInt(KPrefsKeyVersionCode, 0)) prefs.edit().clear().putInt(KPrefsKeyVersionCode, version).apply(); return prefs; } } class AppScope extends SharedPrefsBasedScopeImpl { AppScope(final Context context) { super(CrossProcessSharedPreferences.get(context, Scopes.KPrefsNameAppScope)); } } class SharedPrefsBasedScopeImpl implements Scope { private static final String KPrefsKeyPrefix = "mark-"; private static final String KPrefsKeyPrefixLegacy = "first-time-"; // Old name, for backward-compatibility @Override public boolean isMarked(@NonNull final String tag) { return mPrefs.getBoolean(KPrefsKeyPrefix + tag, false); } @Override public boolean mark(@NonNull final String tag) { final String key = KPrefsKeyPrefix + tag; if (mPrefs.getBoolean(key, false)) return false; mPrefs.edit().putBoolean(key, true).apply(); return true; } @Override public boolean unmark(@NonNull final String tag) { final String key = KPrefsKeyPrefix + tag; if (! mPrefs.getBoolean(key, false)) return false; mPrefs.edit().putBoolean(key, false).apply(); return true; } SharedPrefsBasedScopeImpl(final SharedPreferences prefs) { mPrefs = prefs; // Migrate legacy entries SharedPreferences.Editor editor = null; for (final String key : prefs.getAll().keySet()) { if (! key.startsWith(KPrefsKeyPrefixLegacy)) continue; if (editor == null) editor = prefs.edit(); try { editor.putBoolean(KPrefsKeyPrefix + key.substring(KPrefsKeyPrefixLegacy.length()), ! prefs.getBoolean(key, true)); } catch (final ClassCastException ignored) {} editor.remove(key); } if (editor != null) editor.apply(); } private final SharedPreferences mPrefs; }
package io.branch.referral; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; public class ServerRequestQueue { private static final String PREF_KEY = "BNCServerRequestQueue"; private static final int MAX_ITEMS = 25; private static ServerRequestQueue SharedInstance; private SharedPreferences sharedPref; private SharedPreferences.Editor editor; private final List<ServerRequest> queue; public static ServerRequestQueue getInstance(Context c) { if(SharedInstance == null) { synchronized(ServerRequestQueue.class) { if(SharedInstance == null) { SharedInstance = new ServerRequestQueue(c); } } } return SharedInstance; } @SuppressLint( "CommitPrefEdits" ) private ServerRequestQueue (Context c) { sharedPref = c.getSharedPreferences("BNC_Server_Request_Queue", Context.MODE_PRIVATE); editor = sharedPref.edit(); queue = retrieve(); } private void persist() { new Thread(new Runnable() { @Override public void run() { JSONArray jsonArr = new JSONArray(); synchronized(queue) { for (ServerRequest aQueue : queue) { JSONObject json = aQueue.toJSON(); if (json != null) { jsonArr.put( json ); } } try { editor.putString(PREF_KEY, jsonArr.toString()).commit(); } catch (ConcurrentModificationException ex) { PrefHelper.Debug("Persisting Queue: ", jsonArr.toString()); } finally { try { editor.putString(PREF_KEY, jsonArr.toString()).commit(); } catch (ConcurrentModificationException ignored) {} } } } }).start(); } private List<ServerRequest> retrieve() { List<ServerRequest> result = Collections.synchronizedList(new LinkedList<ServerRequest>()); String jsonStr = sharedPref.getString(PREF_KEY, null); if (jsonStr != null) { try { JSONArray jsonArr = new JSONArray(jsonStr); for (int i = 0; i < jsonArr.length(); i++) { JSONObject json = jsonArr.getJSONObject(i); ServerRequest req = ServerRequest.fromJSON(json); if (req != null) { result.add(req); } } } catch (JSONException ignored) { } } return result; } public int getSize() { return queue.size(); } public void enqueue(ServerRequest request) { if (request != null) { queue.add(request); if (getSize() >= MAX_ITEMS) { queue.remove(1); } persist(); } } public ServerRequest dequeue() { ServerRequest req = null; try { req = queue.remove(0); persist(); } catch (IndexOutOfBoundsException ignored) { } catch (NoSuchElementException ignored) { } return req; } public ServerRequest peek() { ServerRequest req = null; try { req = queue.get(0); } catch (IndexOutOfBoundsException ignored) { } catch (NoSuchElementException ignored) { } return req; } public ServerRequest peekAt(int index) { ServerRequest req = null; try { req = queue.get(index); } catch (IndexOutOfBoundsException ignored) { } catch (NoSuchElementException ignored) { } return req; } public void insert(ServerRequest request, int index) { try { queue.add(index, request); persist(); } catch (IndexOutOfBoundsException ignored) { } } public ServerRequest removeAt(int index) { ServerRequest req = null; try { req = queue.remove(index); persist(); } catch (IndexOutOfBoundsException ignored) { } return req; } public boolean containsClose() { synchronized(queue) { for (ServerRequest req : queue) { if (req != null && req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { return true; } } } return false; } public boolean containsInstallOrOpen() { synchronized(queue) { for (ServerRequest req : queue) { if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { return true; } } } return false; } public void moveInstallOrOpenToFront(String tag, int networkCount) { synchronized(queue) { Iterator<ServerRequest> iter = queue.iterator(); while (iter.hasNext()) { ServerRequest req = iter.next(); if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { tag = BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL; } else { tag = BranchRemoteInterface.REQ_TAG_REGISTER_OPEN; } iter.remove(); break; } } } ServerRequest req = new ServerRequest(tag); if (networkCount == 0) { insert(req, 0); } else { insert(req, 1); } } }
package com.sksamuel.jqm4gwt.list; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.shared.GwtEvent.Type; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiChild; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.Widget; import com.sksamuel.jqm4gwt.DataIcon; import com.sksamuel.jqm4gwt.HasCorners; import com.sksamuel.jqm4gwt.HasInset; import com.sksamuel.jqm4gwt.JQMCommon; import com.sksamuel.jqm4gwt.JQMContext; import com.sksamuel.jqm4gwt.JQMPage; import com.sksamuel.jqm4gwt.JQMWidget; import com.sksamuel.jqm4gwt.events.HasTapHandlers; import com.sksamuel.jqm4gwt.events.JQMComponentEvents; import com.sksamuel.jqm4gwt.events.JQMHandlerRegistration; import com.sksamuel.jqm4gwt.events.JQMHandlerRegistration.WidgetHandlerCounter; import com.sksamuel.jqm4gwt.events.TapEvent; import com.sksamuel.jqm4gwt.events.TapHandler; import com.sksamuel.jqm4gwt.html.ListWidget; public class JQMList extends JQMWidget implements HasClickHandlers, HasTapHandlers, HasInset<JQMList>, HasFilter<JQMList>, HasCorners<JQMList> { /** * An ordered JQMList */ public static class Ordered extends JQMList { public Ordered() { super(true); } } /** * An unordered JQMList */ public static class Unordered extends JQMList { public Unordered() { super(false); } } /** The underlying &lt;li> or &lt;ul> widget */ private final ListWidget list; /** The index of the last click */ private int clickIndex; private boolean clickIsSplit; /** * The collection of items added to this list */ private final List<JQMListItem> items = new ArrayList<JQMListItem>(); /** * Create a new unordered {@link JQMList} */ public JQMList() { this(false); } /** * Create a new {@link JQMList} that is unordered or ordered depending on the given boolean. * * @param ordered true if you want an ordered list, false otherwise. */ public JQMList(boolean ordered) { list = new ListWidget(ordered); initWidget(list); setStyleName("jqm4gwt-list"); setDataRole("listview"); setId(); } /** * Registers a new {@link ClickHandler} on this list. * <p/> * When a click event has been fired, you can get a reference to the position that was clicked by getClickIndex() * and a reference to the item that was clicked with getClickItem() */ @Override public HandlerRegistration addClickHandler(ClickHandler handler) { return list.addDomHandler(handler, ClickEvent.getType()); } @Override public HandlerRegistration addTapHandler(TapHandler handler) { // this is not a native browser event so we will have to manage it via JS return JQMHandlerRegistration.registerJQueryHandler(new WidgetHandlerCounter() { @Override public int getHandlerCountForWidget(Type<?> type) { return getHandlerCount(type); } }, this, handler, JQMComponentEvents.TAP_EVENT, TapEvent.getType()); } public void addDivider(int index, JQMListDivider d) { list.insert(d, index); items.add(index, null); // to keep the list and items in sync } /** * Add a new divider with the given text and an automatically assigned id. * * @return the created divider which can be used to change the text dynamically. Changes to that * instance write back to this list. */ public HasText addDivider(String text) { JQMListDivider d = new JQMListDivider(text); appendDivider(d); return d; } /** * For UiBinder. */ @UiChild(tagname = "divider") public void appendDivider(JQMListDivider divider) { addDivider(items.size(), divider); } public void addItem(int index, final JQMListItem item) { list.insert(item, index); items.add(index, item); item.setList(this); } public JQMListItem addItem(int index, String text) { return addItem(index, text, (String) null); } public JQMListItem addItem(int index, String text, String url) { JQMListItem item = new JQMListItem(text, url); addItem(index, item); return item; } /** * Add a new read only item */ public JQMListItem addItem(String text) { return addItem(text, (String) null); } public static enum ListItemImageKind { NONE, THUMBNAIL, ICON } public JQMListItem addItem(String text, String url, ListItemImageKind imageKind, String imageUrl) { return addItem(items.size(), text, url, imageKind, imageUrl); } public JQMListItem addItem(int index, String text, String url, ListItemImageKind imageKind, String imageUrl) { // In case if icon/thumbnail is present there is severe rendering problem, JQMListItem item = null; boolean hasImage = imageKind != ListItemImageKind.NONE; boolean clickable = url != null; if (hasImage) { // workaround is needed for proper rendering if (clickable) { item = addItem(index, text, url); } else { item = addItem(index, text); // Empty url cannot be used, because we don't need clickable and right arrow icon item.addHeaderText(1, ""); } switch (imageKind) { case ICON: if (imageUrl != null && !imageUrl.isEmpty()) item.setIcon(imageUrl); break; case THUMBNAIL: if (imageUrl != null && !imageUrl.isEmpty()) item.setThumbnail(imageUrl); break; default: break; } } else { item = addItem(index, text, url); } return item; } /** * For UiBinder. */ @UiChild(tagname = "item") public void appendItem(JQMListItem item) { addItem(items.size(), item); } /** * Adds a new {@link JQMListItem} that contains the given @param text as the heading element. * <p/> * The list item is made linkable to the given page * * @param text the text to use as the content of the header element * @param page the page to make the list item link to */ public JQMListItem addItem(String text, JQMPage page) { return addItem(text, "#" + page.getId()); } /** * Adds a new {@link JQMListItem} that contains the given @param text as the content. Note that if you want to * navigate to an internal url (ie, another JQM Page) then you must prefix the url with a hash. IE, the hash is * not added automatically. This allows you to navigate to external urls as well. * <p/> * If you add an item after the page has been created then you must call .refresh() to update the layout. * <p/> * The list item is made linkable to the @param url */ public JQMListItem addItem(String text, String url) { JQMListItem item = new JQMListItem(text, url); addItem(items.size(), item); return item; } /** * Add a collection of read only items. */ public JQMList addItems(Collection<String> items) { for (String item : items) addItem(item); return this; } /** * Remove all items from this list. */ public void clear() { list.clear(); items.clear(); } /** * Returns true if this list contains the given item * * @param item the {@link JQMListItem} to check for */ public boolean contains(JQMListItem item) { return items.contains(item); } /** * Returns the index of the last click. This is useful in event handlers when one wants to get a reference to * which item was clicked. * * @return the index of the last clicked item */ public int getClickIndex() { return clickIndex; } public boolean getClickIsSplit() { return clickIsSplit; } /** * Returns the JQMListItem that was last clicked on. This is useful in event handlers when one wants to get a * reference to which item was clicked. * * @return the last clicked item */ public JQMListItem getClickItem() { return items.get(getClickIndex()); } public String getCountTheme() { return getAttribute("data-count-theme"); } /** * Returns the currently set theme for dividers * * @return the data divider theme string, eg "b" */ public String getDividerTheme() { return getAttribute("data-divider-theme"); } @Override public JQMList withFilterable(boolean filterable) { setFilterable(filterable); return this; } public String getFilterPlaceholder() { return getAttribute("data-filter-placeholder"); } public void setFilterPlaceholder(String placeholderText) { setAttribute("data-filter-placeholder", placeholderText); } public String getFilterTheme() { return getAttribute("data-filter-theme"); } /** * Sets the color scheme (swatch) for the search filter bar. * It accepts a single letter from a-z that maps to the swatches included in your theme. */ public JQMList setFilterTheme(String theme) { setAttribute("data-filter-theme", theme); return this; } public boolean isFilterReveal() { return "true".equals(JQMCommon.getAttribute(this, "data-filter-reveal")); } public void setFilterReveal(boolean value) { JQMCommon.setAttribute(this, "data-filter-reveal", value ? "true" : null); } /** * Returns the {@link JQMListItem} at the given position */ public JQMListItem getItem(int pos) { return items.get(pos); } /** * Returns a List of {@link JQMListItem}s currently set on this list. * @return the items, null values for divider locations! */ public List<JQMListItem> getItems() { return items; } /** * @return - true if there is not null {@link JQMListItem} in items. */ public boolean isAnyListItem() { for (JQMListItem li : items) { if (li != null) return true; } return false; } public interface LiCallback { void on(JQMListItem item); } public void forEach(LiCallback callback) { if (callback == null) return; for (JQMListItem li : items) { if (li == null) continue; callback.on(li); } } public void setAllChecked(boolean checked) { for (JQMListItem li : items) { if (li == null || li.isChecked() == checked) continue; li.setChecked(checked); } } public static enum ListChecked { NONE, ANY, ALL } public ListChecked getCheckedInfo() { boolean anyChecked = false; boolean allChecked = true; int cnt = 0; for (JQMListItem li : items) { if (li == null || !li.isCheckBox()) continue; cnt++; if (!li.isChecked()) { allChecked = false; if (anyChecked) break; } else { anyChecked = true; if (!allChecked) break; } } if (cnt == 0) allChecked = false; if (allChecked) return ListChecked.ALL; else if (anyChecked) return ListChecked.ANY; else return ListChecked.NONE; } public boolean isAnyChecked() { for (JQMListItem li : items) { if (li == null || !li.isCheckBox()) continue; if (li.isChecked()) return true; } return false; } @Override public boolean isInset() { return "true".equals(getElement().getAttribute("inset")); } /** * Call to refresh the list after a programmatic change is made. * <p/> In some cases you have to call recreate() first, and then refresh(), for example * when adding complex list items. */ public void refresh() { refresh(getElement()); } protected native void refresh(Element elt) /*-{ var w = $wnd.$(elt); if (w.data('mobile-listview') !== undefined) { w.listview('refresh'); } }-*/; /** * Needed in some cases (when refresh() is not enough/working) for dynamic list views. * <p>For example after adding complex list items you have to call recreate() and then refresh().</p> */ public void recreate() { JQMContext.render(getElement()); } /** * Remove the divider with the given text. This method will search all the dividers and remove the first divider * found with the given text. * * @return true if a divider with the given text was found and removed, otherwise false. */ public boolean removeDivider(String text) { for (int k = 0; k < list.getWidgetCount(); k++) { Widget w = list.getWidget(k); if (JQMListDivider.ATTR_VALUE.equals(w.getElement().getAttribute(JQMListDivider.ATTR_NAME)) && w.getElement().getInnerText().equals(text)) { list.remove(k); items.remove(k); return true; } } return false; } /** * Remove the divider with the given tag. This method will search all the dividers and remove the first divider * found with the given tag. * * @return true if a divider with the given tag was found and removed, otherwise false. */ public boolean removeDivider(Object tag) { if (tag == null) return false; for (int k = 0; k < list.getWidgetCount(); k++) { Widget w = list.getWidget(k); if (JQMListDivider.ATTR_VALUE.equals(w.getElement().getAttribute(JQMListDivider.ATTR_NAME)) && tag.equals(((JQMListDivider) w).getTag())) { list.remove(k); items.remove(k); return true; } } return false; } /** * Find the divider with the given text. This method will search all the dividers and return the first divider * found with the given text. * * @return the divider with the given text (if found, or null otherwise). */ public JQMListDivider findDivider(String text) { for (int k = 0; k < list.getWidgetCount(); k++) { Widget w = list.getWidget(k); if (JQMListDivider.ATTR_VALUE.equals(w.getElement().getAttribute(JQMListDivider.ATTR_NAME)) && w.getElement().getInnerText().equals(text)) { return (JQMListDivider) w; } } return null; } /** * Find the divider with the given tag. This method will search all the dividers and return the first divider * found with the given tag. * * @return the divider with the given tag (if found, or null otherwise). */ public JQMListDivider findDivider(Object tag) { if (tag == null) return null; for (int k = 0; k < list.getWidgetCount(); k++) { Widget w = list.getWidget(k); if (JQMListDivider.ATTR_VALUE.equals(w.getElement().getAttribute(JQMListDivider.ATTR_NAME)) && tag.equals(((JQMListDivider) w).getTag())) { return (JQMListDivider) w; } } return null; } public int findDividerIdx(JQMListDivider d) { if (d == null) return -1; for (int k = 0; k < list.getWidgetCount(); k++) { Widget w = list.getWidget(k); if (d.equals(w)) return k; } return -1; } /** * For given divider finds the index at which new item should be inserted to become a part of * this divider's group. * * @return - proper index for new item insertion, or -1 in case of error * */ public int findInsertIdxByDivider(JQMListDivider d) { if (d == null) return -1; int i = findDividerIdx(d); if (i == -1) return -1; List<JQMListItem> lst = getItems(); int rslt = i + 1; while (rslt < lst.size()) { if (lst.get(rslt) == null) { // next divider return rslt; } rslt++; } return rslt; } public JQMListItem findItem(String text) { if (text == null) return null; List<JQMListItem> lst = getItems(); for (JQMListItem i : lst) { if (i == null) continue; if (text.equals(i.getText())) return i; } return null; } /** * Removes the item at the given position. * * @param pos the integer position, 0 indexed */ public void removeItem(int pos) { items.remove(pos); list.remove(pos); } /** * Removes the given item from the list * * @param item the item to remove */ public void removeItem(JQMListItem item) { if (item != null) { items.remove(item); list.remove(item); } } /** * Removes all the given items. Conveniece method for calling removeItem(JQMListItem)multiple times. */ public void removeItems(List<JQMListItem> items) { for (JQMListItem item : items) removeItem(item); } public JQMList setAutoDividers(boolean auto) { getElement().setAttribute("data-autodividers", String.valueOf(auto)); return this; } protected JQMList setClickIndex(int clickIndex, boolean isSplit) { this.clickIndex = clickIndex; this.clickIsSplit = isSplit; return this; } JQMList setClickItem(JQMListItem item, boolean isSplit) { setClickIndex(list.getWidgetIndex(item), isSplit); return this; } /** * Sets the color scheme (swatch) for list item count bubbles. It accepts a single letter from a-z that maps to * the swatches included in your theme. */ public JQMList setCountTheme(String theme) { setAttribute("data-count-theme", theme); return this; } /** * Sets the theme attribute for the data dividers */ public JQMList setDividerTheme(String theme) { setAttribute("data-divider-theme", theme); return this; } public JQMList setHeaderTheme(String theme) { setAttribute("data-header-theme", theme); return this; } @Override public void setInset(boolean inset) { if (inset) getElement().setAttribute("data-inset", "true"); else getElement().removeAttribute("data-inset"); } @Override public JQMList withInset(boolean inset) { setInset(inset); return this; } public void setSplitTheme(String theme) { setAttribute("data-split-theme", theme); } public JQMList withSplitTheme(String theme) { setSplitTheme(theme); return this; } public String getSplitTheme() { return getAttribute("data-split-theme"); } public void setSplitIcon(DataIcon icon) { setAttribute("data-split-icon", icon != null ? icon.getJqmValue() : null); } public DataIcon getSplitIcon() { String s = getAttribute("data-split-icon"); return DataIcon.fromJqmValue(s); } @Override public boolean isCorners() { return JQMCommon.isCorners(this); } @Override public void setCorners(boolean corners) { JQMCommon.setCorners(this, corners); } @Override public JQMList withCorners(boolean corners) { setCorners(corners); return this; } }
package gov.nih.nci.cabig.report2caaers; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_INVOCATION_COMPLETED; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_INVOCATION_INITIATED; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_IN_TRANSFORMATION; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_OUT_TRANSFORMATION; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.POST_PROCESS_EDI_MSG; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.PRE_PROCESS_EDI_MSG; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.REQUEST_RECEIVED; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.ROUTED_TO_CAAERS_RESPONSE_SINK; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.ROUTED_TO_CAAERS_WS_INVOCATION_CHANNEL; import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.E2B_SCHEMATRON_VALIDATION; import static gov.nih.nci.cabig.caaers2adeers.track.Tracker.track; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.camel.Exchange; import org.apache.camel.Processor; import gov.nih.nci.cabig.caaers2adeers.Caaers2AdeersRouteBuilder; public class ToCaaersReportWSRouteBuilder { private static String caAERSSafetyReportJBIURL = "jbi:service:http: private static String requestXSLBase = "xslt/e2b/request/"; private static String responseXSLBase = "xslt/e2b/response/"; private static String[] msgComboIdPaths = { "//safetyreportid", "//messagedate"}; private String inputEDIDir; private String outputEDIDir; private Caaers2AdeersRouteBuilder routeBuilder; public void configure(Caaers2AdeersRouteBuilder rb){ this.routeBuilder = rb; Map<String, String> nss = new HashMap<String, String>(); nss.put("svrl", "http://purl.oclc.org/dsdl/svrl"); routeBuilder.from("file://"+inputEDIDir+"?preMove=inprogress&move=done&moveFailed=movefailed") .convertBodyTo(String.class, "UTF-8") .convertBodyTo(byte[].class, "Windows-1252") .convertBodyTo(String.class, "UTF-8") .to("log:gov.nih.nci.cabig.report2caaers.caaers-ws-request?showHeaders=true&level=TRACE") .processRef("removeEDIHeadersAndFootersProcessor") .processRef("crlfFixProcessor") .process(track(REQUEST_RECEIVED, msgComboIdPaths)) .to(routeBuilder.getFileTracker().fileURI(REQUEST_RECEIVED)) .processRef("eDIMessagePreProcessor") .process(track(PRE_PROCESS_EDI_MSG)) .to(routeBuilder.getFileTracker().fileURI(PRE_PROCESS_EDI_MSG)) .to("direct:performSchematronValidation"); //perform schematron validation routeBuilder.from("direct:performSchematronValidation") .process(track(E2B_SCHEMATRON_VALIDATION)) .to("xslt:" + requestXSLBase + "safetyreport_e2b_schematron.xsl?transformerFactoryClass=net.sf.saxon.TransformerFactoryImpl") //for XSLT2.0 support .to(routeBuilder.getFileTracker().fileURI(E2B_SCHEMATRON_VALIDATION)) .choice() .when().xpath("//svrl:failed-assert", nss) .to("xslt:" + responseXSLBase + "extract-failures.xsl") .to("xslt:" + responseXSLBase + "E2BSchematronErrors2ACK.xsl") .to("direct:sendE2BAckSink") .otherwise() .to("direct:processE2B"); routeBuilder.from("direct:processE2B") .to("log:gov.nih.nci.cabig.report2caaers.caaers-ws-request?showHeaders=true&level=TRACE") .processRef("resetOriginalMessageProcessor") .to("direct:caaers-reportSubmit-sync"); nss = new HashMap<String, String>(); nss.put("soap", "http://schemas.xmlsoap.org/soap/envelope/"); nss.put("ns1", "http://schema.integration.caaers.cabig.nci.nih.gov/aereport"); nss.put("ns3", "http://schema.integration.caaers.cabig.nci.nih.gov/common"); //content based router //if it is saveSafetyReportResponse, then E2B ack will not be sent //also, if submit safety report is processed successfully to indicate succesfully submitted to AdEERS, then E2B ack will not be sent routeBuilder.from("direct:processedE2BMessageSink") .to("log:gov.nih.nci.cabig.report2caaers.caaers-ws-request?showHeaders=true&level=TRACE") .choice() .when().xpath("/soap:Envelope/soap:Body/ns1:saveSafetyReportResponse", nss) .to("direct:morgue") .when().xpath("/ichicsrack/acknowledgment/messageacknowledgment/parsingerrormessage", nss) .to("direct:sendE2BAckSink") .otherwise() .to("direct:morgue"); routeBuilder.from("direct:sendE2BAckSink") .process(track(ROUTED_TO_CAAERS_WS_INVOCATION_CHANNEL)) .processRef("addEDIHeadersAndFootersProcessor") .process(track(POST_PROCESS_EDI_MSG)) .to(routeBuilder.getFileTracker().fileURI(POST_PROCESS_EDI_MSG)) .to("file://"+outputEDIDir); //caAERS - createParticipant configureWSCallRoute("direct:caaers-reportSubmit-sync", "safetyreport_e2b_sync.xsl", caAERSSafetyReportJBIURL + "submitSafetyReport" ); } private void configureWSCallRoute(String fromSink, String xslFileName, String serviceURI){ this.routeBuilder.configureWSCallRoute(fromSink, requestXSLBase + xslFileName, serviceURI, responseXSLBase + xslFileName, "direct:processedE2BMessageSink", CAAERS_WS_IN_TRANSFORMATION, CAAERS_WS_INVOCATION_INITIATED, CAAERS_WS_INVOCATION_COMPLETED, CAAERS_WS_OUT_TRANSFORMATION, ROUTED_TO_CAAERS_RESPONSE_SINK); } public String getInputEDIDir() { return inputEDIDir; } public void setInputEDIDir(String inputEDIDir) { this.inputEDIDir = inputEDIDir; } public String getOutputEDIDir() { return outputEDIDir; } public void setOutputEDIDir(String outputEDIDir) { this.outputEDIDir = outputEDIDir; } }
package org.eclipse.smarthome.binding.wemo.handler; import static org.eclipse.smarthome.binding.wemo.WemoBindingConstants.*; import java.math.BigDecimal; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.binding.wemo.internal.http.WemoHttpCall; import org.eclipse.smarthome.config.core.Configuration; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingStatusInfo; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.io.transport.upnp.UpnpIOParticipant; import org.eclipse.smarthome.io.transport.upnp.UpnpIOService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WemoLightHandler extends BaseThingHandler implements UpnpIOParticipant { private final Logger logger = LoggerFactory.getLogger(WemoLightHandler.class); private Map<String, Boolean> subscriptionState = new HashMap<String, Boolean>(); private UpnpIOService service; private WemoBridgeHandler wemoBridgeHandler; private String wemoLightID; private int currentBrightness; /** * Set dimming stepsize to 5% */ private static final int DIM_STEPSIZE = 5; protected final static String SUBSCRIPTION = "bridge1"; protected final static int SUBSCRIPTION_DURATION = 600; /** * The default refresh interval in Seconds. */ private int DEFAULT_REFRESH_INTERVAL = 60; /** * The default refresh initial delay in Seconds. */ private static int DEFAULT_REFRESH_INITIAL_DELAY = 15; private ScheduledFuture<?> refreshJob; private Runnable refreshRunnable = new Runnable() { @Override public void run() { try { if (!isUpnpDeviceRegistered()) { logger.debug("WeMo UPnP device {} not yet registered", getUDN()); } getDeviceState(); onSubscription(); } catch (Exception e) { logger.debug("Exception during poll : {}", e); } } }; public WemoLightHandler(Thing thing, UpnpIOService upnpIOService) { super(thing); if (upnpIOService != null) { logger.debug("UPnPIOService '{}'", upnpIOService); this.service = upnpIOService; } else { logger.debug("upnpIOService not set."); } } @Override public void initialize() { // initialize() is only called if the required parameter 'deviceID' is available wemoLightID = (String) getConfig().get(DEVICE_ID); if (getBridge() != null) { logger.debug("Initializing WemoLightHandler for LightID '{}'", wemoLightID); if (getBridge().getStatus() == ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); onSubscription(); onUpdate(); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.BRIDGE_OFFLINE); } } else { updateStatus(ThingStatus.OFFLINE); } } @Override public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) { updateStatus(ThingStatus.ONLINE); onSubscription(); onUpdate(); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.BRIDGE_OFFLINE); if (refreshJob != null && !refreshJob.isCancelled()) { refreshJob.cancel(true); refreshJob = null; } } } @Override public void dispose() { logger.debug("WeMoLightHandler disposed."); removeSubscription(); if (refreshJob != null && !refreshJob.isCancelled()) { refreshJob.cancel(true); refreshJob = null; } } private synchronized WemoBridgeHandler getWemoBridgeHandler() { if (this.wemoBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.error("Required bridge not defined for device {}.", wemoLightID); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof WemoBridgeHandler) { this.wemoBridgeHandler = (WemoBridgeHandler) handler; } else { logger.debug("No available bridge handler found for {} bridge {} .", wemoLightID, bridge.getUID()); return null; } } return this.wemoBridgeHandler; } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { try { getDeviceState(); } catch (Exception e) { logger.debug("Exception during poll : {}", e); } } else { Configuration configuration = getConfig(); configuration.get(DEVICE_ID); WemoBridgeHandler wemoBridge = getWemoBridgeHandler(); if (wemoBridge == null) { logger.debug("wemoBridgeHandler not found, cannot handle command"); return; } String devUDN = "uuid:" + wemoBridge.getThing().getConfiguration().get(UDN).toString(); logger.trace("WeMo Bridge to send command to : {}", devUDN); String value = null; String capability = null; switch (channelUID.getId()) { case CHANNEL_BRIGHTNESS: capability = "10008"; if (command instanceof PercentType) { int newBrightness = ((PercentType) command).intValue(); logger.trace("wemoLight received Value {}", newBrightness); int value1 = Math.round(newBrightness * 255 / 100); value = value1 + ":0"; currentBrightness = newBrightness; } else if (command instanceof OnOffType) { switch (command.toString()) { case "ON": value = "255:0"; break; case "OFF": value = "0:0"; break; } } else if (command instanceof IncreaseDecreaseType) { int newBrightness; switch (command.toString()) { case "INCREASE": currentBrightness = currentBrightness + DIM_STEPSIZE; newBrightness = Math.round(currentBrightness * 255 / 100); if (newBrightness > 255) { newBrightness = 255; } value = newBrightness + ":0"; break; case "DECREASE": currentBrightness = currentBrightness - DIM_STEPSIZE; newBrightness = Math.round(currentBrightness * 255 / 100); if (newBrightness < 0) { newBrightness = 0; } value = newBrightness + ":0"; break; } } break; case CHANNEL_STATE: capability = "10006"; switch (command.toString()) { case "ON": value = "1"; break; case "OFF": value = "0"; break; } break; } try { String soapHeader = "\"urn:Belkin:service:bridge:1#SetDeviceStatus\""; String content = "<?xml version=\"1.0\"?>" + "<s:Envelope xmlns:s=\"http: + "<s:Body>" + "<u:SetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceStatusList>" + "&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;DeviceStatus&gt;&lt;DeviceID&gt;" + wemoLightID + "&lt;/DeviceID&gt;&lt;IsGroupAction&gt;NO&lt;/IsGroupAction&gt;&lt;CapabilityID&gt;" + capability + "&lt;/CapabilityID&gt;&lt;CapabilityValue&gt;" + value + "&lt;/CapabilityValue&gt;&lt;/DeviceStatus&gt;" + "</DeviceStatusList>" + "</u:SetDeviceStatus>" + "</s:Body>" + "</s:Envelope>"; String wemoURL = getWemoURL(); if (wemoURL != null && capability != null && value != null) { String wemoCallResponse = WemoHttpCall.executeCall(wemoURL, soapHeader, content); if (wemoCallResponse != null) { if (capability != null && capability.equals("10008") && value != null) { OnOffType binaryState = null; binaryState = value.equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { updateState(CHANNEL_STATE, binaryState); } } } } } catch (Exception e) { throw new RuntimeException("Could not send command to WeMo Bridge", e); } } } @Override public String getUDN() { WemoBridgeHandler wemoBridge = getWemoBridgeHandler(); if (wemoBridge == null) { logger.debug("wemoBridgeHandler not found"); return null; } return (String) wemoBridge.getThing().getConfiguration().get(UDN); } /** * The {@link getDeviceState} is used for polling the actual state of a WeMo Light and updating the according * channel states. */ public void getDeviceState() { logger.debug("Request actual state for LightID '{}'", wemoLightID); try { String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\""; String content = "<?xml version=\"1.0\"?>" + "<s:Envelope xmlns:s=\"http: + "<s:Body>" + "<u:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>" + wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>"; String wemoURL = getWemoURL(); if (wemoURL != null) { String wemoCallResponse = WemoHttpCall.executeCall(wemoURL, soapHeader, content); if (wemoCallResponse != null) { wemoCallResponse = StringEscapeUtils.unescapeXml(wemoCallResponse); String response = StringUtils.substringBetween(wemoCallResponse, "<CapabilityValue>", "</CapabilityValue>"); logger.trace("wemoNewLightState = {}", response); String[] splitResponse = response.split(","); if (splitResponse[0] != null) { OnOffType binaryState = null; binaryState = splitResponse[0].equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { updateState(CHANNEL_STATE, binaryState); } } if (splitResponse[1] != null) { String splitBrightness[] = splitResponse[1].split(":"); if (splitBrightness[0] != null) { int newBrightnessValue = Integer.valueOf(splitBrightness[0]); int newBrightness = Math.round(newBrightnessValue * 100 / 255); logger.trace("newBrightness = {}", newBrightness); State newBrightnessState = new PercentType(newBrightness); updateState(CHANNEL_BRIGHTNESS, newBrightnessState); currentBrightness = newBrightness; } } } } } catch (Exception e) { throw new RuntimeException("Could not retrieve new Wemo light state", e); } } @Override public void onServiceSubscribed(String service, boolean succeeded) { } @Override public void onValueReceived(String variable, String value, String service) { logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'", new Object[] { variable, value, service, this.getThing().getUID() }); String capabilityId = StringUtils.substringBetween(value, "<CapabilityId>", "</CapabilityId>"); String newValue = StringUtils.substringBetween(value, "<Value>", "</Value>"); switch (capabilityId) { case "10006": OnOffType binaryState = null; binaryState = newValue.equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { updateState(CHANNEL_STATE, binaryState); } break; case "10008": String splitValue[] = newValue.split(":"); if (splitValue[0] != null) { int newBrightnessValue = Integer.valueOf(splitValue[0]); int newBrightness = Math.round(newBrightnessValue * 100 / 255); State newBrightnessState = new PercentType(newBrightness); updateState(CHANNEL_BRIGHTNESS, newBrightnessState); currentBrightness = newBrightness; } break; } } @Override public void onStatusChanged(boolean status) { } private synchronized void onSubscription() { if (service.isRegistered(this)) { logger.debug("Checking WeMo GENA subscription for '{}'", this); if ((subscriptionState.get(SUBSCRIPTION) == null) || !subscriptionState.get(SUBSCRIPTION).booleanValue()) { logger.debug("Setting up GENA subscription {}: Subscribing to service {}...", getUDN(), SUBSCRIPTION); service.addSubscription(this, SUBSCRIPTION, SUBSCRIPTION_DURATION); subscriptionState.put(SUBSCRIPTION, true); } } else { logger.debug("Setting up WeMo GENA subscription for '{}' FAILED - service.isRegistered(this) is FALSE", this); } } private synchronized void removeSubscription() { if (service.isRegistered(this)) { logger.debug("Removing WeMo GENA subscription for '{}'", this); if ((subscriptionState.get(SUBSCRIPTION) != null) && subscriptionState.get(SUBSCRIPTION).booleanValue()) { logger.debug("WeMo {}: Unsubscribing from service {}...", getUDN(), SUBSCRIPTION); service.removeSubscription(this, SUBSCRIPTION); } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } } private synchronized void onUpdate() { if (refreshJob == null || refreshJob.isCancelled()) { Configuration config = getThing().getConfiguration(); int refreshInterval = DEFAULT_REFRESH_INTERVAL; Object refreshConfig = config.get("refresh"); if (refreshConfig != null) { refreshInterval = ((BigDecimal) refreshConfig).intValue(); } logger.trace("Start polling job for LightID '{}'", wemoLightID); refreshJob = scheduler.scheduleWithFixedDelay(refreshRunnable, DEFAULT_REFRESH_INITIAL_DELAY, refreshInterval, TimeUnit.SECONDS); } } private boolean isUpnpDeviceRegistered() { return service.isRegistered(this); } public String getWemoURL() { URL descriptorURL = service.getDescriptorURL(this); String wemoURL = null; if (descriptorURL != null) { String deviceURL = StringUtils.substringBefore(descriptorURL.toString(), "/setup.xml"); wemoURL = deviceURL + "/upnp/control/bridge1"; return wemoURL; } return null; } }
package org.springframework.ide.vscode.boot.java.handlers; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp; import org.springframework.ide.vscode.commons.java.IClasspath; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.languageserver.jdt.ls.Classpath; import org.springframework.ide.vscode.commons.languageserver.jdt.ls.Classpath.CPE; import org.springframework.ide.vscode.commons.util.CollectorUtil; /** * @author Martin Lippert */ public class RunningAppMatcher { public static Collection<SpringBootApp> getAllMatchingApps(Collection<SpringBootApp> apps, IJavaProject project) throws Exception { if (project != null) { Collection<SpringBootApp> matchedProjects = apps.stream().filter((app) -> { return RunningAppMatcher.doesProjectMatch(app, project); }).collect(CollectorUtil.toImmutableList()); return matchedProjects; } return apps; } private static boolean doesProjectMatch(SpringBootApp app, IJavaProject project) { if (hasProjectName(app, project)) { return doesProjectNameMatch(app, project); } return true; } public static boolean hasProjectName(SpringBootApp app, IJavaProject project) { try { String projectName = app.getSystemProperty("spring.boot.project.name"); return projectName != null && projectName.trim().length() > 0; } catch (Exception e) { return false; } } public static boolean doesProjectNameMatch(SpringBootApp app, IJavaProject project) { try { String projectName = app.getSystemProperty("spring.boot.project.name"); return projectName != null && projectName.equals(project.getElementName()); } catch (Exception e) { return false; } } public static boolean doesClasspathMatch(SpringBootApp app, IJavaProject project) { try { Set<String> runningAppClasspath = new HashSet<>(); Collections.addAll(runningAppClasspath, app.getClasspath()); return doesClasspathMatch(runningAppClasspath, project); } catch (Exception e) { return false; } } public static boolean doesClasspathMatch(Set<String> runningAppClasspath, IJavaProject project) throws Exception { IClasspath classpath = project.getClasspath(); Collection<CPE> entries = classpath.getClasspathEntries(); for (CPE cpe : entries) { if (Classpath.ENTRY_KIND_SOURCE.equals(cpe.getKind())) { String path = cpe.getOutputFolder(); if (runningAppClasspath.contains(path)) { return true; } } } return false; } public static boolean doesProjectThinJarWrapperMatch(SpringBootApp app, IJavaProject project) { // not yet implemented return false; } }
package org.innovateuk.ifs.project.spendprofile.transactional; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.commons.error.CommonFailureKeys; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.error.ValidationMessages; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.notifications.resource.Notification; import org.innovateuk.ifs.notifications.resource.NotificationTarget; import org.innovateuk.ifs.notifications.resource.SystemNotificationSource; import org.innovateuk.ifs.notifications.resource.UserNotificationTarget; import org.innovateuk.ifs.notifications.service.NotificationService; import org.innovateuk.ifs.organisation.domain.Organisation; import org.innovateuk.ifs.organisation.domain.OrganisationType; import org.innovateuk.ifs.organisation.repository.OrganisationRepository; import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum; import org.innovateuk.ifs.project.core.builder.ProjectBuilder; import org.innovateuk.ifs.project.core.domain.PartnerOrganisation; import org.innovateuk.ifs.project.core.domain.Project; import org.innovateuk.ifs.project.core.domain.ProjectUser; import org.innovateuk.ifs.project.core.repository.ProjectRepository; import org.innovateuk.ifs.project.core.transactional.PartnerOrganisationService; import org.innovateuk.ifs.project.core.util.ProjectUsersHelper; import org.innovateuk.ifs.project.finance.resource.EligibilityState; import org.innovateuk.ifs.project.finance.resource.TimeUnit; import org.innovateuk.ifs.project.finance.resource.ViabilityState; import org.innovateuk.ifs.project.financechecks.domain.*; import org.innovateuk.ifs.project.financechecks.repository.CostCategoryRepository; import org.innovateuk.ifs.project.financechecks.repository.CostCategoryTypeRepository; import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.EligibilityWorkflowHandler; import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.ViabilityWorkflowHandler; import org.innovateuk.ifs.project.grantofferletter.transactional.GrantOfferLetterService; import org.innovateuk.ifs.project.resource.ApprovalType; import org.innovateuk.ifs.project.resource.PartnerOrganisationResource; import org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId; import org.innovateuk.ifs.project.spendprofile.configuration.workflow.SpendProfileWorkflowHandler; import org.innovateuk.ifs.project.spendprofile.domain.SpendProfile; import org.innovateuk.ifs.project.spendprofile.domain.SpendProfileNotifications; import org.innovateuk.ifs.project.spendprofile.repository.SpendProfileRepository; import org.innovateuk.ifs.project.spendprofile.resource.SpendProfileCSVResource; import org.innovateuk.ifs.project.spendprofile.resource.SpendProfileTableResource; import org.innovateuk.ifs.project.spendprofile.validator.SpendProfileValidationUtil; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.repository.UserRepository; import org.innovateuk.ifs.user.resource.UserResource; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.springframework.test.util.ReflectionTestUtils; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.*; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.finance.resource.cost.FinanceRowType.*; import static org.innovateuk.ifs.notifications.resource.NotificationMedium.EMAIL; import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation; import static org.innovateuk.ifs.organisation.builder.OrganisationTypeBuilder.newOrganisationType; import static org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum.BUSINESS; import static org.innovateuk.ifs.project.builder.PartnerOrganisationResourceBuilder.newPartnerOrganisationResource; import static org.innovateuk.ifs.project.core.builder.PartnerOrganisationBuilder.newPartnerOrganisation; import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser; import static org.innovateuk.ifs.project.finance.resource.TimeUnit.MONTH; import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryBuilder.newCostCategory; import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryGroupBuilder.newCostCategoryGroup; import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryTypeBuilder.newCostCategoryType; import static org.innovateuk.ifs.project.spendprofile.builder.SpendProfileBuilder.newSpendProfile; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class SpendProfileServiceImplTest extends BaseServiceUnitTest<SpendProfileServiceImpl> { private static final String webBaseUrl = "https://ifs-local-dev/dashboard"; private Long projectId = 123L; private Long organisationId = 456L; @Mock private SpendProfileCostCategorySummaryStrategy spendProfileCostCategorySummaryStrategy; @Mock private NotificationService notificationServiceMock; @Mock private SpendProfileValidationUtil validationUtil; @Mock private Error mockedError; @Mock private ViabilityWorkflowHandler viabilityWorkflowHandlerMock; @Mock private EligibilityWorkflowHandler eligibilityWorkflowHandlerMock; @Mock private SpendProfileWorkflowHandler spendProfileWorkflowHandlerMock; @Mock private SpendProfileRepository spendProfileRepositoryMock; @Mock private ProjectUsersHelper projectUsersHelperMock; /* @Mock private ProjectService projectServiceMock;*/ @Mock private PartnerOrganisationService partnerOrganisationServiceMock; @Mock private ProjectRepository projectRepositoryMock; @Mock private OrganisationRepository organisationRepositoryMock; @Mock private CostCategoryRepository costCategoryRepositoryMock; @Mock private CostCategoryTypeRepository costCategoryTypeRepositoryMock; @Mock private UserRepository userRepositoryMock; @Mock private GrantOfferLetterService grantOfferLetterServiceMock; @Mock private SystemNotificationSource systemNotificationSource; @Test public void generateSpendProfile() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); CostCategoryType costCategoryType1 = generateSpendProfileData.getCostCategoryType1(); CostCategoryType costCategoryType2 = generateSpendProfileData.getCostCategoryType2(); CostCategory type1Cat1 = generateSpendProfileData.type1Cat1; CostCategory type1Cat2 = generateSpendProfileData.type1Cat2; CostCategory type2Cat1 = generateSpendProfileData.type2Cat1; setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandlerMock.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandlerMock.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); User generatedBy = generateSpendProfileData.getUser(); List<Cost> expectedOrganisation1EligibleCosts = asList( new Cost("100").withCategory(type1Cat1), new Cost("200").withCategory(type1Cat2)); List<Cost> expectedOrganisation1SpendProfileFigures = asList( new Cost("34").withCategory(type1Cat1).withTimePeriod(0, MONTH, 1, MONTH), new Cost("33").withCategory(type1Cat1).withTimePeriod(1, MONTH, 1, MONTH), new Cost("33").withCategory(type1Cat1).withTimePeriod(2, MONTH, 1, MONTH), new Cost("68").withCategory(type1Cat2).withTimePeriod(0, MONTH, 1, MONTH), new Cost("66").withCategory(type1Cat2).withTimePeriod(1, MONTH, 1, MONTH), new Cost("66").withCategory(type1Cat2).withTimePeriod(2, MONTH, 1, MONTH)); Calendar generatedDate = Calendar.getInstance(); SpendProfile expectedOrganisation1Profile = new SpendProfile(organisation1, project, costCategoryType1, expectedOrganisation1EligibleCosts, expectedOrganisation1SpendProfileFigures, generatedBy, generatedDate, false); List<Cost> expectedOrganisation2EligibleCosts = singletonList( new Cost("301").withCategory(type2Cat1)); List<Cost> expectedOrganisation2SpendProfileFigures = asList( new Cost("101").withCategory(type2Cat1).withTimePeriod(0, MONTH, 1, MONTH), new Cost("100").withCategory(type2Cat1).withTimePeriod(1, MONTH, 1, MONTH), new Cost("100").withCategory(type2Cat1).withTimePeriod(2, MONTH, 1, MONTH)); SpendProfile expectedOrganisation2Profile = new SpendProfile(organisation2, project, costCategoryType2, expectedOrganisation2EligibleCosts, expectedOrganisation2SpendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepositoryMock.save(spendProfileExpectations(expectedOrganisation1Profile))).thenReturn(null); when(spendProfileRepositoryMock.save(spendProfileExpectations(expectedOrganisation2Profile))).thenReturn(null); User financeContactUser1 = newUser().withEmailAddress("z@abc.com").withFirstName("A").withLastName("Z").build(); ProjectUser financeContact1 = newProjectUser().withUser(financeContactUser1).build(); User financeContactUser2 = newUser().withEmailAddress("a@abc.com").withFirstName("A").withLastName("A").build(); ProjectUser financeContact2 = newProjectUser().withUser(financeContactUser2).build(); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.of(financeContact1)); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); Map<String, Object> expectedNotificationArguments = asMap( "dashboardUrl", "https://ifs-local-dev/dashboard", "applicationId", project.getApplication().getId(), "competitionName", "Competition 1" ); NotificationTarget to1 = new UserNotificationTarget("A Z", "z@abc.com"); NotificationTarget to2 = new UserNotificationTarget("A A", "a@abc.com"); Notification notification1 = new Notification(systemNotificationSource, to1, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); Notification notification2 = new Notification(systemNotificationSource, to2, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); when(notificationServiceMock.sendNotificationWithFlush(notification1, EMAIL)).thenReturn(serviceSuccess()); when(notificationServiceMock.sendNotificationWithFlush(notification2, EMAIL)).thenReturn(serviceSuccess()); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isSuccess()); verify(spendProfileRepositoryMock).save(spendProfileExpectations(expectedOrganisation1Profile)); verify(spendProfileRepositoryMock).save(spendProfileExpectations(expectedOrganisation2Profile)); verify(notificationServiceMock).sendNotificationWithFlush(notification1, EMAIL); verify(notificationServiceMock).sendNotificationWithFlush(notification2, EMAIL); } @Test public void generateSpendProfileButNotAllViabilityApproved() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.REVIEW); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_VIABILITY_APPROVED)); verify(spendProfileRepositoryMock, never()).save(isA(SpendProfile.class)); verifyNoMoreInteractions(spendProfileRepositoryMock); } @Test public void generateSpendProfileWhenNotAllEligibilityApproved() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.REVIEW); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_ELIGIBILITY_APPROVED)); verify(spendProfileRepositoryMock, never()).save(isA(SpendProfile.class)); verifyNoMoreInteractions(spendProfileRepositoryMock); } @Test public void generateSpendProfileWhenSpendProfileAlreadyGenerated() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandlerMock.isAlreadyGenerated(project)).thenReturn(true); SpendProfile spendProfileForOrganisation1 = new SpendProfile(); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.of(spendProfileForOrganisation1)); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_HAS_ALREADY_BEEN_GENERATED)); verify(spendProfileRepositoryMock, never()).save(isA(SpendProfile.class)); } @Test public void generateSpendProfileWhenSendingEmailFails() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandlerMock.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandlerMock.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); User financeContactUser1 = newUser().withEmailAddress("z@abc.com").withFirstName("A").withLastName("Z").build(); ProjectUser financeContact1 = newProjectUser().withUser(financeContactUser1).build(); User financeContactUser2 = newUser().withEmailAddress("a@abc.com").withFirstName("A").withLastName("A").build(); ProjectUser financeContact2 = newProjectUser().withUser(financeContactUser2).build(); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.of(financeContact1)); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); Map<String, Object> expectedNotificationArguments = asMap( "dashboardUrl", "https://ifs-local-dev/dashboard", "competitionName", "Competition 1", "applicationId", project.getApplication().getId() ); NotificationTarget to1 = new UserNotificationTarget("A Z", "z@abc.com"); NotificationTarget to2 = new UserNotificationTarget("A A", "a@abc.com"); Notification notification1 = new Notification(systemNotificationSource, to1, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); Notification notification2 = new Notification(systemNotificationSource, to2, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); when(notificationServiceMock.sendNotificationWithFlush(notification1, EMAIL)).thenReturn(serviceSuccess()); when(notificationServiceMock.sendNotificationWithFlush(notification2, EMAIL)).thenReturn(serviceFailure(CommonFailureKeys.NOTIFICATIONS_UNABLE_TO_SEND_SINGLE)); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.NOTIFICATIONS_UNABLE_TO_SEND_SINGLE)); verify(spendProfileRepositoryMock, times(2)).save(isA(SpendProfile.class)); verify(notificationServiceMock).sendNotificationWithFlush(notification1, EMAIL); verify(notificationServiceMock).sendNotificationWithFlush(notification2, EMAIL); } @Test public void generateSpendProfileSendEmailFailsDueToNoFinanceContact() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandlerMock.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandlerMock.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); ProjectUser financeContact2 = newProjectUser().withUser((User[]) null).build(); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.SPEND_PROFILE_FINANCE_CONTACT_NOT_PRESENT, CommonFailureKeys.SPEND_PROFILE_FINANCE_CONTACT_NOT_PRESENT)); verify(spendProfileRepositoryMock, times(2)).save(isA(SpendProfile.class)); } @Test public void generateSpendProfileNotReadyToGenerate() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandlerMock.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandlerMock.isAlreadyGenerated(project)).thenReturn(true); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.SPEND_PROFILE_HAS_ALREADY_BEEN_GENERATED)); } private void setupGenerateSpendProfilesExpectations(GenerateSpendProfileData generateSpendProfileData, Project project, Organisation organisation1, Organisation organisation2) { CostCategoryType costCategoryType1 = generateSpendProfileData.getCostCategoryType1(); CostCategoryType costCategoryType2 = generateSpendProfileData.getCostCategoryType2(); CostCategory type1Cat1 = generateSpendProfileData.type1Cat1; CostCategory type1Cat2 = generateSpendProfileData.type1Cat2; CostCategory type2Cat1 = generateSpendProfileData.type2Cat1; // setup expectations for getting project users to infer the partner organisations /* List<ProjectUserResource> projectUsers = newProjectUserResource().withOrganisation(organisation1.getId(), organisation2.getId()).build(2);*/ List<PartnerOrganisationResource> partnerOrganisationResources = newPartnerOrganisationResource().withOrganisation(organisation1.getId(), organisation2.getId()).build(2); //when(projectServiceMock.getProjectUsers(projectId)).thenReturn(serviceSuccess(projectUsers)); when(partnerOrganisationServiceMock.getProjectPartnerOrganisations(projectId)).thenReturn(serviceSuccess(partnerOrganisationResources)); // setup expectations for finding finance figures per Cost Category from which to generate the spend profile when(spendProfileCostCategorySummaryStrategy.getCostCategorySummaries(project.getId(), organisation1.getId())).thenReturn(serviceSuccess( new SpendProfileCostCategorySummaries( asList( new SpendProfileCostCategorySummary(type1Cat1, new BigDecimal("100.00"), project.getDurationInMonths()), new SpendProfileCostCategorySummary(type1Cat2, new BigDecimal("200.00"), project.getDurationInMonths())), costCategoryType1))); when(spendProfileCostCategorySummaryStrategy.getCostCategorySummaries(project.getId(), organisation2.getId())).thenReturn(serviceSuccess( new SpendProfileCostCategorySummaries( singletonList(new SpendProfileCostCategorySummary(type2Cat1, new BigDecimal("300.66"), project.getDurationInMonths())), costCategoryType2))); } @Test public void generateSpendProfileForPartnerOrganisation() { Competition competition = newCompetition() .withName("Competition 1") .build(); Application application = newApplication() .withName("Application 1") .withCompetition(competition) .build(); Project project = newProject() .withId(projectId) .withDuration(3L) .withPartnerOrganisations(newPartnerOrganisation() .build(2)) .withApplication(application) .build(); Organisation organisation1 = newOrganisation().build(); CostCategory costCategoryLabour = newCostCategory().withName(LABOUR.getName()).build(); CostCategory costCategoryMaterials = newCostCategory().withName(MATERIALS.getName()).build(); CostCategoryType costCategoryType1 = newCostCategoryType() .withName("Type 1") .withCostCategoryGroup( newCostCategoryGroup() .withDescription("Group 1") .withCostCategories(asList(costCategoryLabour, costCategoryMaterials)) .build()) .build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(costCategoryRepositoryMock.findOne(costCategoryLabour.getId())).thenReturn(costCategoryLabour); when(costCategoryRepositoryMock.findOne(costCategoryMaterials.getId())).thenReturn(costCategoryMaterials); when(costCategoryTypeRepositoryMock.findOne(costCategoryType1.getId())).thenReturn(costCategoryType1); when(spendProfileCostCategorySummaryStrategy.getCostCategorySummaries(project.getId(), organisation1.getId())).thenReturn(serviceSuccess( new SpendProfileCostCategorySummaries( asList( new SpendProfileCostCategorySummary(costCategoryLabour, new BigDecimal("100.00"), project.getDurationInMonths()), new SpendProfileCostCategorySummary(costCategoryMaterials, new BigDecimal("200.00"), project.getDurationInMonths())), costCategoryType1))); List<Cost> expectedOrganisation1EligibleCosts = asList( new Cost("100").withCategory(costCategoryLabour), new Cost("200").withCategory(costCategoryMaterials)); List<Cost> expectedOrganisation1SpendProfileFigures = asList( new Cost("34").withCategory(costCategoryLabour).withTimePeriod(0, MONTH, 1, MONTH), new Cost("33").withCategory(costCategoryLabour).withTimePeriod(1, MONTH, 1, MONTH), new Cost("33").withCategory(costCategoryLabour).withTimePeriod(2, MONTH, 1, MONTH), new Cost("68").withCategory(costCategoryMaterials).withTimePeriod(0, MONTH, 1, MONTH), new Cost("66").withCategory(costCategoryMaterials).withTimePeriod(1, MONTH, 1, MONTH), new Cost("66").withCategory(costCategoryMaterials).withTimePeriod(2, MONTH, 1, MONTH)); Long userId = 7L; User generatedBy = newUser().build(); when(userRepositoryMock.findOne(userId)).thenReturn(generatedBy); Calendar generatedDate = Calendar.getInstance(); SpendProfile expectedOrganisation1Profile = new SpendProfile(organisation1, project, costCategoryType1, expectedOrganisation1EligibleCosts, expectedOrganisation1SpendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepositoryMock.save(spendProfileExpectations(expectedOrganisation1Profile))).thenReturn(null); User financeContactUser1 = newUser().withEmailAddress("z@abc.com").withFirstName("A").withLastName("Z").build(); ProjectUser financeContact1 = newProjectUser().withUser(financeContactUser1).build(); when(projectUsersHelperMock.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.of(financeContact1)); Map<String, Object> expectedNotificationArguments = asMap( "dashboardUrl", "https://ifs-local-dev/dashboard", "applicationId", project.getApplication().getId(), "competitionName", "Competition 1" ); NotificationTarget to1 = new UserNotificationTarget("A Z", "z@abc.com"); Notification notification1 = new Notification(systemNotificationSource, to1, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); when(notificationServiceMock.sendNotificationWithFlush(notification1, EMAIL)).thenReturn(serviceSuccess()); ServiceResult<Void> generateResult = service.generateSpendProfileForPartnerOrganisation(projectId, organisation1.getId(), userId); assertTrue(generateResult.isSuccess()); verify(spendProfileRepositoryMock).save(spendProfileExpectations(expectedOrganisation1Profile)); verify(notificationServiceMock).sendNotificationWithFlush(notification1, EMAIL); verifyNoMoreInteractions(spendProfileRepositoryMock); } @Test public void generateSpendProfileCSV() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfile spendProfileInDB = createSpendProfile(project, // eligible costs asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), // Spend Profile costs asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); CostCategory testCostCategory = new CostCategory(); testCostCategory.setId(1L); testCostCategory.setName("One"); testCostCategory.setLabel("Group Name"); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(costCategoryRepositoryMock.findOne(anyLong())).thenReturn(testCostCategory); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ServiceResult<SpendProfileCSVResource> serviceResult = service.getSpendProfileCSV(projectOrganisationCompositeId); assertTrue(serviceResult.getSuccess().getFileName().startsWith("TEST_Spend_Profile_" + dateFormat.format(date))); assertTrue(serviceResult.getSuccess().getCsvData().contains("Group Name")); assertEquals(Arrays.asList(serviceResult.getSuccess().getCsvData().split("\n")).stream().filter(s -> s.contains("Group Name") && !s.contains("Month") && !s.contains("TOTAL")).count(), 3); } @Test public void generateSpendProfileCSVWithCategoryGroupLabelEmpty() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfile spendProfileInDB = createSpendProfile(project, // eligible costs asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), // Spend Profile costs asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); CostCategory testCostCategory = new CostCategory(); testCostCategory.setId(1L); testCostCategory.setName("One"); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(costCategoryRepositoryMock.findOne(anyLong())).thenReturn(testCostCategory); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ServiceResult<SpendProfileCSVResource> serviceResult = service.getSpendProfileCSV(projectOrganisationCompositeId); assertTrue(serviceResult.getSuccess().getFileName().startsWith("TEST_Spend_Profile_" + dateFormat.format(date))); assertFalse(serviceResult.getSuccess().getCsvData().contains("Group Name")); assertEquals(Arrays.asList(serviceResult.getSuccess().getCsvData().split("\n")).stream().filter(s -> s.contains("Group Name") && !s.contains("Month") && !s.contains("TOTAL")).count(), 0); } @Test public void getSpendProfileStatusByProjectIdApproved() { Project project = newProject().build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.getApproval(project)).thenReturn(ApprovalType.APPROVED); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.APPROVED, result.getSuccess()); } @Test public void getSpendProfileStatusByProjectIdRejected() { Project project = newProject().build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.getApproval(project)).thenReturn(ApprovalType.REJECTED); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.REJECTED, result.getSuccess()); } @Test public void getSpendProfileStatusByProjectIdUnset() { List<SpendProfile> spendProfileList = newSpendProfile().build(3); when(spendProfileRepositoryMock.findByProjectId(projectId)).thenReturn(spendProfileList); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.UNSET, result.getSuccess()); } @Test public void approveSpendProfile() { List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(true); when(grantOfferLetterServiceMock.generateGrantOfferLetterIfReady(projectId)).thenReturn(serviceSuccess()); Long userId = 1234L; User user = newUser().withId(userId).build(); UserResource loggedInUser = newUserResource().withId(user.getId()).build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findOne(userId)).thenReturn(user); when(spendProfileWorkflowHandlerMock.spendProfileApproved(project, user)).thenReturn(true); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertTrue(result.isSuccess()); ; verify(spendProfileRepositoryMock).save(spendProfileList); verify(grantOfferLetterServiceMock).generateGrantOfferLetterIfReady(projectId); verify(spendProfileWorkflowHandlerMock).spendProfileApproved(project, user); } @Test public void rejectSpendProfile() { Long projectId = 4234L; List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(true); when(grantOfferLetterServiceMock.generateGrantOfferLetterIfReady(projectId)).thenReturn(serviceSuccess()); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findOne(userId)).thenReturn(user); when(spendProfileWorkflowHandlerMock.spendProfileRejected(project, user)).thenReturn(true); ServiceResult<Void> resultNew = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertTrue(resultNew.isSuccess()); assertTrue(project.getSpendProfileSubmittedDate() == null); verify(spendProfileRepositoryMock).save(spendProfileList); verify(spendProfileWorkflowHandlerMock).spendProfileRejected(project, user); } @Test public void approveSpendProfileProcessNotApproved() { List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(true); when(grantOfferLetterServiceMock.generateGrantOfferLetterIfReady(projectId)).thenReturn(serviceSuccess()); Long userId = 1234L; User user = newUser().withId(userId).build(); UserResource loggedInUser = newUserResource().withId(user.getId()).build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findOne(userId)).thenReturn(user); when(spendProfileWorkflowHandlerMock.spendProfileApproved(project, user)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_CANNOT_BE_APPROVED.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(spendProfileRepositoryMock).save(spendProfileList); verify(spendProfileWorkflowHandlerMock).spendProfileApproved(project,user); } @Test public void rejectSpendProfileNotReadyToApprove() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } @Test public void approveSpendProfileInvalidApprovalType() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(true); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.UNSET); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } @Test public void approveSpendProfileNotReadyToApprove() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } @Test public void rejectSpendProfileFails() { Long projectId = 4234L; Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(spendProfileWorkflowHandlerMock.isReadyToApprove(project)).thenReturn(true); when(grantOfferLetterServiceMock.generateGrantOfferLetterIfReady(projectId)).thenReturn(serviceSuccess()); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findOne(userId)).thenReturn(user); when(spendProfileWorkflowHandlerMock.spendProfileRejected(project, user)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_CANNOT_BE_REJECTED.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } @Test public void approveSpendProfileNoProject() { when(projectRepositoryMock.findOne(projectId)).thenReturn(null); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } @Test public void saveSpendProfileWhenValidationFails() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfileTableResource table = new SpendProfileTableResource(); // the validation is tested in the validator related unit tests table.setMonthlyCostsPerCategoryMap(Collections.emptyMap()); ValidationMessages validationMessages = new ValidationMessages(); validationMessages.setErrors(Collections.singletonList(mockedError)); when(validationUtil.validateSpendProfileTableResource(eq(table))).thenReturn(Optional.of(validationMessages)); ServiceResult<Void> result = service.saveSpendProfile(projectOrganisationCompositeId, table); assertFalse(result.isSuccess()); } @Test public void saveSpendProfileEnsureSpendProfileDomainIsCorrectlyUpdated() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfileTableResource table = new SpendProfileTableResource(); table.setEligibleCostPerCategoryMap(asMap( 173L, new BigDecimal("100"), 174L, new BigDecimal("180"), 175L, new BigDecimal("55"))); table.setMonthlyCostsPerCategoryMap(asMap( 173L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("40")), 174L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 175L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0")))); List<Cost> spendProfileFigures = buildCostsForCategories(Arrays.asList(173L, 174L, 175L), 3); User generatedBy = newUser().build(); Calendar generatedDate = Calendar.getInstance(); SpendProfile spendProfileInDB = new SpendProfile(null, newProject().build(), null, Collections.emptyList(), spendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(validationUtil.validateSpendProfileTableResource(eq(table))).thenReturn(Optional.empty()); // Before the call (ie before the SpendProfile is updated), ensure that the values are set to 1 assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 2, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 2, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 2, BigDecimal.ONE); ServiceResult<Void> result = service.saveSpendProfile(projectOrganisationCompositeId, table); assertTrue(result.isSuccess()); // Assert that the SpendProfile domain is correctly updated assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 0, new BigDecimal("30")); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 1, new BigDecimal("30")); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 2, new BigDecimal("40")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 0, new BigDecimal("70")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 1, new BigDecimal("50")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 2, new BigDecimal("60")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 0, new BigDecimal("50")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 1, new BigDecimal("5")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 2, new BigDecimal("0")); verify(spendProfileRepositoryMock).save(spendProfileInDB); } @Test public void markSpendProfileIncomplete() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withId(projectId) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, // eligible costs asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), // Spend Profile costs asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); spendProfileInDB.setMarkedAsComplete(true); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDB); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileIncomplete(projectOrganisationCompositeId); assertTrue(result.isSuccess()); assertFalse(spendProfileInDB.isMarkedAsComplete()); } @Test public void markSpendProfileWhenActualTotalsGreaterThanEligibleCosts() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, // eligible costs asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), // Spend Profile costs asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDB); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileComplete(projectOrganisationCompositeId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE)); } @Test public void markSpendProfileSuccessWhenActualTotalsAreLessThanEligibleCosts() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, // eligible costs asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), // Spend Profile costs asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("10"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDB); when(spendProfileRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileComplete(projectOrganisationCompositeId); assertTrue(result.isSuccess()); } @Test public void completeSpendProfilesReviewSuccess() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(null); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(true); projectInDb.setSpendProfiles(asList(spendProfileInDb)); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDb); assertThat(projectInDb.getSpendProfileSubmittedDate(), nullValue()); when(spendProfileWorkflowHandlerMock.submit(projectInDb)).thenReturn(true); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isSuccess()); assertThat(projectInDb.getSpendProfileSubmittedDate(), notNullValue()); } @Test public void completeSpendProfilesReviewFailureWhenSpendProfileIncomplete() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(null); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(false); projectInDb.setSpendProfiles(asList(spendProfileInDb)); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDb); assertThat(projectInDb.getSpendProfileSubmittedDate(), nullValue()); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isFailure()); } @Test public void completeSpendProfilesReviewFailureWhenAlreadySubmitted() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(ZonedDateTime.now()); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(true); projectInDb.setSpendProfiles(asList(spendProfileInDb)); when(projectRepositoryMock.findOne(projectId)).thenReturn(projectInDb); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isFailure()); } private SpendProfile createSpendProfile(Project projectInDB, Map<Long, BigDecimal> eligibleCostsMap, Map<Long, List<BigDecimal>> spendProfileCostsMap) { CostCategoryType costCategoryType = createCostCategoryType(); List<Cost> eligibleCosts = buildEligibleCostsForCategories(eligibleCostsMap, costCategoryType.getCostCategoryGroup()); List<Cost> spendProfileFigures = buildCostsForCategoriesWithGivenValues(spendProfileCostsMap, 3, costCategoryType.getCostCategoryGroup()); User generatedBy = newUser().build(); Calendar generatedDate = Calendar.getInstance(); SpendProfile spendProfileInDB = new SpendProfile(null, projectInDB, costCategoryType, eligibleCosts, spendProfileFigures, generatedBy, generatedDate, true); return spendProfileInDB; } private CostCategoryType createCostCategoryType() { CostCategoryGroup costCategoryGroup = createCostCategoryGroup(); CostCategoryType costCategoryType = new CostCategoryType("Cost Category Type for Categories Labour, Materials, Other costs", costCategoryGroup); return costCategoryType; } private CostCategoryGroup createCostCategoryGroup() { List<CostCategory> costCategories = createCostCategories(Arrays.asList(1L, 2L, 3L)); CostCategoryGroup costCategoryGroup = new CostCategoryGroup("Cost Category Group for Categories Labour, Materials, Other costs", costCategories); return costCategoryGroup; } private List<CostCategory> createCostCategories(List<Long> categories) { List<CostCategory> costCategories = new ArrayList<>(); categories.stream().forEach(category -> { CostCategory costCategory = new CostCategory(); costCategory.setId(category); costCategories.add(costCategory); }); return costCategories; } private List<Cost> buildEligibleCostsForCategories(Map<Long, BigDecimal> categoryCost, CostCategoryGroup costCategoryGroup) { List<Cost> eligibleCostForAllCategories = new ArrayList<>(); categoryCost.forEach((category, value) -> { eligibleCostForAllCategories.add(createEligibleCost(category, value, costCategoryGroup)); }); return eligibleCostForAllCategories; } private Cost createEligibleCost(Long categoryId, BigDecimal value, CostCategoryGroup costCategoryGroup) { CostCategory costCategory = new CostCategory(); costCategory.setId(categoryId); costCategory.setCostCategoryGroup(costCategoryGroup); Cost cost = new Cost(); cost.setCostCategory(costCategory); cost.setValue(value); return cost; } private void assertCostForCategoryForGivenMonth(SpendProfile spendProfileInDB, Long category, Integer whichMonth, BigDecimal expectedValue) { boolean thisCostShouldExist = spendProfileInDB.getSpendProfileFigures().getCosts().stream() .anyMatch(cost -> Objects.equals(cost.getCostCategory().getId(), category) && cost.getCostTimePeriod().getOffsetAmount().equals(whichMonth) && cost.getValue().equals(expectedValue)); Assert.assertTrue(thisCostShouldExist); } private List<Cost> buildCostsForCategories(List<Long> categories, int totalMonths) { List<Cost> costForAllCategories = new ArrayList<>(); categories.forEach(category -> { // Intentionally insert in the reverse order of months to ensure that the sorting functionality actually works for (int index = totalMonths - 1; index >= 0; index costForAllCategories.add(createCost(category, index, BigDecimal.ONE, null)); } }); return costForAllCategories; } private List<Cost> buildCostsForCategoriesWithGivenValues(Map<Long, List<BigDecimal>> categoryCosts, int totalMonths, CostCategoryGroup costCategoryGroup) { List<Cost> costForAllCategories = new ArrayList<>(); categoryCosts.forEach((category, costs) -> { for (int index = 0; index < totalMonths; index++) { costForAllCategories.add(createCost(category, index, costs.get(index), costCategoryGroup)); } }); return costForAllCategories; } private Cost createCost(Long categoryId, Integer offsetAmount, BigDecimal value, CostCategoryGroup costCategoryGroup) { CostCategory costCategory = new CostCategory(); costCategory.setId(categoryId); costCategory.setCostCategoryGroup(costCategoryGroup); //CostTimePeriod(Integer offsetAmount, TimeUnit offsetUnit, Integer durationAmount, TimeUnit durationUnit) CostTimePeriod costTimePeriod = new CostTimePeriod(offsetAmount, TimeUnit.MONTH, 1, TimeUnit.MONTH); Cost cost = new Cost(); cost.setCostCategory(costCategory); cost.setCostTimePeriod(costTimePeriod); cost.setValue(value); return cost; } private SpendProfile spendProfileExpectations(SpendProfile expectedSpendProfile) { return createLambdaMatcher(spendProfile -> { assertEquals(expectedSpendProfile.getOrganisation(), spendProfile.getOrganisation()); assertEquals(expectedSpendProfile.getProject(), spendProfile.getProject()); assertEquals(expectedSpendProfile.getCostCategoryType(), spendProfile.getCostCategoryType()); CostGroup expectedEligibles = expectedSpendProfile.getEligibleCosts(); CostGroup actualEligibles = spendProfile.getEligibleCosts(); assertCostGroupsEqual(expectedEligibles, actualEligibles); CostGroup expectedSpendFigures = expectedSpendProfile.getSpendProfileFigures(); CostGroup actualSpendFigures = spendProfile.getSpendProfileFigures(); assertCostGroupsEqual(expectedSpendFigures, actualSpendFigures); assertEquals(expectedSpendProfile.getGeneratedBy(), spendProfile.getGeneratedBy()); assertTrue(spendProfile.getGeneratedDate().getTimeInMillis() - expectedSpendProfile.getGeneratedDate().getTimeInMillis() < 100); }); } private void assertCostGroupsEqual(CostGroup expected, CostGroup actual) { assertEquals(expected.getDescription(), actual.getDescription()); assertEquals(expected.getCosts().size(), actual.getCosts().size()); expected.getCosts().forEach(expectedCost -> assertTrue(simpleFindFirst(actual.getCosts(), actualCost -> costsMatch(expectedCost, actualCost)).isPresent()) ); } private boolean costsMatch(Cost expectedCost, Cost actualCost) { try { CostGroup expectedCostGroup = expectedCost.getCostGroup(); CostGroup actualCostGroup = actualCost.getCostGroup(); assertEquals(expectedCostGroup != null, actualCostGroup != null); if (expectedCostGroup != null) { assertEquals(expectedCostGroup.getDescription(), actualCostGroup.getDescription()); } assertEquals(expectedCost.getValue(), actualCost.getValue()); assertEquals(expectedCost.getCostCategory(), actualCost.getCostCategory()); CostTimePeriod expectedTimePeriod = expectedCost.getCostTimePeriod(); CostTimePeriod actualTimePeriod = actualCost.getCostTimePeriod(); assertEquals(expectedTimePeriod != null, actualTimePeriod != null); if (expectedTimePeriod != null) { assertEquals(expectedTimePeriod.getOffsetAmount(), actualTimePeriod.getOffsetAmount()); assertEquals(expectedTimePeriod.getOffsetUnit(), actualTimePeriod.getOffsetUnit()); assertEquals(expectedTimePeriod.getDurationAmount(), actualTimePeriod.getDurationAmount()); assertEquals(expectedTimePeriod.getDurationUnit(), actualTimePeriod.getDurationUnit()); } return true; } catch (AssertionError e) { return false; } } private List<SpendProfile> getSpendProfilesAndSetWhenSpendProfileRepositoryMock(Long projectId) { List<SpendProfile> spendProfileList = newSpendProfile().build(2); when(spendProfileRepositoryMock.findByProjectId(projectId)).thenReturn(spendProfileList); return spendProfileList; } @Override protected SpendProfileServiceImpl supplyServiceUnderTest() { SpendProfileServiceImpl spendProfileService = new SpendProfileServiceImpl(); ReflectionTestUtils.setField(spendProfileService, "webBaseUrl", webBaseUrl); return spendProfileService; } private class GenerateSpendProfileData { private Project project; private Organisation organisation1; private Organisation organisation2; private CostCategoryType costCategoryType1; private CostCategoryType costCategoryType2; private CostCategory type1Cat1; private CostCategory type1Cat2; private CostCategory type2Cat1; private User user; public Project getProject() { return project; } public Organisation getOrganisation1() { return organisation1; } public Organisation getOrganisation2() { return organisation2; } public CostCategoryType getCostCategoryType1() { return costCategoryType1; } public CostCategoryType getCostCategoryType2() { return costCategoryType2; } public User getUser() { return user; } public GenerateSpendProfileData build() { UserResource loggedInUser = newUserResource().build(); user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findOne(loggedInUser.getId())).thenReturn(user); organisation1 = newOrganisation().withOrganisationType(BUSINESS).build(); organisation2 = newOrganisation().withOrganisationType(OrganisationTypeEnum.RTO).build(); PartnerOrganisation partnerOrganisation1 = newPartnerOrganisation().withOrganisation(organisation1).build(); PartnerOrganisation partnerOrganisation2 = newPartnerOrganisation().withOrganisation(organisation2).build(); Competition competition = newCompetition() .withName("Competition 1") .build(); Application application = newApplication() .withName("Application 1") .withCompetition(competition) .build(); project = newProject(). withId(projectId). withDuration(3L). withPartnerOrganisations(asList(partnerOrganisation1, partnerOrganisation2)). withApplication(application). build(); // First cost category type and everything that goes with it. type1Cat1 = newCostCategory().withName(LABOUR.getName()).build(); type1Cat2 = newCostCategory().withName(MATERIALS.getName()).build(); costCategoryType1 = newCostCategoryType() .withName("Type 1") .withCostCategoryGroup( newCostCategoryGroup() .withDescription("Group 1") .withCostCategories(asList(type1Cat1, type1Cat2)) .build()) .build(); // Second cost category type and everything that goes with it. type2Cat1 = newCostCategory().withName(ACADEMIC.getName()).build(); costCategoryType2 = newCostCategoryType() .withName("Type 2") .withCostCategoryGroup( newCostCategoryGroup() .withDescription("Group 2") .withCostCategories(asList(type2Cat1)) .build()) .build(); // set basic repository lookup expectations when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(organisationRepositoryMock.findOne(organisation1.getId())).thenReturn(organisation1); when(organisationRepositoryMock.findOne(organisation2.getId())).thenReturn(organisation2); when(costCategoryRepositoryMock.findOne(type1Cat1.getId())).thenReturn(type1Cat1); when(costCategoryRepositoryMock.findOne(type1Cat2.getId())).thenReturn(type1Cat2); when(costCategoryRepositoryMock.findOne(type2Cat1.getId())).thenReturn(type2Cat1); when(costCategoryTypeRepositoryMock.findOne(costCategoryType1.getId())).thenReturn(costCategoryType1); when(costCategoryTypeRepositoryMock.findOne(costCategoryType2.getId())).thenReturn(costCategoryType2); return this; } } }
package org.innovateuk.ifs.management.admin.viewmodel; import org.innovateuk.ifs.management.admin.form.InviteUserView; import org.innovateuk.ifs.user.resource.Role; import org.junit.Test; import static java.util.stream.Collectors.toSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class InviteUserViewModelTest { @Test public void InviteInternalUserViewModel() { InviteUserViewModel viewModel = new InviteUserViewModel(InviteUserView.INTERNAL_USER, Role.internalRoles(), true); assertEquals(InviteUserView.INTERNAL_USER, viewModel.getType()); assertEquals(InviteUserView.INTERNAL_USER.getName(), viewModel.getTypeName()); assertTrue(viewModel.isInternal()); assertEquals(viewModel.getRoles(), Role.internalRoles()); } @Test public void InviteExternalUserViewModel() { InviteUserViewModel viewModel = new InviteUserViewModel(InviteUserView.EXTERNAL_USER, Role.externalRolesToInvite().stream().collect(toSet()), false); assertEquals(InviteUserView.EXTERNAL_USER, viewModel.getType()); assertTrue(Role.externalRolesToInvite().stream().map(Role::getName).anyMatch(name -> name.equals(viewModel.getTypeName()))); assertTrue(viewModel.isExternal()); assertEquals(viewModel.getRoles(), Role.externalRolesToInvite().stream().collect(toSet())); } }
package org.eclipse.persistence.testing.tests.jpa.criteria.metamodel; import java.util.Set; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.Tuple; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.QueryBuilder; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.expressions.ExpressionMath; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.queries.ReadAllQuery; import org.eclipse.persistence.queries.ReadObjectQuery; import org.eclipse.persistence.queries.ReportQuery; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.sessions.UnitOfWork; import org.eclipse.persistence.sessions.server.Server; import org.eclipse.persistence.testing.models.jpa.advanced.Address; import org.eclipse.persistence.testing.models.jpa.advanced.Address_; import org.eclipse.persistence.testing.models.jpa.advanced.AdvancedTableCreator; import org.eclipse.persistence.testing.models.jpa.advanced.Employee; import org.eclipse.persistence.testing.models.jpa.advanced.EmployeePopulator; import org.eclipse.persistence.testing.models.jpa.advanced.Employee_; import org.eclipse.persistence.testing.models.jpa.advanced.LargeProject; import org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber; import org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber_; import org.eclipse.persistence.testing.models.jpa.advanced.Project; import org.eclipse.persistence.testing.models.jpa.advanced.SmallProject; import org.eclipse.persistence.testing.tests.jpa.jpql.JUnitDomainObjectComparer; import org.eclipse.persistence.testing.framework.junit.JUnitTestCase; /** * @author cdelahun * Converted from JUnitJPQLSimpleTestSuite */ public class JUnitCriteriaSimpleTestSuite extends JUnitTestCase { static JUnitDomainObjectComparer comparer; //the global comparer object used in all tests public JUnitCriteriaSimpleTestSuite() { super(); } public JUnitCriteriaSimpleTestSuite(String name) { super(name); } //This method is run at the end of EVERY test case method public void tearDown() { clearCache(); } //This suite contains all tests contained in this class public static Test suite() { TestSuite suite = new TestSuite(); suite.setName("JUnitJPQLSimpleTestSuite"); suite.addTest(new JUnitCriteriaSimpleTestSuite("testSetup")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleJoinFetchTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleJoinFetchTest2")); suite.addTest(new JUnitCriteriaSimpleTestSuite("baseTestCase")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleABSTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleBetweenTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleConcatTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleConcatTestWithParameters")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleConcatTestWithConstants1")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleCountTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleThreeArgConcatTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleDistinctTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleDistinctNullTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleDistinctMultipleResultTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleDoubleOrTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleEqualsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleEqualsTestWithJoin")); suite.addTest(new JUnitCriteriaSimpleTestSuite("collectionMemberIdentifierEqualsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("abstractSchemaIdentifierEqualsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("abstractSchemaIdentifierNotEqualsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleInOneDotTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleInTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleInListTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleLengthTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleLikeTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleLikeTestWithParameter")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleLikeEscapeTestWithParameter")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNotBetweenTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNotEqualsVariablesInteger")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNotInTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNotLikeTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleOrFollowedByAndTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleOrFollowedByAndTestWithStaticNames")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleOrTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleParameterTestChangingParameters")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseAbsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseConcatTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseEqualsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseLengthTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseSqrtTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleReverseSubstringTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleSqrtTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleSubstringTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNullTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleNotNullTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("distinctTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleModTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleIsEmptyTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleIsNotEmptyTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleEscapeUnderscoreTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleEnumTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("smallProjectMemberOfProjectsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("smallProjectNOTMemberOfProjectsTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectCountOneToOneTest")); //bug 4616218 suite.addTest(new JUnitCriteriaSimpleTestSuite("selectOneToOneTest")); //employee.address doesnt not work suite.addTest(new JUnitCriteriaSimpleTestSuite("selectPhonenumberDeclaredInINClauseTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectPhoneUsingALLTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectSimpleMemberOfWithParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectSimpleNotMemberOfWithParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectSimpleBetweenWithParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectSimpleInWithParameterTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("selectAverageQueryForByteColumnTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("multipleExecutionOfCriteriaQueryTest")); //suite.addTest(new JUnitCriteriaSimpleTestSuite("testOneEqualsOne"));//Doesn't use canonical model suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleTypeTest")); suite.addTest(new JUnitCriteriaSimpleTestSuite("simpleAsOrderByTest")); return suite; } /** * The setup is done as a test, both to record its failure, and to allow execution in the server. */ public void testSetup() { clearCache(); //get session to start setup DatabaseSession session = JUnitTestCase.getServerSession(); //create a new EmployeePopulator EmployeePopulator employeePopulator = new EmployeePopulator(); new AdvancedTableCreator().replaceTables(session); //initialize the global comparer object comparer = new JUnitDomainObjectComparer(); //set the session for the comparer to use comparer.setSession((AbstractSession)session.getActiveSession()); //Populate the tables employeePopulator.buildExamples(); //Persist the examples in the database employeePopulator.persistExample(session); } //GF Bug#404 //1. Fetch join now works with LAZY. The fix is to trigger the value holder during object registration. The test is to serialize //the results and deserialize it, then call getPhoneNumbers().size(). It used to throw an exception because the value holder //wasn't triggered and the data was in a transient attribute that was lost during serialization //2. Test both scenarios of using the cache and bypassing the cache public void simpleJoinFetchTest() throws Exception { if (isOnServer()) { // Not work on server. return; } org.eclipse.persistence.jpa.JpaEntityManager em = (org.eclipse.persistence.jpa.JpaEntityManager)createEntityManager(); simpleJoinFetchTest(em); } //bug#6130550: // tests that Fetch join works when returning objects that may already have been loaded in the em/uow (without the joined relationships) // Builds on simpleJoinFetchTest public void simpleJoinFetchTest2() throws Exception { if (isOnServer()) { // Not work on server. return; } org.eclipse.persistence.jpa.JpaEntityManager em = (org.eclipse.persistence.jpa.JpaEntityManager)createEntityManager(); //preload employees into the cache so that phonenumbers are not prefetched String ejbqlString = "SELECT e FROM Employee e"; List result = em.createQuery(ejbqlString).getResultList(); // run the simpleJoinFetchTest and verify all employees have phonenumbers fetched. simpleJoinFetchTest(em); } public void simpleJoinFetchTest(org.eclipse.persistence.jpa.JpaEntityManager em) throws Exception { //"SELECT e FROM Employee e LEFT JOIN FETCH e.phoneNumbers" //use the cache QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Root<Employee> root2 = cq.from(Employee.class); //getEntityManagerFactory().getMetamodel(); root.fetch(Employee_.phoneNumbers, JoinType.LEFT); List result = em.createQuery(cq).getResultList(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream stream = new ObjectOutputStream(byteStream); stream.writeObject(result); stream.flush(); byte arr[] = byteStream.toByteArray(); ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr); ObjectInputStream inObjStream = new ObjectInputStream(inByteStream); List deserialResult = (List)inObjStream.readObject(); for (Iterator iterator = deserialResult.iterator(); iterator.hasNext(); ) { Employee emp = (Employee)iterator.next(); emp.getPhoneNumbers().size(); } ReportQuery reportQuery = new ReportQuery(); reportQuery.setShouldReturnWithoutReportQueryResult(true); reportQuery.setReferenceClass(Employee.class); ExpressionBuilder builder = reportQuery.getExpressionBuilder(); List joins = new ArrayList(1); joins.add(builder.anyOfAllowingNone("phoneNumbers")); reportQuery.addItem("emp", builder, joins); Vector expectedResult = (Vector)em.getUnitOfWork().executeQuery(reportQuery); if (!comparer.compareObjects(result, expectedResult)) { this.fail("simpleJoinFetchTest Failed when using cache, collections do not match: " + result + " expected: " + expectedResult); } //Bypass the cache clearCache(); em.clear(); result = em.createQuery(cq).getResultList(); byteStream = new ByteArrayOutputStream(); stream = new ObjectOutputStream(byteStream); stream.writeObject(result); stream.flush(); arr = byteStream.toByteArray(); inByteStream = new ByteArrayInputStream(arr); inObjStream = new ObjectInputStream(inByteStream); deserialResult = (List)inObjStream.readObject(); for (Iterator iterator = deserialResult.iterator(); iterator.hasNext(); ) { Employee emp = (Employee)iterator.next(); emp.getPhoneNumbers().size(); } clearCache(); expectedResult = (Vector)em.getUnitOfWork().executeQuery(reportQuery); if (!comparer.compareObjects(result, expectedResult)) { this.fail("simpleJoinFetchTest Failed when not using cache, collections do not match: " + result + " expected: " + expectedResult); } } //Test case for selecting ALL employees from the database public void baseTestCase() { EntityManager em = createEntityManager(); List expectedResult = getServerSession().readAllObjects(Employee.class); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp" List result = em.createQuery(em.getQueryBuilder().createQuery(Employee.class)).getResultList(); Assert.assertTrue("Base Test Case Failed", comparer.compareObjects(result, expectedResult)); } //Test case for ABS function in EJBQL public void simpleABSTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE ABS(emp.salary) = " + expectedResult.getSalary(); QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); getEntityManagerFactory().getMetamodel().getEntities(); getEntityManagerFactory().getMetamodel().type(Employee.class).getDeclaredSingularAttribute("manager", Employee.class).getType(); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where(qb.equal( qb.abs(root.get(Employee_.salary)), expectedResult.getSalary()) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("ABS test failed", comparer.compareObjects(result, expectedResult)); } //Test case for Between function in EJBQL public void simpleBetweenTest() { BigDecimal empId = new BigDecimal(0); EntityManager em = createEntityManager(); Employee employee = (Employee)(getServerSession().readAllObjects(Employee.class).lastElement()); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("id").between(empId, employee.getId()); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id BETWEEN " + empId + "AND " + employee.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); //Cast to Expression<Comparable> since empId is BigDec and getId is Integer. between requires Comparable types; Number is not comparable cq.where( qb.between(root.get(Employee_.id).as(Comparable.class), qb.literal(empId), qb.literal(employee.getId()) ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Between test failed", comparer.compareObjects(result, expectedResult)); } //Test case for concat function in EJBQL public void simpleConcatTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); clearCache(); String partOne, partTwo; partOne = expectedResult.getFirstName().substring(0, 2); partTwo = expectedResult.getFirstName().substring(2); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = CONCAT(\"" + partOne + "\", \"" + partTwo + "\")" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.firstName), qb.concat(qb.literal(partOne), qb.literal(partTwo))) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Concat test failed", comparer.compareObjects(result, expectedResult)); } //Test case for concat function in EJBQL taking parameters public void simpleConcatTestWithParameters() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); clearCache(); String partOne = expectedResult.getFirstName().substring(0, 2); String partTwo = expectedResult.getFirstName().substring(2); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = CONCAT( :partOne, :partTwo )" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.firstName), qb.concat(qb.parameter(String.class, "partOne"), qb.parameter(String.class, "partTwo"))) ); Query query = em.createQuery(cq); query.setParameter("partOne", partOne).setParameter("partTwo", partTwo); List result = query.getResultList(); Assert.assertTrue("Concat test failed", comparer.compareObjects(result, expectedResult)); } //Test case for concat function with constants in EJBQL public void simpleConcatTestWithConstants1() { EntityManager em = createEntityManager(); Employee emp = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); String partOne = emp.getFirstName(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").concat("Smith").like(partOne + "Smith"); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE CONCAT(emp.firstName,\"Smith\") LIKE \"" + partOne + "Smith\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.like(qb.concat(root.get(Employee_.firstName), qb.literal("Smith") ), partOne+"Smith") ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Concat test with constraints failed", comparer.compareObjects(result, expectedResult)); } //Test case for concat function with constants in EJBQL public void simpleCountTest() { EntityManager em = createEntityManager(); ReportQuery query = new ReportQuery(); query.setReferenceClass(PhoneNumber.class); //need to specify Long return type query.addCount("COUNT", new ExpressionBuilder().get("owner").get("id"), Long.class); query.returnSingleAttribute(); query.dontRetrievePrimaryKeys(); query.setName("selectPhoneNumbersAssociatedToEmployees"); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"SELECT COUNT(phone.owner) FROM PhoneNumber phone"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Long> cq = qb.createQuery(Long.class); Root<PhoneNumber> root = cq.from(PhoneNumber.class); cq.select(qb.count(root.get(getEntityManagerFactory().getMetamodel().entity(PhoneNumber.class).getSingularAttribute("owner", Employee.class)) .get(getEntityManagerFactory().getMetamodel().entity(Employee.class).getSingularAttribute("id", Integer.class)))); //cq.select(qb.count(root.get(PhoneNumber_.owner).get(Employee_.id))); List result = em.createQuery(cq).getResultList(); System.out.println(" results are :"+result); qb = em.getQueryBuilder(); cq = qb.createQuery(Long.class); root = cq.from(PhoneNumber.class); cq.select(qb.count(root.get(PhoneNumber_.owner).get(Employee_.id))); result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Count test failed", expectedResult.elementAt(0).equals(result.get(0))); } public void simpleThreeArgConcatTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); clearCache(); String partOne, partTwo, partThree; partOne = expectedResult.getFirstName().substring(0, 1); partTwo = expectedResult.getFirstName().substring(1, 2); partThree = expectedResult.getFirstName().substring(2); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = CONCAT(\"" + partOne + "\", CONCAT(\"" + partTwo // + "\", \"" + partThree + "\") )" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal( root.get(Employee_.firstName), qb.concat(qb.literal(partOne), qb.concat( qb.literal(partTwo), qb.literal(partThree)) ) ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Concat test failed", comparer.compareObjects(result, expectedResult)); } public void simpleDistinctTest() { EntityManager em = createEntityManager(); //"SELECT DISTINCT e FROM Employee e JOIN FETCH e.phoneNumbers " QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.distinct(true); cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).join(Employee_.phoneNumbers); List result = em.createQuery(cq).getResultList(); Set testSet = new HashSet(); for (Iterator iterator = result.iterator(); iterator.hasNext(); ) { Employee emp = (Employee)iterator.next(); assertFalse("Result was not distinct", testSet.contains(emp)); testSet.add(emp); } } public void simpleDistinctNullTest() { EntityManager em = createEntityManager(); Employee emp = (Employee)em.createQuery("SELECT e from Employee e").getResultList().get(0); String oldFirstName = emp.getFirstName(); beginTransaction(em); try { emp = em.find(Employee.class, emp.getId()); emp.setFirstName(null); commitTransaction(em); } catch (RuntimeException ex) { if (isTransactionActive(em)) { rollbackTransaction(em); } closeEntityManager(em); throw ex; } try { //"SELECT DISTINCT e.firstName FROM Employee e WHERE e.lastName = '" + emp.getLastName() + "'" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<String> cq = qb.createQuery(String.class); cq.distinct(true); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.select(root.get(Employee_.firstName)); cq.where( qb.equal(root.get(Employee_.lastName), qb.literal(emp.getLastName()))); List result = em.createQuery(cq).getResultList(); assertTrue("Failed to return null value", result.contains(null)); } finally { try { beginTransaction(em); emp = em.find(Employee.class, emp.getId()); emp.setFirstName(oldFirstName); commitTransaction(em); } catch (RuntimeException ex) { if (isTransactionActive(em)) { rollbackTransaction(em); } closeEntityManager(em); throw ex; } } } public void simpleDistinctMultipleResultTest() { EntityManager em = createEntityManager(); //"SELECT DISTINCT e, e.firstName FROM Employee e JOIN FETCH e.phoneNumbers " QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Tuple> cq = qb.createTupleQuery(); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); root.join(Employee_.phoneNumbers); cq.distinct(true); cq.multiselect(root, root.get(Employee_.firstName)); List result = em.createQuery(cq).getResultList(); Set testSet = new HashSet(); for (Iterator iterator = result.iterator(); iterator.hasNext(); ) { String ids = ""; javax.persistence.Tuple row = (javax.persistence.Tuple)iterator.next(); Employee emp = row.get(0, Employee.class); String string = row.get(1, String.class); ids = "_" + emp.getId() + "_" + string; assertFalse("Result was not distinct", testSet.contains(ids)); testSet.add(ids); } } //Test case for double OR function in EJBQL public void simpleDoubleOrTest() { Employee emp1, emp2, emp3; EntityManager em = createEntityManager(); emp1 = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); emp2 = (Employee)(getServerSession().readAllObjects(Employee.class).elementAt(1)); emp3 = (Employee)(getServerSession().readAllObjects(Employee.class).elementAt(2)); clearCache(); Vector expectedResult = new Vector(); expectedResult.add(emp1); expectedResult.add(emp2); expectedResult.add(emp3); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id = " + emp1.getId() + "OR emp.id = " + emp2.getId() + "OR emp.id = " + emp3.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Predicate firstOr = qb.or(qb.equal(root.get(Employee_.id), emp1.getId()), qb.equal(root.get(Employee_.id), emp2.getId())); cq.where( qb.or(firstOr, qb.equal(root.get(Employee_.id), emp3.getId())) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Double OR test failed", comparer.compareObjects(result, expectedResult)); } //Test case for equals in EJBQL public void simpleEqualsTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)(getServerSession().readAllObjects(Employee.class).firstElement()); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = \"" + expectedResult.getFirstName() + "\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.firstName), expectedResult.getFirstName() ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Equals test failed", comparer.compareObjects(expectedResult, result)); } //Test case for equals with join in EJBQL public void simpleEqualsTestWithJoin() { EntityManager em = createEntityManager(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.anyOf("managedEmployees").get("address").get("city").equal("Ottawa"); Vector expectedResult = getServerSession().readAllObjects(Employee.class, whereClause); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp, IN(emp.managedEmployees) managedEmployees " + "WHERE managedEmployees.address.city = 'Ottawa'" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Join managedEmp = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).join(Employee_.managedEmployees); cq.where( qb.equal(managedEmp.get(Employee_.address).get(Address_.city), "Ottawa" ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Equals test with Join failed", comparer.compareObjects(result, expectedResult)); } public void collectionMemberIdentifierEqualsTest() { EntityManager em = createEntityManager(); ExpressionBuilder employees = new ExpressionBuilder(); Expression exp = employees.get("firstName").equal("Bob"); exp = exp.and(employees.get("lastName").equal("Smith")); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class, exp).firstElement(); clearCache(); PhoneNumber phoneNumber = (PhoneNumber)((Vector)expectedResult.getPhoneNumbers()).firstElement(); //"SELECT OBJECT(emp) FROM Employee emp, IN (emp.phoneNumbers) phone " + "WHERE phone = ?1" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Join phones = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).join(Employee_.phoneNumbers); cq.where( qb.equal(phones, qb.parameter(PhoneNumber.class, "1") ) ); List result = em.createQuery(cq).setParameter("1", phoneNumber).getResultList(); Assert.assertTrue("CollectionMemberIdentifierEqualsTest failed", comparer.compareObjects(expectedResult, result)); } public void abstractSchemaIdentifierEqualsTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).firstElement(); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp = ?1" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root, qb.parameter(Employee.class, "1") ) ); List result = em.createQuery(cq).setParameter("1", expectedResult).getResultList(); Assert.assertTrue("abstractSchemaIdentifierEqualsTest failed", comparer.compareObjects(expectedResult, result)); } public void abstractSchemaIdentifierNotEqualsTest() { EntityManager em = createEntityManager(); Vector expectedResult = getServerSession().readAllObjects(Employee.class); clearCache(); Employee emp = (Employee)expectedResult.firstElement(); expectedResult.removeElementAt(0); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp <> ?1"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.notEqual(root, qb.parameter(Employee.class, "1") ) ); List result = em.createQuery(cq).setParameter("1", emp).getResultList(); Assert.assertTrue("abstractSchemaIdentifierNotEqualsTest failed", comparer.compareObjects(result, expectedResult)); } public void simpleInOneDotTest() { //select a specifif employee using Expr Bob Smithn EntityManager em = createEntityManager(); ReadObjectQuery roq = new ReadObjectQuery(Employee.class); ExpressionBuilder empBldr = new ExpressionBuilder(); Expression exp1 = empBldr.get("firstName").equal("Bob"); Expression exp2 = empBldr.get("lastName").equal("Smith"); roq.setSelectionCriteria(exp1.and(exp2)); Employee expectedResult = (Employee)getServerSession().executeQuery(roq); clearCache(); PhoneNumber empPhoneNumbers = (PhoneNumber)((Vector)expectedResult.getPhoneNumbers()).firstElement(); //"SelecT OBJECT(emp) from Employee emp, in (emp.phoneNumbers) phone " + "Where phone.areaCode = \"" + empPhoneNumbers.getAreaCode() + "\"" // + "AND emp.firstName = \"" + expectedResult.getFirstName() + "\"" + "AND emp.lastName = \"" + expectedResult.getLastName() + "\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Join phone = root.join(Employee_.phoneNumbers); Predicate firstAnd = qb.and( qb.equal(phone.get(PhoneNumber_.areaCode), empPhoneNumbers.getAreaCode()), qb.equal(root.get(Employee_.firstName), expectedResult.getFirstName())); cq.where( qb.and(firstAnd, qb.equal(root.get(Employee_.lastName), expectedResult.getLastName())) ); Employee result = em.createQuery(cq).getSingleResult(); Assert.assertTrue("Simple In Dot Test failed", comparer.compareObjects(result, expectedResult)); } public void selectAverageQueryForByteColumnTest() { EntityManager em = createEntityManager(); //"Select AVG(emp.salary)from Employee emp" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Double> cq = qb.createQuery(Double.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); //casting types again. Avg takes a number, so Path<Object> won't compile cq.select( qb.avg( root.get(Employee_.salary) ) ); Object result = em.createQuery(cq).getSingleResult(); Assert.assertTrue("AVG result type [" + result.getClass() + "] not of type Double", result.getClass() == Double.class); } public void simpleInTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id IN (" + expectedResult.getId().toString() + ")" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.in(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.id)).value(expectedResult.getId()) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple In Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleInListTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); List expectedResultList = new ArrayList(); expectedResultList.add(expectedResult.getId()); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id IN :result" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); //passing a collection to IN might not be supported in criteria api, trying to get around it by hidding the type ParameterExpression exp = qb.parameter(List.class, "result"); cq.where( qb.in(root.get(Employee_.id)).value(exp) ); List result = em.createQuery(cq).setParameter("result", expectedResultList).getResultList(); Assert.assertTrue("Simple In Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleLengthTest() { EntityManager em = createEntityManager(); Assert.assertFalse("Warning SQL doesnot support LENGTH function", (JUnitTestCase.getServerSession()).getPlatform().isSQLServer()); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String ejbqlString; //"SELECT OBJECT(emp) FROM Employee emp WHERE LENGTH ( emp.firstName ) = " + expectedResult.getFirstName().length(); QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal( qb.length(root.get(Employee_.firstName)) , expectedResult.getFirstName().length()) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Length Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleLikeTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String partialFirstName = expectedResult.getFirstName().substring(0, 3) + "%"; //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName LIKE \"" + partialFirstName + "\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.like( root.get(Employee_.firstName), partialFirstName) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Like Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleLikeTestWithParameter() { EntityManager em = createEntityManager(); Employee emp = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); String partialFirstName = "%" + emp.getFirstName().substring(0, 3) + "%"; ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); Vector parameters = new Vector(); parameters.add(partialFirstName); ExpressionBuilder eb = new ExpressionBuilder(); Expression whereClause = eb.get("firstName").like(partialFirstName); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName LIKE ?1" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.like( root.get(Employee_.firstName), qb.parameter(String.class, "1")) ); List result = em.createQuery(cq).setParameter("1", partialFirstName).getResultList(); Assert.assertTrue("Simple Like Test with Parameter failed", comparer.compareObjects(result, expectedResult)); } public void simpleLikeEscapeTestWithParameter() { EntityManager em = createEntityManager(); Address expectedResult = new Address(); expectedResult.setCity("TAIYUAN"); expectedResult.setCountry("CHINA"); expectedResult.setProvince("SHANXI"); expectedResult.setPostalCode("030024"); expectedResult.setStreet("234 RUBY _Way"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); uow.registerObject(expectedResult); uow.commit(); //test the apostrophe //"SELECT OBJECT(address) FROM Address address WHERE address.street LIKE :pattern ESCAPE :esc" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Address> cq = qb.createQuery(Address.class); Root<Address> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Address.class)); cq.where( qb.like( root.get(Address_.street), qb.parameter(String.class, "pattern"), qb.parameter(Character.class, "esc")) ); String patternString = null; Character escChar = null; // \ is always treated as escape in MySQL. Therefore ESCAPE '\' is considered a syntax error if (getServerSession().getPlatform().isMySQL()) { patternString = "234 RUBY $_Way"; escChar = new Character('$'); } else { patternString = "234 RUBY \\_Way"; escChar = new Character('\\'); } List result = em.createQuery(cq).setParameter("pattern", patternString).setParameter("esc", escChar).getResultList(); Assert.assertTrue("Simple Escape Underscore test failed", comparer.compareObjects(result, expectedResult)); } public void simpleNotBetweenTest() { EntityManager em = createEntityManager(); Employee emp1 = (Employee)getServerSession().readAllObjects(Employee.class).firstElement(); Employee emp2 = (Employee)getServerSession().readAllObjects(Employee.class).lastElement(); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); ExpressionBuilder eb = new ExpressionBuilder(); Expression whereClause = eb.get("id").between(emp1.getId(), emp2.getId()).not(); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id NOT BETWEEN " + emp1.getId() + " AND "+ emp2.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.not(qb.between(root.get(Employee_.id), emp1.getId(), emp2.getId())) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Not Between Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleNotEqualsVariablesInteger() { EntityManager em = createEntityManager(); Vector expectedResult = getServerSession().readAllObjects(Employee.class); clearCache(); Employee emp = (Employee)expectedResult.elementAt(0); expectedResult.removeElementAt(0); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id <> " + emp.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.notEqual(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.id), emp.getId()) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Like Test with Parameter failed", comparer.compareObjects(result, expectedResult)); } public void simpleNotInTest() { EntityManager em = createEntityManager(); Employee emp = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); ExpressionBuilder builder = new ExpressionBuilder(); Vector idVector = new Vector(); idVector.add(emp.getId()); Expression whereClause = builder.get("id").notIn(idVector); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id NOT IN (" + emp.getId().toString() + ")" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.not(qb.in(root.get(Employee_.id)).value(emp.getId())) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Not In Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleNotLikeTest() { EntityManager em = createEntityManager(); Employee emp = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); String partialFirstName = emp.getFirstName().substring(0, 3) + "%"; ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").notLike(partialFirstName); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName NOT LIKE \"" + partialFirstName + "\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.notLike(root.get(Employee_.firstName), partialFirstName ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Not Like Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleOrFollowedByAndTest() { EntityManager em = createEntityManager(); Employee emp1 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); Employee emp2 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(1); Employee emp3 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(2); Vector expectedResult = new Vector(); expectedResult.add(emp1); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id = " + emp1.getId() + " OR emp.id = " + emp2.getId() + " AND emp.id = " + emp3.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Predicate andOpp = qb.and(qb.equal(root.get(Employee_.id), emp2.getId()), qb.equal(root.get(Employee_.id), emp3.getId())); cq.where( qb.or( qb.equal(root.get(Employee_.id), emp1.getId()), andOpp ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Or followed by And Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleOrFollowedByAndTestWithStaticNames() { EntityManager em = createEntityManager(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").equal("John").or(builder.get("firstName").equal("Bob").and(builder.get("lastName").equal("Smith"))); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = \"John\" OR emp.firstName = \"Bob\" AND emp.lastName = \"Smith\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression empFName = root.get(Employee_.firstName); Predicate andOpp = qb.and(qb.equal(empFName, "Bob"), qb.equal(root.get(Employee_.lastName), "Smith")); cq.where( qb.or( qb.equal(empFName, "John"), andOpp ) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Or followed by And With Static Names Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleOrTest() { EntityManager em = createEntityManager(); Employee emp1 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); Employee emp2 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(1); Vector expectedResult = new Vector(); expectedResult.add(emp1); expectedResult.add(emp2); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id = " + emp1.getId() + "OR emp.id = " + emp2.getId() QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression empId = root.get(Employee_.id); cq.where( qb.or( qb.equal(empId, emp1.getId()), qb.equal(empId, emp2.getId()) ) ); List result = em.createQuery(cq).getResultList(); clearCache(); Assert.assertTrue("Simple Or Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleParameterTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); String parameterName = "firstName"; ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").equal(builder.getParameter(parameterName)); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); raq.addArgument(parameterName); Vector parameters = new Vector(); parameters.add(expectedResult.getFirstName()); Vector employees = (Vector)getServerSession().executeQuery(raq, parameters); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE " + "emp.firstName = ?1 " QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.firstName), qb.parameter(String.class,parameterName)) ); List result = em.createQuery(cq).setParameter(parameterName, expectedResult.getFirstName()).getResultList(); Assert.assertTrue("Simple Parameter Test failed", comparer.compareObjects(result, expectedResult)); } public void simpleParameterTestChangingParameters() { EntityManager em = createEntityManager(); Employee emp1 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); Employee emp2 = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(1); String parameterName = "firstName"; ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").equal(builder.getParameter(parameterName)); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); raq.addArgument(parameterName); Vector firstParameters = new Vector(); firstParameters.add(emp1.getFirstName()); Vector secondParameters = new Vector(); secondParameters.add(emp2.getFirstName()); Vector firstEmployees = (Vector)getServerSession().executeQuery(raq, firstParameters); clearCache(); Vector secondEmployees = (Vector)getServerSession().executeQuery(raq, secondParameters); clearCache(); Vector expectedResult = new Vector(); expectedResult.addAll(firstEmployees); expectedResult.addAll(secondEmployees); //"SELECT OBJECT(emp) FROM Employee emp WHERE " + "emp.firstName = ?1 " QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.firstName), qb.parameter(String.class, "1")) ); List firstResultSet = em.createQuery(cq).setParameter("1", firstParameters.get(0)).getResultList(); clearCache(); List secondResultSet = em.createQuery(cq).setParameter("1", secondParameters.get(0)).getResultList(); clearCache(); Vector result = new Vector(); result.addAll(firstResultSet); result.addAll(secondResultSet); Assert.assertTrue("Simple Parameter Test Changing Parameters failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseAbsTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE " + expectedResult.getSalary() + " = ABS(emp.salary)" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); //equal can't take an int as the first argument, it must be an expression cq.where( qb.equal(qb.literal(expectedResult.getSalary()), qb.abs(root.get(Employee_.salary))) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse Abs test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseConcatTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String partOne = expectedResult.getFirstName().substring(0, 2); String partTwo = expectedResult.getFirstName().substring(2); //"SELECT OBJECT(emp) FROM Employee emp WHERE CONCAT(\""+ partOne + "\", \""+ partTwo + "\") = emp.firstName"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); //One argument to concat must be an expression cq.where( qb.equal(qb.concat(partOne, qb.literal(partTwo)), root.get(Employee_.firstName)) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse Concat test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseEqualsTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE \"" + expectedResult.getFirstName() + "\" = emp.firstName" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(qb.literal(expectedResult.getFirstName()), root.get(Employee_.firstName)) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse Equals test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseLengthTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE " + expectedResult.getFirstName().length() + " = LENGTH(emp.firstName)" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression<Integer> length = qb.length(root.get(Employee_.firstName)); cq.where( qb.equal(qb.literal(expectedResult.getFirstName().length()), length) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse Length test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseParameterTest() { EntityManager em = createEntityManager(); Employee emp = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String parameterName = "firstName"; ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").equal(builder.getParameter(parameterName)); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); raq.addArgument(parameterName); Vector parameters = new Vector(); parameters.add(emp.getFirstName()); Vector expectedResult = (Vector)getServerSession().executeQuery(raq, parameters); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE ?1 = emp.firstName " QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(qb.parameter(String.class, "1"), root.get(Employee_.firstName)) ); List result = em.createQuery(cq).setParameter("1", parameters.get(0)).getResultList(); Assert.assertTrue("Simple Reverse Parameter test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseSqrtTest() { EntityManager em = createEntityManager(); ExpressionBuilder expbldr = new ExpressionBuilder(); Expression whereClause = expbldr.get("firstName").equal("SquareRoot").and(expbldr.get("lastName").equal("TestCase1")); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); double salarySquareRoot = Math.sqrt((new Double(((Employee)expectedResult.firstElement()).getSalary()).doubleValue())); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE "+ salarySquareRoot + " = SQRT(emp.salary)" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression<Double> sqrt = qb.sqrt(root.get(Employee_.salary)); cq.where( qb.equal(qb.literal(salarySquareRoot), sqrt) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse Square Root test failed", comparer.compareObjects(result, expectedResult)); } public void simpleReverseSubstringTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String firstNamePart; String ejbqlString; firstNamePart = expectedResult.getFirstName().substring(0, 2); //"SELECT OBJECT(emp) FROM Employee emp WHERE \"" + firstNamePart + "\" = SUBSTRING(emp.firstName, 1, 2)"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression<String> substring = qb.substring(root.get(Employee_.firstName), 1, 2); cq.where( qb.equal(qb.literal(firstNamePart), substring) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Reverse SubString test failed", comparer.compareObjects(result, expectedResult)); } public void simpleSqrtTest() { EntityManager em = createEntityManager(); ExpressionBuilder expbldr = new ExpressionBuilder(); Expression whereClause = expbldr.get("firstName").equal("SquareRoot").and(expbldr.get("lastName").equal("TestCase1")); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); double salarySquareRoot = Math.sqrt((new Double(((Employee)expectedResult.firstElement()).getSalary()).doubleValue())); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE SQRT(emp.salary) = "+ salarySquareRoot QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(qb.sqrt(root.get(Employee_.salary)), salarySquareRoot) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Square Root test failed", comparer.compareObjects(result, expectedResult)); } public void simpleSubstringTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readAllObjects(Employee.class).elementAt(0); clearCache(); String firstNamePart = expectedResult.getFirstName().substring(0, 2); //"SELECT OBJECT(emp) FROM Employee emp WHERE SUBSTRING(emp.firstName, 1, 2) = \"" + firstNamePart + "\"" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression<String> substring = qb.substring(root.get(Employee_.firstName), 1, 2); cq.where( qb.equal(substring, firstNamePart) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple SubString test failed", comparer.compareObjects(result, expectedResult)); } public void simpleNullTest() { EntityManager em = createEntityManager(); Employee nullEmployee = new Employee(); nullEmployee.setFirstName(null); nullEmployee.setLastName("Test"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); uow.registerObject(nullEmployee); uow.commit(); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").isNull(); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName IS NULL" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.isNull(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.firstName)) ); List result = em.createQuery(cq).getResultList(); uow = clientSession.acquireUnitOfWork(); uow.deleteObject(nullEmployee); uow.commit(); Assert.assertTrue("Simple Null test failed", comparer.compareObjects(result, expectedResult)); } public void simpleNotNullTest() { EntityManager em = createEntityManager(); Employee nullEmployee = new Employee(); nullEmployee.setFirstName(null); nullEmployee.setLastName("Test"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); uow.registerObject(nullEmployee); uow.commit(); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").isNull().not(); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName IS NOT NULL" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.isNotNull(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.firstName)) ); List result = em.createQuery(cq).getResultList(); uow = clientSession.acquireUnitOfWork(); uow.deleteObject(nullEmployee); uow.commit(); Assert.assertTrue("Simple Not Null test failed", comparer.compareObjects(result, expectedResult)); } public void distinctTest() { EntityManager em = createEntityManager(); ReadAllQuery raq = new ReadAllQuery(); ExpressionBuilder employee = new ExpressionBuilder(); Expression whereClause = employee.get("lastName").equal("Smith"); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); raq.useDistinct(); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT DISTINCT OBJECT(emp) FROM Employee emp WHERE emp.lastName = \'Smith\'" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.distinct(true); cq.where( qb.equal(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.lastName), "Smith") ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Distinct test failed", comparer.compareObjects(result, expectedResult)); } public void multipleExecutionOfCriteriaQueryTest() { //bug 5279859 EntityManager em = createEntityManager(); //"SELECT e FROM Employee e where e.address.postalCode = :postalCode" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.equal(root.get(Employee_.address).get(Address_.postalCode), qb.parameter(String.class, "postalCode")) ); Query query = em.createQuery(cq); query.setParameter("postalCode", "K1T3B9"); try { query.getResultList(); } catch (RuntimeException ex) { fail("Failed to execute query, exception resulted on first execution, not expected"); } try { query.getResultList(); } catch (RuntimeException ex) { fail("Failed to execute query, exception resulted on second execution"); } query = em.createNamedQuery("findEmployeeByPostalCode"); query.setParameter("postalCode", "K1T3B9"); try { query.getResultList(); } catch (RuntimeException ex) { fail("Failed to execute query, exception resulted on first execution, of second use of named query"); } query.setMaxResults(100000); try { query.getResultList(); } catch (RuntimeException ex) { fail("Failed to execute query, exception resulted after setting max results (forcing reprepare)"); } } public void simpleModTest() { EntityManager em = createEntityManager(); Assert.assertFalse("Warning SQL/Sybase doesnot support MOD function", (JUnitTestCase.getServerSession()).getPlatform().isSQLServer() || (JUnitTestCase.getServerSession()).getPlatform().isSybase()); ReadAllQuery raq = new ReadAllQuery(); ExpressionBuilder employee = new ExpressionBuilder(); Expression whereClause = ExpressionMath.mod(employee.get("salary"), 2).greaterThan(0); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE MOD(emp.salary, 2) > 0" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.gt(qb.mod(root.get(Employee_.salary), 2), 0) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Mod test failed", comparer.compareObjects(result, expectedResult)); // Test MOD(fieldAccess, fieldAccess) glassfish issue 2771 expectedResult = getServerSession().readAllObjects(Employee.class); clearCache(); //"SELECT emp FROM Employee emp WHERE MOD(emp.salary, emp.salary) = 0" qb = em.getQueryBuilder(); cq = qb.createQuery(Employee.class); root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); javax.persistence.criteria.Expression<Integer> salaryExp = root.get(Employee_.salary); cq.where( qb.equal(qb.mod(salaryExp, salaryExp), 0) ); result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Mod test(2) failed", comparer.compareObjects(result, expectedResult)); } public void simpleIsEmptyTest() { EntityManager em = createEntityManager(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.isEmpty("phoneNumbers"); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.phoneNumbers IS EMPTY" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.isEmpty(root.get(Employee_.phoneNumbers)) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Is empty test failed", comparer.compareObjects(result, expectedResult)); } public void simpleIsNotEmptyTest() { EntityManager em = createEntityManager(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.notEmpty("phoneNumbers"); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.phoneNumbers IS NOT EMPTY" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.isNotEmpty(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.phoneNumbers)) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple is not empty test failed", comparer.compareObjects(result, expectedResult)); } //JPQL parsing test, not applicable to criteria api //public void simpleApostrohpeTest() { public void simpleEscapeUnderscoreTest() { EntityManager em = createEntityManager(); Address expectedResult = new Address(); expectedResult.setCity("Perth"); expectedResult.setCountry("Canada"); expectedResult.setProvince("ONT"); expectedResult.setPostalCode("Y3Q2N9"); expectedResult.setStreet("234 Wandering _Way"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); uow.registerObject(expectedResult); uow.commit(); Character escapeChar = null; //"SELECT OBJECT(address) FROM Address address WHERE address.street LIKE '234 Wandering " //+escapeString+"_Way' ESCAPE "+escapeString // \ is always treated as escape in MySQL. Therefore ESCAPE '\' is considered a syntax error if (getServerSession().getPlatform().isMySQL()) { escapeChar = '$'; } else { escapeChar = '\\'; } QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Address> cq = qb.createQuery(Address.class); Root<Address> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Address.class)); cq.where( qb.like(root.get(Address_.street), "234 Wandering "+escapeChar+"_Way", escapeChar) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Escape Underscore test failed", comparer.compareObjects(result, expectedResult)); } public void smallProjectMemberOfProjectsTest() { EntityManager em = createEntityManager(); ReadAllQuery query = new ReadAllQuery(); Expression selectionCriteria = new ExpressionBuilder().anyOf("projects").equal(new ExpressionBuilder(SmallProject.class)); query.setSelectionCriteria(selectionCriteria); query.setReferenceClass(Employee.class); query.dontUseDistinct(); //gf 1395 changed jpql to not use distinct on joins Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"SELECT OBJECT(employee) FROM Employee employee, SmallProject sp WHERE sp MEMBER OF employee.projects"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Project> projRoot = cq.from(getEntityManagerFactory().getMetamodel().entity(Project.class)); Root<Employee> empRoot = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where( qb.isMember(projRoot, empRoot.get(Employee_.projects)) ); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple small Project Member Of Projects test failed", comparer.compareObjects(result, expectedResult)); } public void smallProjectNOTMemberOfProjectsTest() { EntityManager em = createEntityManager(); //query for those employees with Project named "Enterprise" (which should be a SmallProject) ReadObjectQuery smallProjectQuery = new ReadObjectQuery(); smallProjectQuery.setReferenceClass(SmallProject.class); smallProjectQuery.setSelectionCriteria(new ExpressionBuilder().get("name").equal("Enterprise")); SmallProject smallProject = (SmallProject)getServerSession().executeQuery(smallProjectQuery); ReadAllQuery query = new ReadAllQuery(); query.addArgument("smallProject"); Expression selectionCriteria = new ExpressionBuilder().noneOf("projects", new ExpressionBuilder().equal(new ExpressionBuilder().getParameter("smallProject"))); query.setSelectionCriteria(selectionCriteria); query.setReferenceClass(Employee.class); Vector arguments = new Vector(); arguments.add(smallProject); Vector expectedResult = (Vector)getServerSession().executeQuery(query, arguments); //"SELECT OBJECT(employee) FROM Employee employee WHERE ?1 NOT MEMBER OF employee.projects" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where( qb.isNotMember(qb.parameter(Project.class, "1"), cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.projects)) ); List result = em.createQuery(cq).setParameter("1", smallProject).getResultList(); Assert.assertTrue("Simple small Project NOT Member Of Projects test failed", comparer.compareObjects(result, expectedResult)); } //This test demonstrates the bug 4616218, waiting for bug fix public void selectCountOneToOneTest() { EntityManager em = createEntityManager(); ReportQuery query = new ReportQuery(); query.setReferenceClass(PhoneNumber.class); //need to specify Long return type query.addCount("COUNT", new ExpressionBuilder().get("owner").distinct(), Long.class); query.returnSingleAttribute(); query.dontRetrievePrimaryKeys(); query.setName("selectEmployeesThatHavePhoneNumbers"); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"SELECT COUNT(DISTINCT phone.owner) FROM PhoneNumber phone"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Long> cq = qb.createQuery(Long.class); cq.select(qb.countDistinct(cq.from(getEntityManagerFactory().getMetamodel().entity(PhoneNumber.class)).get(PhoneNumber_.owner))); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Select Count One To One test failed", expectedResult.elementAt(0).equals(result.get(0))); } public void selectOneToOneTest() { EntityManager em = createEntityManager(); ReadAllQuery query = new ReadAllQuery(); query.setReferenceClass(Address.class); query.useDistinct(); ExpressionBuilder employeeBuilder = new ExpressionBuilder(Employee.class); Expression selectionCriteria = new ExpressionBuilder(Address.class).equal(employeeBuilder.get("address")).and(employeeBuilder.get("lastName").like("%Way%")); query.setSelectionCriteria(selectionCriteria); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"SELECT DISTINCT employee.address FROM Employee employee WHERE employee.lastName LIKE '%Way%'" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Address> cq = qb.createQuery(Address.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.distinct(true); cq.select(root.get(Employee_.address)); cq.where(qb.like(root.get(Employee_.lastName), "%Way%")); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple Select One To One test failed", comparer.compareObjects(result, expectedResult)); } public void selectPhonenumberDeclaredInINClauseTest() { EntityManager em = createEntityManager(); ReadAllQuery query = new ReadAllQuery(); ExpressionBuilder employeeBuilder = new ExpressionBuilder(Employee.class); Expression phoneAnyOf = employeeBuilder.anyOf("phoneNumbers"); ExpressionBuilder phoneBuilder = new ExpressionBuilder(PhoneNumber.class); Expression selectionCriteria = phoneBuilder.equal(employeeBuilder.anyOf("phoneNumbers")).and(phoneAnyOf.get("number").notNull()); query.setSelectionCriteria(selectionCriteria); query.setReferenceClass(PhoneNumber.class); query.addAscendingOrdering("number"); query.addAscendingOrdering("areaCode"); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"Select Distinct Object(p) from Employee emp, IN(emp.phoneNumbers) p WHERE p.number IS NOT NULL ORDER BY p.number, p.areaCode"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<PhoneNumber> cq = qb.createQuery(PhoneNumber.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Join phone = root.join(Employee_.phoneNumbers); cq.where(qb.isNotNull(phone.get(PhoneNumber_.number))); cq.orderBy(qb.asc(phone.get(PhoneNumber_.number)), qb.asc(phone.get(PhoneNumber_.areaCode))); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple select Phonenumber Declared In IN Clause test failed", comparer.compareObjects(result, expectedResult)); } /** * Test the ALL function. * This test was added to mirror a CTS failure. * This currently throws an error but should be a valid (although odd) query. * BUG#6025292 public void badSelectPhoneUsingALLTest() { EntityManager em = createEntityManager(); ReadAllQuery query = new ReadAllQuery(); ExpressionBuilder employeeBuilder = new ExpressionBuilder(Employee.class); Expression phoneAnyOf = employeeBuilder.anyOf("phoneNumbers"); ExpressionBuilder phoneBuilder = new ExpressionBuilder(PhoneNumber.class); ReportQuery subQuery = new ReportQuery(); subQuery.setReferenceClass(PhoneNumber.class); subQuery.addMinimum("number");//number is a string? //bad sql - Expression selectionCriteria = employeeBuilder.anyOf("phoneNumbers").equal(employeeBuilder.all(subQuery)); //bad sql - Expression selectionCriteria = employeeBuilder.anyOf("phoneNumbers").equal(subQuery); Expression selectionCriteria = phoneBuilder.equal(employeeBuilder.anyOf("phoneNumbers")).and( phoneAnyOf.get("number").equal(employeeBuilder.all(subQuery))); query.setSelectionCriteria(selectionCriteria); query.setReferenceClass(Employee.class); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"Select Distinct Object(emp) from Employee emp, IN(emp.phoneNumbers) p WHERE p.number = ALL (Select MIN(pp.number) FROM PhoneNumber pp)"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.distinct(true); Subquery<Number> sq = cq.subquery(Number.class); Root<PhoneNumber> subroot = cq.from(PhoneNumber.class); sq.select(qb.min(subroot.<Number>get("number")));//number is a string? not sure this will work. Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Join phone = root.join("phoneNumbers"); cq.where(qb.equal(root.get("number"), qb.all(sq))); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("Simple select Phonenumber Declared In IN Clause test failed", comparer.compareObjects(result, expectedResult)); }*/ /** * Test the ALL function. * This test was added to mirror a CTS failure. */ public void selectPhoneUsingALLTest() { EntityManager em = createEntityManager(); ReadAllQuery query = new ReadAllQuery(); ExpressionBuilder employeeBuilder = new ExpressionBuilder(Employee.class); ReportQuery subQuery = new ReportQuery(); subQuery.setReferenceClass(PhoneNumber.class); subQuery.addMinimum("number"); Expression selectionCriteria = employeeBuilder.anyOf("phoneNumbers").get("number").equal(employeeBuilder.all(subQuery)); query.setSelectionCriteria(selectionCriteria); query.setReferenceClass(Employee.class); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"Select Distinct Object(emp) from Employee emp, IN(emp.phoneNumbers) p WHERE p.number = ALL (Select MIN(pp.number) FROM PhoneNumber pp)"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.distinct(true); Subquery<Number> sq = cq.subquery(Number.class); Root<PhoneNumber> subroot = cq.from(PhoneNumber.class); sq.select(qb.min(subroot.<Number>get("number")));//number is a string? not sure this will work. Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); Join phone = root.join(Employee_.phoneNumbers); cq.where(qb.equal(phone.get(PhoneNumber_.number), qb.all(sq))); Query jpqlQuery = em.createQuery(cq); jpqlQuery.setMaxResults(10); List result = jpqlQuery.getResultList(); Assert.assertTrue("Simple select Phonenumber Declared In IN Clause test failed", comparer.compareObjects(result, expectedResult)); } public void selectSimpleMemberOfWithParameterTest() { EntityManager em = createEntityManager(); Employee expectedResult = (Employee)getServerSession().readObject(Employee.class); PhoneNumber phone = new PhoneNumber(); phone.setAreaCode("613"); phone.setNumber("1234567"); phone.setType("cell"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); PhoneNumber phoneClone = (PhoneNumber)uow.registerObject(phone); Employee empClone = (Employee)uow.registerObject(expectedResult); phoneClone.setOwner(empClone); empClone.addPhoneNumber(phoneClone); uow.registerObject(phone); uow.commit(); //"SELECT OBJECT(emp) FROM Employee emp " + "WHERE ?1 MEMBER OF emp.phoneNumbers"; QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where(qb.isMember(qb.parameter(PhoneNumber.class, "1"), root.get(Employee_.phoneNumbers))); Vector parameters = new Vector(); parameters.add(phone); List result = em.createQuery(cq).setParameter("1", phone).getResultList(); uow = clientSession.acquireUnitOfWork(); uow.deleteObject(phone); uow.commit(); Assert.assertTrue("Select simple member of with parameter test failed", comparer.compareObjects(result, expectedResult)); } public void selectSimpleNotMemberOfWithParameterTest() { EntityManager em = createEntityManager(); Vector expectedResult = getServerSession().readAllObjects(Employee.class); clearCache(); Employee emp = (Employee)expectedResult.get(0); expectedResult.remove(0); PhoneNumber phone = new PhoneNumber(); phone.setAreaCode("613"); phone.setNumber("1234567"); phone.setType("cell"); Server serverSession = JUnitTestCase.getServerSession(); Session clientSession = serverSession.acquireClientSession(); UnitOfWork uow = clientSession.acquireUnitOfWork(); emp = (Employee)uow.readObject(emp); PhoneNumber phoneClone = (PhoneNumber)uow.registerObject(phone); phoneClone.setOwner(emp); emp.addPhoneNumber(phoneClone); uow.commit(); //"SELECT OBJECT(emp) FROM Employee emp " + "WHERE ?1 NOT MEMBER OF emp.phoneNumbers" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where(qb.isNotMember(qb.parameter(PhoneNumber.class), root.get(Employee_.phoneNumbers))); Vector parameters = new Vector(); parameters.add(phone); List result = em.createQuery(cq).setParameter("1", phone).getResultList(); uow = clientSession.acquireUnitOfWork(); uow.deleteObject(phone); uow.commit(); Assert.assertTrue("Select simple Not member of with parameter test failed", comparer.compareObjects(result, expectedResult)); } public void selectSimpleBetweenWithParameterTest() { EntityManager em = createEntityManager(); Vector employees = getServerSession().readAllObjects(Employee.class); BigDecimal empId1 = new BigDecimal(0); Employee emp2 = (Employee)employees.lastElement(); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); ExpressionBuilder eb = new ExpressionBuilder(); Expression whereClause = eb.get("id").between(empId1, emp2.getId()); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id BETWEEN ?1 AND ?2" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.where(qb.between(root.get(Employee_.id).as(Comparable.class), qb.parameter(BigDecimal.class, "1"), qb.parameter(Integer.class, "2"))); List result = em.createQuery(cq).setParameter("1", empId1).setParameter("2", emp2.getId()).getResultList(); Assert.assertTrue("Simple select between with parameter test failed", comparer.compareObjects(result, expectedResult)); } public void selectSimpleInWithParameterTest() { EntityManager em = createEntityManager(); Vector employees = getServerSession().readAllObjects(Employee.class); BigDecimal empId1 = new BigDecimal(0); Employee emp2 = (Employee)employees.lastElement(); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); ExpressionBuilder eb = new ExpressionBuilder(); Vector vec = new Vector(); vec.add(empId1); vec.add(emp2.getId()); Expression whereClause = eb.get("id").in(vec); raq.setSelectionCriteria(whereClause); Vector expectedResult = (Vector)getServerSession().executeQuery(raq); clearCache(); //"SELECT OBJECT(emp) FROM Employee emp WHERE emp.id IN (?1, ?2)" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); QueryBuilder.In inExp = qb.in(root.get(Employee_.id)); inExp.value(qb.parameter(BigDecimal.class, "1")); inExp.value(qb.parameter(Integer.class, "2")); cq.where(inExp); List result = em.createQuery(cq).setParameter("1", empId1).setParameter("2", emp2.getId()).getResultList(); Assert.assertTrue("Simple select between with parameter test failed", comparer.compareObjects(result, expectedResult)); } //Test case for ABS function in EJBQL public void simpleEnumTest() { EntityManager em = createEntityManager(); String ejbqlString; //"SELECT emp FROM Employee emp WHERE emp.status = org.eclipse.persistence.testing.models.jpa.advanced.Employee.EmployeeStatus.FULL_TIME" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); cq.where(qb.equal(cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)).get(Employee_.status), org.eclipse.persistence.testing.models.jpa.advanced.Employee.EmployeeStatus.FULL_TIME)); List result = em.createQuery(cq).getResultList(); } public void simpleTypeTest(){ EntityManager em = createEntityManager(); List expectedResult = getServerSession().readAllObjects(LargeProject.class); clearCache(); //"SELECT OBJECT(proj) FROM Project proj WHERE TYPE(proj) = LargeProject" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Project> cq = qb.createQuery(Project.class); cq.where(qb.equal(cq.from(getEntityManagerFactory().getMetamodel().entity(Project.class)).type(), org.eclipse.persistence.testing.models.jpa.advanced.LargeProject.class)); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("SimpleTypeTest", comparer.compareObjects(result, expectedResult)); } public void simpleAsOrderByTest(){ EntityManager em = createEntityManager(); ReportQuery query = new ReportQuery(); query.setReferenceClass(Employee.class); query.addItem("firstName", query.getExpressionBuilder().get("firstName")); query.returnSingleAttribute(); query.dontRetrievePrimaryKeys(); query.addOrdering(query.getExpressionBuilder().get("firstName").ascending()); Vector expectedResult = (Vector)getServerSession().executeQuery(query); clearCache(); //"SELECT e.firstName as firstName FROM Employee e ORDER BY firstName" QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<String> cq = qb.createQuery(String.class); Root<Employee> root = cq.from(getEntityManagerFactory().getMetamodel().entity(Employee.class)); cq.select(root.get(Employee_.firstName)); cq.orderBy(qb.asc(root.get(Employee_.firstName))); List result = em.createQuery(cq).getResultList(); Assert.assertTrue("SimpleTypeTest", comparer.compareObjects(result, expectedResult)); } }
package fertilizers; import database.DatabaseConnection; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JFrame; /** * * @author ProjectTeam */ public class FarmerForm extends AbstractForm { public FarmerForm(JFrame prev) { super(prev); initComponents(); } /** * Creates new form FarmerForm */ public FarmerForm() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jlheader = new javax.swing.JLabel(); jlname = new javax.swing.JLabel(); jladdress = new javax.swing.JLabel(); jlmobile = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtaaddress = new javax.swing.JTextArea(); jtfname = new javax.swing.JTextField(); jtfmobile = new javax.swing.JTextField(); jbtcreate = new javax.swing.JButton(); jbtclear = new javax.swing.JButton(); jbtback = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jlmsg = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jlheader.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jlheader.setText("Create Farmer"); jlname.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jlname.setText("Name : "); jladdress.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jladdress.setText("Address : "); jlmobile.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jlmobile.setText("Mobile : "); jtaaddress.setColumns(20); jtaaddress.setRows(5); jScrollPane1.setViewportView(jtaaddress); jbtcreate.setText("Create"); jbtcreate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtcreateActionPerformed(evt); } }); jbtclear.setText("Clear"); jbtclear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtclearActionPerformed(evt); } }); jbtback.setText("Back"); jbtback.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtbackActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jladdress, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jlmobile, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jtfmobile, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 122, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jbtcreate, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jbtclear, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jlheader, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jbtback, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlname, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jtfname, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(355, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jlheader, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlname, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfname, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jladdress, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlmobile, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfmobile, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbtcreate, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbtclear, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbtback, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34)) ); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jlmsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jlmsg, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbtcreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtcreateActionPerformed // TODO add your handling code here: //declaration String name = this.jtfname.getText(); String address = this.jtaaddress.getText(); String mobileString = this.jtfmobile.getText(); java.sql.Date today; //initialization this.errors.clear(); this.success.clear(); //validation if(name == null || name.isEmpty()){ this.errors.add("Enter Name of the supplier"); } if (mobileString == null || mobileString.isEmpty()) { this.errors.add("Enter a mobile number"); } else { try { long mobile = Long.parseLong(mobileString); if (mobileString.length() != 10) { this.errors.add("Enter 10 digit mobile number"); } } catch (NumberFormatException ex) { this.errors.add("Enter only digits in mobile field"); } } if (address == null || address.isEmpty()) { this.errors.add("Enter address of the supplier"); } if(this.errors.isEmpty()){ this.stmt = DatabaseConnection.getConnection().getStatement(); this.query = "SELECT id " + "FROM farmer " + "where name='" + name + "' AND address='" + address + "' AND " + "mobile='" + mobileString + "'"; try { this.rs = this.stmt.executeQuery(this.query); if(!this.rs.next()){ this.query = "INSERT INTO farmer " + "(name, address, mobile) " + "VALUES " + "('" + name + "', '" + address + "', '" + mobileString + "')"; this.rs = null; // to ensure we are not using the previous result set again Integer numero = this.stmt.executeUpdate(this.query, Statement.RETURN_GENERATED_KEYS); this.rs = this.stmt.getGeneratedKeys(); if (this.rs != null && this.rs.next()) { Long farmerId = this.rs.getLong(1); this.success.add("Farmer account with ID " + farmerId + " is created successfully"); //only if the Famer id is created, generate an account for the farmer //convert today to sql date format java.util.Date util_today = new java.util.Date(); today = new java.sql.Date(util_today.getTime()); this.query = "INSERT INTO account " + "(farmerid, date, balance) " + "VALUES " + "('" + farmerId + "', '" + today + "', '" + 0.00 + "')"; this.rs = null; numero = this.stmt.executeUpdate(this.query, Statement.RETURN_GENERATED_KEYS); this.rs = this.stmt.getGeneratedKeys(); if(this.rs != null && this.rs.next()){ this.success.add("An account for the farmer with ID " + this.rs.getLong(1) + " is created successfully"); } else { this.errors.add(" But account for this farmer is not created"); } } else { this.errors.add("Farmer IDis not created"); } } else { this.errors.add("A farmer with same data already exists"); } } catch (SQLException ex) { this.errors.add("Cannot insert data into database"); } } if (!this.errors.isEmpty()) { this.jlmsg.setText(this.msgListToString(this.errors)); } if (!this.success.isEmpty()) { this.jlmsg.setText(this.msgListToString(this.success)); } }//GEN-LAST:event_jbtcreateActionPerformed private void jbtclearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtclearActionPerformed // TODO add your handling code here: this.jtaaddress.setText(""); this.jtfmobile.setText(""); this.jtfname.setText(""); }//GEN-LAST:event_jbtclearActionPerformed private void jbtbackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtbackActionPerformed // TODO add your handling code here: this.goToPrevious(); }//GEN-LAST:event_jbtbackActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FarmerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FarmerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FarmerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FarmerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FarmerForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbtback; private javax.swing.JButton jbtclear; private javax.swing.JButton jbtcreate; private javax.swing.JLabel jladdress; private javax.swing.JLabel jlheader; private javax.swing.JLabel jlmobile; private javax.swing.JLabel jlmsg; private javax.swing.JLabel jlname; private javax.swing.JTextArea jtaaddress; private javax.swing.JTextField jtfmobile; private javax.swing.JTextField jtfname; // End of variables declaration//GEN-END:variables }
package io.trane.future; import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; /** * Promise is a Future that provides methods to set its result. They are useful * to interact with callback-based APIs like the ones that are typically * provided by network libraries. A promise can be created and returned * synchronously to the caller, but its completion is deferred until the value is * set, typically by a callback. * * @param <T> * the type of the asynchronous computation result */ public abstract class Promise<T> implements Future<T> { private static final long STATE_OFFSET = Unsafe.objectFieldOffset(Promise.class, "state"); private static final Logger LOGGER = Logger.getLogger(Promise.class.getName()); /** * Creates a promise that triggers the provided handlers in case it receives * an interrupt. * * @param handlers the list of handlers to be triggered. * @return the new promise instance. */ public static final <T> Promise<T> apply(final List<? extends InterruptHandler> handlers) { final Optional<?>[] savedContext = Local.save(); if (savedContext.length == 0) return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return Local.EMPTY; } @Override protected final InterruptHandler getInterruptHandler() { return InterruptHandler.apply(handlers); } }; else return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return savedContext; } @Override protected final InterruptHandler getInterruptHandler() { return InterruptHandler.apply(handlers); } }; } /** * Creates a promise that triggers the provided handler in case it receives an * interrupt. * * @param handler the handler to be triggered. * @return the new promise instance. */ public static final <T> Promise<T> apply(final InterruptHandler handler) { final Optional<?>[] savedContext = Local.save(); if (savedContext.length == 0) return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return Local.EMPTY; } @Override protected final InterruptHandler getInterruptHandler() { return handler; } }; else return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return savedContext; } @Override protected final InterruptHandler getInterruptHandler() { return handler; } }; } /** * Creates a promise without an interrupt handler. Interrupt signals are * ignored by the created promise since there's no handler. * * @return the new promise instance. */ public static final <T> Promise<T> apply() { final Optional<?>[] savedContext = Local.save(); if (savedContext.length == 0) return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return Local.EMPTY; } }; else return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return savedContext; } }; } /** * Creates a new promise using a handler builder that it's based on the * promise under creation. This method allows the user to define handlers that * use the it's own promise. * * @param handlerBuilder * a builder that receives the new promise and returns the interrupt * handler of the new promise. * @return the new promise. */ public static final <T> Promise<T> create(final Function<Promise<T>, InterruptHandler> handlerBuilder) { final Optional<?>[] savedContext = Local.save(); if (savedContext.length == 0) return new Promise<T>() { final InterruptHandler handler = handlerBuilder.apply(this); @Override protected final Optional<?>[] getSavedContext() { return Local.EMPTY; } @Override protected final InterruptHandler getInterruptHandler() { return handler; } }; else return new Promise<T>() { final InterruptHandler handler = handlerBuilder.apply(this); @Override protected final Optional<?>[] getSavedContext() { return savedContext; } @Override protected final InterruptHandler getInterruptHandler() { return handler; } }; } protected static final <T> Promise<T> apply(final InterruptHandler h1, final InterruptHandler h2) { final Optional<?>[] savedContext = Local.save(); return new Promise<T>() { @Override protected final Optional<?>[] getSavedContext() { return savedContext; } @Override protected final InterruptHandler getInterruptHandler() { return InterruptHandler.apply(h1, h2); } }; } protected Promise() { } // Future<T> (Done) | Promise<T>|LinkedContinuation<?, T> (Linked) | // WaitQueue|Null (Pending) volatile Object state; protected InterruptHandler getInterruptHandler() { return null; } protected Optional<?>[] getSavedContext() { return null; } private final boolean cas(final Object oldState, final Object newState) { return Unsafe.compareAndSwapObject(this, STATE_OFFSET, oldState, newState); } /** * Becomes another future. This and result become the same: both are completed * with the same result and both receive the same interrupt signals. * * @param result the future to become. */ public final void become(final Future<T> result) { if (!becomeIfEmpty(result)) throw new IllegalStateException("Can't set result " + result + " for promise with state " + state); } /** * Becomes another future only if this promise is undefined. This and result * become the same: both are completed with the same result and both receive * the same interrupt signals. * * @param result the future to become. * @return if the operation was successful */ public final boolean becomeIfEmpty(final Future<T> result) { final Optional<?>[] savedContext = getSavedContext(); Optional<?>[] originalContext; if (savedContext != null && (originalContext = Local.save()) != savedContext) { Local.restore(savedContext); try { return trySetState(result); } finally { Local.restore(originalContext); } } else return trySetState(result); } @SuppressWarnings("unchecked") public final boolean trySetState(final Future<T> result) { try { while (true) { final Object curr = state; if (curr instanceof SatisfiedFuture) return false; else if (curr instanceof Promise && !(curr instanceof Continuation)) return ((Promise<T>) curr).becomeIfEmpty(result); else if (curr instanceof LinkedContinuation) return ((LinkedContinuation<?, T>) curr).becomeIfEmpty(result); else if (result instanceof Promise) { ((Promise<T>) result).compress().link(this); return true; } else if (cas(curr, result)) { if (curr != null) ((WaitQueue<T>) curr).flush(result); return true; } } } catch (final StackOverflowError ex) { if (!(this instanceof Continuation)) LOGGER.log(Level.SEVERE, "FATAL: Stack overflow when satisfying promise, the promise and its continuations won't be satisfied. " + "Use `Future.tailrec` or increase the stack size (-Xss) if the future isn't recursive.", ex); throw ex; } } @SuppressWarnings("unchecked") protected final WaitQueue<T> safeFlush(final Future<T> result) { while (true) { final Object curr = state; if (curr instanceof Promise && !(curr instanceof Continuation)) return ((Promise<T>) curr).safeFlush(result); else if (curr instanceof LinkedContinuation) return ((LinkedContinuation<?, T>) curr).safeFlush(result); else if (curr instanceof SatisfiedFuture) return null; else if (result instanceof Promise) { ((Promise<T>) result).compress().link(this); return null; } else if (cas(curr, result)) return (WaitQueue<T>) curr; } } @SuppressWarnings("unchecked") private final void link(final Promise<T> target) { while (true) { final Object curr = state; if (curr instanceof SatisfiedFuture) { target.become((SatisfiedFuture<T>) curr); return; } else { Object newState; if (target instanceof Continuation) newState = new LinkedContinuation<>((Continuation<T, ?>) target); else newState = target; if (cas(curr, newState)) { if (curr != null) ((WaitQueue<T>) curr).forward(target); return; } } } } @SuppressWarnings("unchecked") protected final <R> Future<R> continuation(final Continuation<T, R> c) { while (true) { final Object curr = state; if (curr == null) { if (cas(curr, c)) return c; } else if (curr instanceof WaitQueue) { if (cas(curr, ((WaitQueue<T>) curr).add(c))) return c; } else if (curr instanceof SatisfiedFuture) { c.flush((SatisfiedFuture<T>) curr); return c; } else if (curr instanceof Promise && !(curr instanceof Continuation)) return ((Promise<T>) curr).continuation(c); else if (curr instanceof LinkedContinuation) return ((LinkedContinuation<?, T>) curr).continuation(c); } } @SuppressWarnings("unchecked") private final Promise<T> compress() { while (true) { final Object curr = state; if (curr instanceof Promise && !(curr instanceof Continuation)) { // Linked final Promise<T> target = ((Promise<T>) curr).compress(); if (curr == target || cas(curr, target)) return target; } else return this; } } /** * Completes this promise with value. * * @param value the result. */ public final void setValue(final T value) { become(new ValueFuture<>(value)); } /** * Completes this promise with a failure ex. * * @param ex the failure. */ public final void setException(final Throwable ex) { become(new ExceptionFuture<>(ex)); } /** * Raises an interrupt. * * @param ex the interrupt exception. */ @SuppressWarnings("unchecked") @Override public final void raise(final Throwable ex) { InterruptHandler interruptHandler; final Object curr = state; if (curr instanceof SatisfiedFuture) // Done return; else if (curr instanceof Promise && !(curr instanceof Continuation)) // Linked ((Promise<T>) curr).raise(ex); else if (curr instanceof LinkedContinuation) ((LinkedContinuation<?, T>) curr).raise(ex); else if ((interruptHandler = getInterruptHandler()) != null) interruptHandler.raise(ex); } @Override public Future<T> interruptible() { final Promise<T> r = Promise.create(p -> ex -> p.setException(ex)); this.proxyTo(r); return r; } @SuppressWarnings("unchecked") @Override public final boolean isDefined() { final Object curr = state; if (curr instanceof SatisfiedFuture) // Done return true; else if (curr instanceof Promise && !(curr instanceof Continuation)) // Linked return ((Promise<T>) curr).isDefined(); else if (curr instanceof LinkedContinuation) return ((LinkedContinuation<?, T>) curr).isDefined(); else // Waiting return false; } @SuppressWarnings("unchecked") @Override public final T get(final Duration timeout) throws CheckedFutureException { final Object curr = state; if (curr instanceof Future && !(curr instanceof Continuation) && ((Future<T>) curr).isDefined()) return ((Future<T>) curr).get(Duration.ZERO); else if (curr instanceof LinkedContinuation && ((LinkedContinuation<?, T>) curr).isDefined()) return ((LinkedContinuation<?, T>) curr).get(Duration.ZERO); else { join(timeout); return ((Future<T>) state).get(Duration.ZERO); } } // Inpired by Scala Future's CompletionLatch private static final class ReleaseOnRunLatch extends AbstractQueuedSynchronizer implements Runnable { private static final long serialVersionUID = -2448584187877095292L; @Override protected int tryAcquireShared(int arg) { if (getState() != 0) return 1; else return -1; } @Override protected boolean tryReleaseShared(int arg) { setState(1); return true; } @Override public final void run() { releaseShared(1); } } @Override public final void join(final Duration timeout) throws CheckedFutureException { final ReleaseOnRunLatch latch = new ReleaseOnRunLatch(); ensure(latch); try { if (!latch.tryAcquireSharedNanos(1, timeout.toNanos())) throw new TimeoutException(); } catch (final InterruptedException ex) { throw new CheckedFutureException(ex); } } private static class Map<T, R> extends Continuation<T, R> { private final Function<? super T, ? extends R> f; public Map(final Function<? super T, ? extends R> f) { this.f = f; } @Override final Future<R> apply(final Future<T> result) { return result.map(f); } } @Override public final <R> Future<R> map(final Function<? super T, ? extends R> f) { if (getInterruptHandler() != null) return continuation(new Map<T, R>(f) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Map<T, R>(f)); } private static class FlatMap<T, R> extends Continuation<T, R> { private final Function<? super T, ? extends Future<R>> f; public FlatMap(final Function<? super T, ? extends Future<R>> f) { this.f = f; } @Override final Future<R> apply(final Future<T> result) { return result.flatMap(f); } } @Override public final <R> Future<R> flatMap(final Function<? super T, ? extends Future<R>> f) { if (getInterruptHandler() != null) return continuation(new FlatMap<T, R>(f) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new FlatMap<T, R>(f)); } private static class Transform<T, R> extends Continuation<T, R> { private final Transformer<? super T, ? extends R> t; public Transform(final Transformer<? super T, ? extends R> t) { this.t = t; } @Override final Future<R> apply(final Future<T> result) { return result.transform(t); } } @Override public <R> Future<R> transform(final Transformer<? super T, ? extends R> t) { if (getInterruptHandler() != null) return continuation(new Transform<T, R>(t) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Transform<T, R>(t)); } private static class TransformWith<T, R> extends Continuation<T, R> { private final Transformer<? super T, ? extends Future<R>> t; public TransformWith(final Transformer<? super T, ? extends Future<R>> t) { this.t = t; } @Override final Future<R> apply(final Future<T> result) { return result.transformWith(t); } } @Override public <R> Future<R> transformWith(final Transformer<? super T, ? extends Future<R>> t) { if (getInterruptHandler() != null) return continuation(new TransformWith<T, R>(t) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new TransformWith<T, R>(t)); } private static class BiMap<T, U, R> extends Continuation<T, R> { private final BiFunction<? super T, ? super U, ? extends R> f; private final Future<U> other; public BiMap(final Future<U> other, final BiFunction<? super T, ? super U, ? extends R> f) { this.other = other; this.f = f; } @Override final Future<R> apply(final Future<T> result) { return result.biMap(other, f); } } @Override public <U, R> Future<R> biMap(final Future<U> other, final BiFunction<? super T, ? super U, ? extends R> f) { if (getInterruptHandler() != null) return continuation(new BiMap<T, U, R>(other, f) { @Override protected final InterruptHandler getInterruptHandler() { return InterruptHandler.apply(Promise.this, other); } }); else return continuation(new BiMap<T, U, R>(other, f)); } private static class BiFlatMap<T, U, R> extends Continuation<T, R> { private final BiFunction<? super T, ? super U, ? extends Future<R>> f; private final Future<U> other; public BiFlatMap(final Future<U> other, final BiFunction<? super T, ? super U, ? extends Future<R>> f) { this.other = other; this.f = f; } @Override final Future<R> apply(final Future<T> result) { return result.biFlatMap(other, f); } } @Override public <U, R> Future<R> biFlatMap(final Future<U> other, final BiFunction<? super T, ? super U, ? extends Future<R>> f) { if (getInterruptHandler() != null) return continuation(new BiFlatMap<T, U, R>(other, f) { @Override protected final InterruptHandler getInterruptHandler() { return InterruptHandler.apply(Promise.this, other); } }); else return continuation(new BiFlatMap<T, U, R>(other, f)); } private static class Ensure<T> extends Continuation<T, T> { private final Runnable f; public Ensure(final Runnable f) { this.f = f; } @Override final Future<T> apply(final Future<T> result) { return result.ensure(f); } } @Override public final Future<T> ensure(final Runnable f) { if (getInterruptHandler() != null) return continuation(new Ensure<T>(f) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Ensure<T>(f)); } private static class OnSuccess<T> extends Continuation<T, T> { private final Consumer<? super T> c; public OnSuccess(final Consumer<? super T> c) { this.c = c; } @Override final Future<T> apply(final Future<T> result) { return result.onSuccess(c); } } @Override public final Future<T> onSuccess(final Consumer<? super T> c) { if (getInterruptHandler() != null) return continuation(new OnSuccess<T>(c) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new OnSuccess<T>(c)); } private static class OnFailure<T> extends Continuation<T, T> { private final Consumer<Throwable> c; public OnFailure(final Consumer<Throwable> c) { this.c = c; } @Override final Future<T> apply(final Future<T> result) { return result.onFailure(c); } } @Override public final Future<T> onFailure(final Consumer<Throwable> c) { if (getInterruptHandler() != null) return continuation(new OnFailure<T>(c) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new OnFailure<T>(c)); } private static class Respond<T> extends Continuation<T, T> { private final Responder<? super T> r; public Respond(final Responder<? super T> r) { this.r = r; } @Override final Future<T> apply(final Future<T> result) { return result.respond(r); } } @Override public final Future<T> respond(final Responder<? super T> r) { if (getInterruptHandler() != null) return continuation(new Respond<T>(r) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Respond<T>(r)); } private static class Rescue<T> extends Continuation<T, T> { private final Function<Throwable, ? extends Future<T>> f; public Rescue(final Function<Throwable, ? extends Future<T>> f) { this.f = f; } @Override final Future<T> apply(final Future<T> result) { return result.rescue(f); } } @Override public final Future<T> rescue(final Function<Throwable, ? extends Future<T>> f) { if (getInterruptHandler() != null) return continuation(new Rescue<T>(f) { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Rescue<T>(f)); } private static class Voided<T> extends Continuation<T, Void> { @Override final Future<Void> apply(final Future<T> result) { return result.voided(); } } @Override public final Future<Void> voided() { if (getInterruptHandler() != null) return continuation(new Voided<T>() { @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } }); else return continuation(new Voided<T>()); } private final class DelayedPromise extends Promise<T> implements Runnable { @Override public final void run() { become(Promise.this); } @Override protected final InterruptHandler getInterruptHandler() { return Promise.this; } } @Override public final Future<T> delayed(final Duration delay, final ScheduledExecutorService scheduler) { final DelayedPromise p = new DelayedPromise(); scheduler.schedule(p, delay.toMillis(), TimeUnit.MILLISECONDS); return p; } @Override public final void proxyTo(final Promise<T> p) { if (p.isDefined()) throw new IllegalStateException("Cannot call proxyTo on an already satisfied Promise."); final Responder<T> r = new Responder<T>() { @Override public final void onException(final Throwable ex) { p.setException(ex); } @Override public final void onValue(final T value) { p.setValue(value); } }; respond(r); } private static final class WithinPromise<T> extends Promise<T> implements Responder<T>, Runnable { private final InterruptHandler handler; private final ScheduledFuture<?> task; private final Throwable exception; public WithinPromise(final InterruptHandler handler, final Duration timeout, final ScheduledExecutorService scheduler, final Throwable exception) { this.handler = handler; this.task = scheduler.schedule(this, timeout.toMillis(), TimeUnit.MILLISECONDS); this.exception = exception; } @Override public final void onException(final Throwable ex) { task.cancel(false); becomeIfEmpty(Future.exception(ex)); } @Override public final void onValue(final T value) { task.cancel(false); becomeIfEmpty(Future.value(value)); } @Override public final void run() { handler.raise(exception); becomeIfEmpty(Future.exception(exception)); } @Override protected final InterruptHandler getInterruptHandler() { return handler; } } @Override public final Future<T> within(final Duration timeout, final ScheduledExecutorService scheduler, final Throwable exception) { if (timeout.toMillis() == Long.MAX_VALUE) return this; final WithinPromise<T> p = new WithinPromise<>(this, timeout, scheduler, exception); respond(p); return p; } protected String toStringPrefix() { return "Promise"; } @Override public final String toString() { final Object curr = state; String stateString; if (curr instanceof SatisfiedFuture) stateString = curr.toString(); else if ((curr instanceof Promise && !(curr instanceof Continuation)) || curr instanceof LinkedContinuation) // Linked stateString = String.format("Linked(%s)", curr.toString()); else stateString = "Waiting"; return String.format("%s(%s)@%s", toStringPrefix(), stateString, Integer.toHexString(hashCode())); } } abstract class Continuation<T, R> extends Promise<R> implements WaitQueue<T> { @Override public final WaitQueue<T> add(final Continuation<T, ?> c) { return new WaitQueueHeadTail<>(c, this); } @Override public final void forward(final Promise<T> target) { target.continuation(this); } @SuppressWarnings("unchecked") @Override public final void flush(final Future<T> result) { Future<Object> r = (Future<Object>) result; WaitQueue<Object> q = (Continuation<Object, Object>) this; while (q instanceof Continuation) { final Continuation<Object, Object> c = (Continuation<Object, Object>) q; r = c.apply(r); q = c.safeFlush(r); } if (q != null) q.flush(r); } abstract Future<R> apply(Future<T> result); @Override protected String toStringPrefix() { return "Continuation"; } } final class LinkedContinuation<T, R> { private final Continuation<T, R> continuation; public LinkedContinuation(final Continuation<T, R> continuation) { super(); this.continuation = continuation; } public boolean isDefined() { return continuation.isDefined(); } public final void raise(final Throwable ex) { continuation.raise(ex); } public final boolean becomeIfEmpty(final Future<R> result) { return continuation.becomeIfEmpty(result); } public final WaitQueue<R> safeFlush(final Future<R> result) { return continuation.safeFlush(result); } final <S> Future<S> continuation(final Continuation<R, S> c) { return continuation.continuation(c); } final R get(final Duration timeout) throws CheckedFutureException { return continuation.get(timeout); } @Override public final String toString() { return continuation.toString(); } }
package com.github.longkerdandy.mithril.mqtt.storage.redis.sync; import com.fasterxml.jackson.databind.JsonNode; import com.github.longkerdandy.mithril.mqtt.api.internal.InternalMessage; import com.github.longkerdandy.mithril.mqtt.api.internal.PacketId; import com.github.longkerdandy.mithril.mqtt.api.internal.Publish; import com.github.longkerdandy.mithril.mqtt.storage.redis.RedisKey; import com.github.longkerdandy.mithril.mqtt.util.Topics; import com.lambdaworks.redis.RedisURI; import com.lambdaworks.redis.ValueScanCursor; import io.netty.handler.codec.mqtt.MqttMessageType; import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttVersion; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.github.longkerdandy.mithril.mqtt.storage.redis.util.JSONs.ObjectMapper; /** * RedisSyncStandaloneStorage Test */ public class RedisSyncStandaloneStorageTest { private static RedisSyncStandaloneStorage redis; @BeforeClass public static void init() { redis = new RedisSyncStandaloneStorage(); redis.init(RedisURI.create("redis://localhost")); } @AfterClass public static void destroy() { redis.destroy(); } @After public void clear() { redis.server().flushdb(); } @Test public void connectedTest() { assert redis.updateConnectedNode("client1", "node1") == null; assert redis.updateConnectedNode("client2", "node1") == null; assert redis.updateConnectedNode("client3", "node1") == null; assert redis.updateConnectedNode("client4", "node1") == null; assert redis.updateConnectedNode("client4", "node2").equals("node1"); // overwrite assert redis.updateConnectedNode("client5", "node2") == null; assert redis.updateConnectedNode("client5", "node2").equals("node2"); // overwrite assert redis.getConnectedNode("client1").equals("node1"); assert redis.getConnectedNode("client2").equals("node1"); assert redis.getConnectedNode("client3").equals("node1"); assert redis.getConnectedNode("client4").equals("node2"); assert redis.getConnectedNode("client5").equals("node2"); ValueScanCursor<String> vcs1 = redis.getConnectedClients("node1", "0", 100); assert vcs1.getValues().contains("client1"); assert vcs1.getValues().contains("client2"); assert vcs1.getValues().contains("client3"); ValueScanCursor<String> vcs2 = redis.getConnectedClients("node2", "0", 100); assert vcs2.getValues().contains("client4"); assert vcs2.getValues().contains("client5"); assert redis.removeConnectedNode("client3", "node1"); assert !redis.removeConnectedNode("client4", "node1"); // not exist assert redis.getConnectedNode("client3") == null; assert redis.getConnectedNode("client4").equals("node2"); vcs1 = redis.getConnectedClients("node1", "0", 100); assert !vcs1.getValues().contains("client3"); vcs2 = redis.getConnectedClients("node2", "0", 100); assert vcs2.getValues().contains("client4"); } @Test public void sessionExistTest() { assert redis.getSessionExist("client1") == -1; redis.updateSessionExist("client1", false); assert redis.getSessionExist("client1") == 0; redis.updateSessionExist("client1", true); assert redis.getSessionExist("client1") == 1; redis.removeSessionExist("client1"); assert redis.getSessionExist("client1") == -1; } @Test public void packetIdTest() { assert redis.getNextPacketId("client1") == 1; assert redis.getNextPacketId("client1") == 2; assert redis.getNextPacketId("client1") == 3; redis.string().set(RedisKey.nextPacketId("client1"), "65533"); assert redis.getNextPacketId("client1") == 65534; assert redis.getNextPacketId("client1") == 65535; assert redis.getNextPacketId("client1") == 1; } @Test @SuppressWarnings("unchecked") public void inFlightTest() throws IOException { String json = "{\"menu\": {\n" + " \"id\": \"file\",\n" + " \"value\": \"File\",\n" + " \"popup\": {\n" + " \"menuItem\": [\n" + " {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" + " {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" + " {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" + " ]\n" + " }\n" + "}}"; JsonNode jn = ObjectMapper.readTree(json); InternalMessage<Publish> publish = new InternalMessage<>( MqttMessageType.PUBLISH, false, MqttQoS.AT_LEAST_ONCE, false, MqttVersion.MQTT_3_1_1, "client1", "user1", "broker1", new Publish("menuTopic", 123456, ObjectMapper.writeValueAsBytes(jn))); redis.addInFlightMessage("client1", 123456, publish, false); publish = redis.getInFlightMessage("client1", 123456); assert publish.getMessageType() == MqttMessageType.PUBLISH; assert !publish.isDup(); assert publish.getQos() == MqttQoS.AT_LEAST_ONCE; assert !publish.isRetain(); assert publish.getVersion() == MqttVersion.MQTT_3_1_1; assert publish.getClientId().equals("client1"); assert publish.getUserName().equals("user1"); assert publish.getPayload().getTopicName().equals("menuTopic"); assert publish.getPayload().getPacketId() == 123456; jn = ObjectMapper.readTree(publish.getPayload().getPayload()); assert jn.get("menu").get("id").textValue().endsWith("file"); assert jn.get("menu").get("value").textValue().endsWith("File"); assert jn.get("menu").get("popup").get("menuItem").get(0).get("value").textValue().equals("New"); assert jn.get("menu").get("popup").get("menuItem").get(0).get("onclick").textValue().equals("CreateNewDoc()"); assert jn.get("menu").get("popup").get("menuItem").get(1).get("value").textValue().equals("Open"); assert jn.get("menu").get("popup").get("menuItem").get(1).get("onclick").textValue().equals("OpenDoc()"); assert jn.get("menu").get("popup").get("menuItem").get(2).get("value").textValue().equals("Close"); assert jn.get("menu").get("popup").get("menuItem").get(2).get("onclick").textValue().equals("CloseDoc()"); publish = redis.getAllInFlightMessages("client1").get(0); assert publish.getPayload().getPacketId() == 123456; redis.removeInFlightMessage("client1", 123456); assert redis.getInFlightMessage("client1", 123456) == null; assert redis.getAllInFlightMessages("client1").size() == 0; InternalMessage<PacketId> pubrel = new InternalMessage<>( MqttMessageType.PUBREL, false, MqttQoS.AT_LEAST_ONCE, false, MqttVersion.MQTT_3_1_1, "client1", "user1", "broker1", new PacketId(10000)); redis.addInFlightMessage("client1", 10000, pubrel, false); pubrel = new InternalMessage<>( MqttMessageType.PUBREL, false, MqttQoS.AT_LEAST_ONCE, false, MqttVersion.MQTT_3_1_1, "client1", "user1", "broker1", new PacketId(10001)); redis.addInFlightMessage("client1", 10001, pubrel, false); pubrel = new InternalMessage<>( MqttMessageType.PUBREL, false, MqttQoS.AT_LEAST_ONCE, false, MqttVersion.MQTT_3_1_1, "client1", "user1", "broker1", new PacketId(10002)); redis.addInFlightMessage("client1", 10002, pubrel, false); assert redis.getAllInFlightMessages("client1").size() == 3; pubrel = redis.getAllInFlightMessages("client1").get(1); assert pubrel.getMessageType() == MqttMessageType.PUBREL; assert !pubrel.isDup(); assert pubrel.getQos() == MqttQoS.AT_LEAST_ONCE; assert !pubrel.isRetain(); assert pubrel.getVersion() == MqttVersion.MQTT_3_1_1; assert pubrel.getClientId().equals("client1"); assert pubrel.getUserName().equals("user1"); assert pubrel.getPayload().getPacketId() == 10001; redis.removeAllInFlightMessage("client1"); assert redis.getInFlightMessage("client1", 10000) == null; assert redis.getInFlightMessage("client1", 10001) == null; assert redis.getInFlightMessage("client1", 10002) == null; assert redis.getAllInFlightMessages("client1").size() == 0; } @Test public void qos2Test() { assert redis.addQoS2MessageId("client1", 10000); assert redis.addQoS2MessageId("client1", 10001); assert redis.addQoS2MessageId("client1", 10002); assert !redis.addQoS2MessageId("client1", 10000); assert redis.removeQoS2MessageId("client1", 10000); assert redis.removeQoS2MessageId("client1", 10001); assert redis.removeQoS2MessageId("client1", 10002); assert !redis.removeQoS2MessageId("client1", 10001); assert redis.addQoS2MessageId("client1", 10003); assert redis.addQoS2MessageId("client1", 10004); redis.removeAllQoS2MessageId("client1"); assert !redis.removeQoS2MessageId("client1", 10003); assert !redis.removeQoS2MessageId("client1", 10004); } @Test public void subscriptionTest() { redis.updateSubscription("client1", Topics.sanitizeTopicFilter("a/+/e"), MqttQoS.AT_MOST_ONCE); redis.updateSubscription("client1", Topics.sanitizeTopicFilter("a/+"), MqttQoS.AT_LEAST_ONCE); redis.updateSubscription("client1", Topics.sanitizeTopicName("a/c/e"), MqttQoS.EXACTLY_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicFilter("a/#"), MqttQoS.AT_MOST_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicFilter("a/+"), MqttQoS.AT_LEAST_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicName("a/c/e"), MqttQoS.EXACTLY_ONCE); assert redis.getClientSubscriptions("client1").get("a/+/e/" + Topics.END) == MqttQoS.AT_MOST_ONCE; assert redis.getClientSubscriptions("client1").get("a/+/" + Topics.END) == MqttQoS.AT_LEAST_ONCE; assert redis.getClientSubscriptions("client1").get("a/c/e/" + Topics.END) == MqttQoS.EXACTLY_ONCE; assert redis.getClientSubscriptions("client2").get("a/#/" + Topics.END) == MqttQoS.AT_MOST_ONCE; assert redis.getClientSubscriptions("client2").get("a/+/" + Topics.END) == MqttQoS.AT_LEAST_ONCE; assert redis.getClientSubscriptions("client2").get("a/c/e/" + Topics.END) == MqttQoS.EXACTLY_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicFilter("a/+/e")).get("client1") == MqttQoS.AT_MOST_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicFilter("a/+")).get("client1") == MqttQoS.AT_LEAST_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicFilter("a/+")).get("client2") == MqttQoS.AT_LEAST_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicName("a/c/e")).get("client1") == MqttQoS.EXACTLY_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicName("a/c/e")).get("client2") == MqttQoS.EXACTLY_ONCE; assert redis.getTopicSubscriptions(Topics.sanitizeTopicFilter("a/#")).get("client2") == MqttQoS.AT_MOST_ONCE; redis.removeSubscription("client1", Topics.sanitizeTopicFilter("a/+")); assert !redis.getTopicSubscriptions(Topics.sanitizeTopicFilter("a/+")).containsKey("client1"); assert !redis.getClientSubscriptions("client1").containsKey("a/+/" + Topics.END); } @Test public void matchTopicFilterTest() { redis.updateSubscription("client1", Topics.sanitizeTopicFilter("a/+/e"), MqttQoS.AT_MOST_ONCE); redis.updateSubscription("client1", Topics.sanitizeTopicFilter("a/+"), MqttQoS.AT_LEAST_ONCE); redis.updateSubscription("client1", Topics.sanitizeTopicFilter("a/c/f/#"), MqttQoS.EXACTLY_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicFilter("a/#"), MqttQoS.AT_MOST_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicFilter("a/c/+/+"), MqttQoS.AT_LEAST_ONCE); redis.updateSubscription("client2", Topics.sanitizeTopicFilter("a/d/#"), MqttQoS.EXACTLY_ONCE); redis.updateSubscription("client3", Topics.sanitizeTopicName("a/b/c/d"), MqttQoS.AT_LEAST_ONCE); Map<String, MqttQoS> result = new HashMap<>(); redis.getMatchSubscriptions(Topics.sanitizeTopicName("a/c/f"), result); assert result.get("client1") == MqttQoS.EXACTLY_ONCE; assert result.get("client2") == MqttQoS.AT_MOST_ONCE; assert !result.containsKey("client3"); result.clear(); redis.getMatchSubscriptions(Topics.sanitizeTopicName("a/d/e"), result); assert result.get("client1") == MqttQoS.AT_MOST_ONCE; assert result.get("client2") == MqttQoS.EXACTLY_ONCE; assert !result.containsKey("client3"); result.clear(); redis.getMatchSubscriptions(Topics.sanitizeTopicName("a/b/c/d"), result); assert !result.containsKey("client1"); assert result.get("client2") == MqttQoS.AT_MOST_ONCE; assert result.get("client3") == MqttQoS.AT_LEAST_ONCE; } @Test public void retainTest() throws IOException { String json = "{\"menu\": {\n" + " \"id\": \"file\",\n" + " \"value\": \"File\",\n" + " \"popup\": {\n" + " \"menuItem\": [\n" + " {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" + " {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" + " {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" + " ]\n" + " }\n" + "}}"; JsonNode jn = ObjectMapper.readTree(json); InternalMessage<Publish> publish = new InternalMessage<>( MqttMessageType.PUBLISH, false, MqttQoS.AT_LEAST_ONCE, false, MqttVersion.MQTT_3_1_1, "client1", "user1", "broker1", new Publish("menuTopic", 123456, ObjectMapper.writeValueAsBytes(jn))); redis.addRetainMessage(Topics.sanitize("a/b/c/d"), publish); publish = redis.getAllRetainMessages(Topics.sanitize("a/b/c/d")).get(0); assert publish.getMessageType() == MqttMessageType.PUBLISH; assert !publish.isDup(); assert publish.getQos() == MqttQoS.AT_LEAST_ONCE; assert !publish.isRetain(); assert publish.getVersion() == MqttVersion.MQTT_3_1_1; assert publish.getUserName().equals("user1"); assert publish.getPayload().getTopicName().equals("menuTopic"); jn = ObjectMapper.readTree(publish.getPayload().getPayload()); assert jn.get("menu").get("id").textValue().endsWith("file"); assert jn.get("menu").get("value").textValue().endsWith("File"); assert jn.get("menu").get("popup").get("menuItem").get(0).get("value").textValue().equals("New"); assert jn.get("menu").get("popup").get("menuItem").get(0).get("onclick").textValue().equals("CreateNewDoc()"); assert jn.get("menu").get("popup").get("menuItem").get(1).get("value").textValue().equals("Open"); assert jn.get("menu").get("popup").get("menuItem").get(1).get("onclick").textValue().equals("OpenDoc()"); assert jn.get("menu").get("popup").get("menuItem").get(2).get("value").textValue().equals("Close"); assert jn.get("menu").get("popup").get("menuItem").get(2).get("onclick").textValue().equals("CloseDoc()"); redis.removeAllRetainMessage(Topics.sanitize("a/b/c/d")); assert redis.getAllRetainMessages(Topics.sanitize("a/b/c/d")).size() == 0; } }
package phrase; import gnu.trove.TIntArrayList; import io.FileUtil; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import phrase.Corpus.Edge; /** * @brief context generates phrase * @author desaic * */ public class C2F { public int K; private int n_words, n_contexts, n_positions; public Corpus c; /**@brief * emit[tag][position][word] = p(word | tag, position in phrase) */ private double emit[][][]; /**@brief * pi[context][tag] = p(tag | context) */ private double pi[][]; public C2F(int numCluster, Corpus corpus){ K=numCluster; c=corpus; n_words=c.getNumWords(); n_contexts=c.getNumContexts(); //number of words in a phrase to be considered //currently the first and last word //if the phrase has length 1 //use the same word for two positions n_positions=2; emit=new double [K][n_positions][n_words]; pi=new double[n_contexts][K]; for(double [][]i:emit){ for(double []j:i){ arr.F.randomise(j); } } for(double []j:pi){ arr.F.randomise(j); } } /**@brief test * */ public static void main(String args[]){ String in="../pdata/canned.con"; String out="../pdata/posterior.out"; int numCluster=25; Corpus corpus = null; File infile = new File(in); try { System.out.println("Reading concordance from " + infile); corpus = Corpus.readFromFile(FileUtil.reader(infile)); corpus.printStats(System.out); } catch (IOException e) { System.err.println("Failed to open input file: " + infile); e.printStackTrace(); System.exit(1); } C2F c2f=new C2F(numCluster,corpus); int iter=20; double llh=0; for(int i=0;i<iter;i++){ llh=c2f.EM(); System.out.println("Iter"+i+", llh: "+llh); } File outfile = new File (out); try { PrintStream ps = FileUtil.printstream(outfile); c2f.displayPosterior(ps); // ps.println(); // c2f.displayModelParam(ps); ps.close(); } catch (IOException e) { System.err.println("Failed to open output file: " + outfile); e.printStackTrace(); System.exit(1); } } public double EM(){ double [][][]exp_emit=new double [K][n_positions][n_words]; double [][]exp_pi=new double[n_contexts][K]; double loglikelihood=0; for(int context=0; context< n_contexts; context++){ List<Edge> contexts = c.getEdgesForContext(context); for (int ctx=0; ctx<contexts.size(); ctx++){ Edge edge = contexts.get(ctx); double p[]=posterior(edge); double z = arr.F.l1norm(p); assert z > 0; loglikelihood += edge.getCount() * Math.log(z); arr.F.l1normalize(p); int count = edge.getCount(); //increment expected count TIntArrayList phrase= edge.getPhrase(); for(int tag=0;tag<K;tag++){ exp_emit[tag][0][phrase.get(0)]+=p[tag]*count; exp_emit[tag][1][phrase.get(phrase.size()-1)]+=p[tag]*count; exp_pi[context][tag]+=p[tag]*count; } } } //System.out.println("Log likelihood: "+loglikelihood); for(double [][]i:exp_emit){ for(double []j:i){ arr.F.l1normalize(j); } } emit=exp_emit; for(double []j:exp_pi){ arr.F.l1normalize(j); } pi=exp_pi; return loglikelihood; } public double[] posterior(Corpus.Edge edge) { double[] prob=Arrays.copyOf(pi[edge.getContextId()], K); TIntArrayList phrase = edge.getPhrase(); for(int tag=0;tag<K;tag++) prob[tag]*=emit[tag][0][phrase.get(0)] *emit[tag][1][phrase.get(phrase.size()-1)]; return prob; } public void displayPosterior(PrintStream ps) { for (Edge edge : c.getEdges()) { double probs[] = posterior(edge); arr.F.l1normalize(probs); // emit phrase ps.print(edge.getPhraseString()); ps.print("\t"); ps.print(edge.getContextString(true)); int t=arr.F.argmax(probs); ps.println(" ||| C=" + t); } } public void displayModelParam(PrintStream ps) { final double EPS = 1e-6; ps.println("P(tag|context)"); for (int i = 0; i < n_contexts; ++i) { ps.print(c.getContext(i)); for(int j=0;j<pi[i].length;j++){ if (pi[i][j] > EPS) ps.print("\t" + j + ": " + pi[i][j]); } ps.println(); } ps.println("P(word|tag,position)"); for (int i = 0; i < K; ++i) { for(int position=0;position<n_positions;position++){ ps.println("tag " + i + " position " + position); for(int word=0;word<emit[i][position].length;word++){ if (emit[i][position][word] > EPS) ps.print(c.getWord(word)+"="+emit[i][position][word]+"\t"); } ps.println(); } ps.println(); } } }
package raptor.connector.ics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import raptor.Raptor; import raptor.chat.Bugger; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.chat.Partnership; import raptor.chat.Seek; import raptor.chess.BughouseGame; import raptor.chess.FischerRandomBughouseGame; import raptor.chess.FischerRandomCrazyhouseGame; import raptor.chess.FischerRandomGame; import raptor.chess.Game; import raptor.chess.GameConstants; import raptor.chess.Result; import raptor.chess.SetupGame; import raptor.chess.Variant; import raptor.chess.WildGame; import raptor.chess.pgn.PgnHeader; import raptor.connector.Connector; import raptor.connector.ics.bughouse.BugWhoGParser; import raptor.connector.ics.bughouse.BugWhoPParser; import raptor.connector.ics.bughouse.BugWhoUParser; import raptor.connector.ics.chat.AbortRequestedEventParser; import raptor.connector.ics.chat.BugWhoAllEventParser; import raptor.connector.ics.chat.CShoutEventParser; import raptor.connector.ics.chat.ChallengeEventParser; import raptor.connector.ics.chat.ChannelTellEventParser; import raptor.connector.ics.chat.ChatEventParser; import raptor.connector.ics.chat.DrawOfferedEventParser; import raptor.connector.ics.chat.FingerEventParser; import raptor.connector.ics.chat.FollowingEventParser; import raptor.connector.ics.chat.HistoryEventParser; import raptor.connector.ics.chat.JournalEventParser; import raptor.connector.ics.chat.KibitzEventParser; import raptor.connector.ics.chat.NotificationEventParser; import raptor.connector.ics.chat.PartnerTellEventParser; import raptor.connector.ics.chat.PartnershipCreatedEventParser; import raptor.connector.ics.chat.PartnershipEndedEventParser; import raptor.connector.ics.chat.QTellParser; import raptor.connector.ics.chat.ShoutEventParser; import raptor.connector.ics.chat.TellEventParser; import raptor.connector.ics.chat.ToldEventParser; import raptor.connector.ics.chat.VariablesEventParser; import raptor.connector.ics.chat.WhisperEventParser; import raptor.connector.ics.game.message.B1Message; import raptor.connector.ics.game.message.G1Message; import raptor.connector.ics.game.message.GameEndMessage; import raptor.connector.ics.game.message.IllegalMoveMessage; import raptor.connector.ics.game.message.MovesMessage; import raptor.connector.ics.game.message.NoLongerExaminingGameMessage; import raptor.connector.ics.game.message.RemovingObsGameMessage; import raptor.connector.ics.game.message.Style12Message; import raptor.pref.PreferenceKeys; import raptor.service.ConnectorService; import raptor.service.GameService; import raptor.service.GameService.GameInfo; import raptor.service.GameService.Offer; import raptor.service.GameService.Offer.OfferType; import raptor.swt.UserInfoDialog; import raptor.util.RaptorLogger; import raptor.util.RaptorStringTokenizer; /** * An implementation of IcsParser that is both BICS and FICS friendly. */ public class IcsParser implements GameConstants { private static final RaptorLogger LOG = RaptorLogger .getLog(IcsParser.class); public static final int MAX_GAME_MESSAGE = 1000; protected B1Parser b1Parser; protected IcsConnector connector; protected G1Parser g1Parser; protected GameEndParser gameEndParser; protected IllegalMoveParser illegalMoveParser; protected MovesParser movesParser; protected NoLongerExaminingGameParser noLongerExaminingParser; protected List<ChatEventParser> nonGameEventParsers = new ArrayList<ChatEventParser>( 30); protected RemovingObsGameParser removingObsGameParser; protected FollowingEventParser followingParser; protected Style12Parser style12Parser; protected SoughtParser soughtParser; protected BugWhoGParser bugWhoGParser; protected BugWhoPParser bugWhoPParser; protected BugWhoUParser bugWhoUParser; protected UserInfoDialog fullUserInfoDialog; protected GameInfoParser gameInfoParser; /** * Used for BICS parsing. Bics sends a B1 right after you make a move then a * style 12 and another B1. This breaks Raptor, since it uses the game * object to keep track of the state. So it is currently being used to * ignore all B1s if the game is zh and its a BICS parser if they were not * preceded by a style 12. */ protected boolean containedStyle12; protected TakebackParser takebackParser; protected boolean isBicsParser = false; /** * A map keyed by game id. Used to temporarily store G1 messages until the * first style 12 message comes along. A new game requires a 12 message as * well as a G1. */ protected Map<String, G1Message> unprocessedG1Messages = new HashMap<String, G1Message>(); /** * A map keyed by game id. Used to temporarily store style12 messages from * newly examined games until the moves message comes along. From the moves * message you can identify the variant and create the game correctly. */ protected Map<String, Style12Message> exaimineGamesWaitingOnMoves = new HashMap<String, Style12Message>(); /** * A map keyed by game id. Used to temporarily store style12 messages from * newly examined games until the moves message comes along. From the moves * message you can identify the variant and create the game correctly. */ protected Map<String, B1Message> exaimineB1sWaitingOnMoves = new HashMap<String, B1Message>(); /** * BICS does'nt support the partner board in G1 messages so you have to * resort to this to link the bug games together. */ protected List<String> bugGamesWithoutBoard2 = new ArrayList<String>(10); private ChatEvent finger, var; public IcsParser(boolean isBicsParser) { this.isBicsParser = isBicsParser; gameEndParser = new GameEndParser(); b1Parser = new B1Parser(); g1Parser = new G1Parser(); illegalMoveParser = new IllegalMoveParser(); removingObsGameParser = new RemovingObsGameParser(); takebackParser = new TakebackParser(); noLongerExaminingParser = new NoLongerExaminingGameParser(); movesParser = new MovesParser(); followingParser = new FollowingEventParser(); style12Parser = new Style12Parser(); if (!isBicsParser) { soughtParser = new SoughtParser(); bugWhoGParser = new BugWhoGParser(); bugWhoPParser = new BugWhoPParser(); bugWhoUParser = new BugWhoUParser(); gameInfoParser = new GameInfoParser(); } nonGameEventParsers.add(new PartnerTellEventParser()); nonGameEventParsers.add(new ToldEventParser()); nonGameEventParsers.add(new ChannelTellEventParser()); nonGameEventParsers.add(new CShoutEventParser()); nonGameEventParsers.add(new ShoutEventParser()); nonGameEventParsers.add(new KibitzEventParser()); nonGameEventParsers.add(new TellEventParser()); nonGameEventParsers.add(new WhisperEventParser()); nonGameEventParsers.add(new QTellParser()); // Non tell types of events. nonGameEventParsers.add(new ChallengeEventParser()); nonGameEventParsers.add(new PartnershipCreatedEventParser()); nonGameEventParsers.add(new PartnershipEndedEventParser()); nonGameEventParsers.add(new FollowingEventParser()); nonGameEventParsers.add(new DrawOfferedEventParser()); nonGameEventParsers.add(new AbortRequestedEventParser()); nonGameEventParsers.add(new HistoryEventParser()); nonGameEventParsers.add(new JournalEventParser()); nonGameEventParsers.add(new FingerEventParser()); nonGameEventParsers.add(new BugWhoAllEventParser()); nonGameEventParsers.add(new NotificationEventParser()); nonGameEventParsers.add(new VariablesEventParser()); } public ChatEvent[] parse(String inboundMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Raw message in: " + inboundMessage); } List<ChatEvent> events = new ArrayList<ChatEvent>(5); // First handle the Moves message. String afterMovesMessage = parseMovesMessage(inboundMessage, events); if (LOG.isDebugEnabled()) { LOG.debug("After handling moves message: " + afterMovesMessage); } // Next handle game events. if (StringUtils.isNotBlank(afterMovesMessage)) { String afterGameEvents = parseGameEvents(afterMovesMessage); if (LOG.isDebugEnabled()) { LOG.debug("After handling game events: " + afterGameEvents); } // Now process what is left over as chat events. // Don't send it if its only a prompt. if (StringUtils.isNotBlank(afterGameEvents) && !afterGameEvents.trim().equals( connector.getContext().getPrompt())) { // Now process bug who events. ChatEvent bugWhoEvent = processBugWho(afterGameEvents); if (bugWhoEvent == null) { // Now process sought events. ChatEvent soughtEvent = processSought(afterGameEvents); if (soughtEvent == null) { ChatEvent gameInfoEvent = processGameInfo(afterGameEvents); if (gameInfoEvent == null) { // Its not a game,gameInfo,bugwho,or sought event so // now try the other parsers. for (ChatEventParser parser : nonGameEventParsers) { ChatEvent event = parser.parse(afterGameEvents); if (event != null) { events.add(event); break; } } // Its an unhandled event if (events.isEmpty()) { events.add(new ChatEvent(null, ChatType.UNKNOWN, afterGameEvents)); } } else { events.add(gameInfoEvent); } } else { events.add(soughtEvent); } } else { events.add(bugWhoEvent); } } } if (fullUserInfoDialog != null) { for (ChatEvent event : events) { if (event.getType() == ChatType.FINGER) { LOG.debug("Received finger for usinfo: " + event.getMessage()); finger = event; } else if (event.getType() == ChatType.VARIABLES) { LOG.debug("Received var for usinfo: " + event.getMessage()); var = event; } } if (finger != null && events.contains(finger)) events.remove(finger); if (var != null && events.contains(var)) events.remove(var); if (finger != null && var != null) { UserInfoParser pars = new UserInfoParser(finger.getMessage(), var.getMessage()); LOG.debug("Parser output: " + pars.getOnFor() + " " + pars.getInterface()); fullUserInfoDialog.updateData(pars.getOnFor(), pars.getInterface(), "", finger.getMessage()); setParseFullUserInfo(null); } } return events.toArray(new ChatEvent[0]); } /** * Invoked when a user is examining a game and it becomes a setup position. */ public void processExaminedGameBecameSetup() { Game[] activeGames = connector.getGameService().getAllActiveGames(); for (Game game : activeGames) { if (game.isInState(Game.EXAMINING_STATE)) { if (LOG.isDebugEnabled()) { LOG.debug("Handling transition from examined game to bsetup."); } SetupGame setupGame = new SetupGame(); game.overwrite(setupGame, true); // Set all the drop pieces. setupGame.setPieceCount(WHITE, PAWN, 1); setupGame.setPieceCount(WHITE, KNIGHT, 1); setupGame.setPieceCount(WHITE, BISHOP, 1); setupGame.setPieceCount(WHITE, ROOK, 1); setupGame.setPieceCount(WHITE, QUEEN, 1); setupGame.setPieceCount(WHITE, KING, 1); setupGame.setPieceCount(BLACK, PAWN, 1); setupGame.setPieceCount(BLACK, KNIGHT, 1); setupGame.setPieceCount(BLACK, BISHOP, 1); setupGame.setPieceCount(BLACK, ROOK, 1); setupGame.setPieceCount(BLACK, QUEEN, 1); setupGame.setPieceCount(BLACK, KING, 1); // Adjust the state since it was cleared after the overwrite. setupGame.clearState(Game.EXAMINING_STATE); setupGame.addState(Game.SETUP_STATE); setupGame.addState(Game.DROPPABLE_STATE); connector.getGameService().addGame(setupGame); connector.getGameService().fireExaminedGameBecameSetup( game.getId()); break; } } } public void setConnector(IcsConnector connector) { this.connector = connector; } /** * If a game is being played on any connector and the preference * BOARD_IGNORE_OBSERVED_GAMES_IF_PLAYING is set then this will veto the * games creation. */ public boolean vetoGameCreation(Game game, G1Message g1Message) { boolean result = false; if (game.isInState(Game.OBSERVING_STATE) && Raptor .getInstance() .getPreferences() .getBoolean( PreferenceKeys.BOARD_IGNORE_OBSERVED_GAMES_IF_PLAYING) && (!isBughouse(game) || (isBughouse(game) && !connector .getGameService().isManaging(g1Message.parterGameId)))) { for (Connector connector : ConnectorService.getInstance() .getConnectors()) { if (connector.isLoggedInUserPlayingAGame()) { result = true; break; } } } return result; } protected void adjustBughouseHeadersAndFollowPartnersGamesForBics( Game game, Style12Message message, GameService service) { // BICS currently does'nt set a partner id so you have // do this. if (bugGamesWithoutBoard2.isEmpty()) { if (observePartnerBoardForGame(game)) { bugGamesWithoutBoard2.add(message.gameId); connector.sendMessage("pobserve " + (message.isWhiteOnTop ? message.blackName : message.whiteName), true); } } else { Game otherBoard = service.getGame(bugGamesWithoutBoard2.get(0)); if (otherBoard == null) { connector .onError( "Could not find game with id " + bugGamesWithoutBoard2.get(0) + " in the GameService. Please get BICS to add a partner game id to its G1 message.\n" + " You can complain to both johnthegreat and aramen.", new Exception()); } else { ((BughouseGame) game).setOtherBoard((BughouseGame) otherBoard); ((BughouseGame) otherBoard).setOtherBoard((BughouseGame) game); if (StringUtils.defaultIfEmpty( otherBoard.getHeader(PgnHeader.WhiteOnTop), "0") .equals("0")) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } bugGamesWithoutBoard2.clear(); } } protected void adjustBughouseHeadersAndFollowPartnersGamesForFics( Game game, G1Message g1Message, Style12Message message, GameService service) { if (!connector.getGameService().isManaging(g1Message.parterGameId)) { if (observePartnerBoardForGame(game)) { connector .sendMessage("observe " + g1Message.parterGameId, true); } } else { Game otherBoard = service.getGame(g1Message.parterGameId); ((BughouseGame) game).setOtherBoard((BughouseGame) otherBoard); ((BughouseGame) otherBoard).setOtherBoard((BughouseGame) game); if (StringUtils.defaultIfEmpty( otherBoard.getHeader(PgnHeader.WhiteOnTop), "0") .equals("0")) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } } protected void adjustWhiteOnTopHeader(Game game, Style12Message message) { if (message.isWhiteOnTop) { // Respect the flip variable. game.setHeader(PgnHeader.WhiteOnTop, "1"); } else if (StringUtils.equalsIgnoreCase(message.whiteName, connector.userName)) { game.setHeader(PgnHeader.WhiteOnTop, "0"); } else if (StringUtils.equalsIgnoreCase(message.whiteName, connector.userFollowing)) { game.setHeader(PgnHeader.WhiteOnTop, "0"); } else if (StringUtils.equalsIgnoreCase(message.blackName, connector.userName)) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else if (StringUtils.equalsIgnoreCase(message.blackName, connector.userFollowing)) { game.setHeader(PgnHeader.WhiteOnTop, "1"); } else { game.setHeader(PgnHeader.WhiteOnTop, "0"); } } protected boolean isBughouse(Game game) { return game.getVariant() == Variant.bughouse || game.getVariant() == Variant.fischerRandomBughouse; } protected boolean isCrazyhouse(Game game) { return game.getVariant() == Variant.crazyhouse || game.getVariant() == Variant.fischerRandomCrazyhouse; } protected boolean observePartnerBoardForGame(Game game) { boolean result = false; // This lets you observe if you are simuled but obsing another game, // otherwise // it wont let you observe. if (connector.isSimulBugConnector()) { String white = IcsUtils .stripTitles(game.getHeader(PgnHeader.White)); String black = IcsUtils .stripTitles(game.getHeader(PgnHeader.Black)); if (StringUtils.equalsIgnoreCase(white, connector.getUserName()) || StringUtils.equalsIgnoreCase(white, connector.getSimulBugPartnerName()) || StringUtils.equalsIgnoreCase(black, connector.getUserName()) || StringUtils.equalsIgnoreCase(black, connector.getSimulBugPartnerName())) { return false; } } if (game.isInState(Game.PLAYING_STATE)) { result = connector.getPreferences().getBoolean( PreferenceKeys.BUGHOUSE_PLAYING_OPEN_PARTNER_BOARD); } else if (game.isInState(Game.OBSERVING_STATE)) { result = connector.getPreferences().getBoolean( PreferenceKeys.BUGHOUSE_OBSERVING_OPEN_PARTNER_BOARD); } return result; } /** * Parses and removes all of the game events from inboundEvent. Adjusts the * games in service. Returns a String with the game events removed. */ protected String parseGameEvents(String inboundMessage) { containedStyle12 = false; if (inboundMessage.length() > MAX_GAME_MESSAGE) { return inboundMessage; } else { if (LOG.isDebugEnabled()) { LOG.debug("Raw message in: " + inboundMessage); } boolean trimAtEnd = false; StringBuilder result = new StringBuilder(inboundMessage.length()); RaptorStringTokenizer tok = new RaptorStringTokenizer( inboundMessage, "\n"); while (tok.hasMoreTokens()) { String line = tok.nextToken(); if (LOG.isDebugEnabled()) { LOG.debug("Processing raw line: " + line); } G1Message g1Message = g1Parser.parse(line); if (g1Message != null) { process(g1Message, connector.getGameService()); trimAtEnd = true; continue; } Style12Message style12Message = style12Parser.parse(line); if (style12Message != null) { process(style12Message, connector.getGameService(), inboundMessage); containedStyle12 = true; continue; } B1Message b1Message = b1Parser.parse(line); if (b1Message != null) { process(b1Message, connector.getGameService()); continue; } GameEndMessage gameEndMessage = gameEndParser.parse(line); if (gameEndMessage != null) { process(gameEndMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); trimAtEnd = true; continue; } IllegalMoveMessage illegalMoveMessage = illegalMoveParser .parse(line); if (illegalMoveMessage != null) { process(illegalMoveMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } RemovingObsGameMessage removingObsGameMessage = removingObsGameParser .parse(line); if (removingObsGameMessage != null) { process(removingObsGameMessage, inboundMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } if (processPendInfo(line)) { trimAtEnd = true; continue; } NoLongerExaminingGameMessage noLonerExaminingGameMessage = noLongerExaminingParser .parse(line); if (noLonerExaminingGameMessage != null) { process(noLonerExaminingGameMessage, connector.getGameService()); result.append(line + (tok.hasMoreTokens() ? "\n" : "")); continue; } takebackParser.parse(line); ChatEvent followingEvent = followingParser.parse(line); if (followingEvent != null && followingEvent.getType() == ChatType.FOLLOWING) { connector.setUserFollowing(followingEvent.getSource()); // Don't eat this line. Let it be appended so the event gets // published. // It is just being used here to set the user we are // following so white on top // can be set properly. } if (line.startsWith("Entering setup mode.") && !inboundMessage.contains("<12>")) { processExaminedGameBecameSetup(); } result.append(line + (tok.hasMoreTokens() ? "\n" : "")); } return trimAtEnd ? result.toString().trim() : result.toString(); } } /** * Parses out the Moves message from inboundEvent. It is assumed moves * messages will never contain other messages. * * @param inboundEvent * The inbound message. * @param events * The chatEvents */ protected String parseMovesMessage(String inboundMessage, List<ChatEvent> events) { MovesMessage movesMessage = movesParser.parse(inboundMessage); if (movesMessage != null) { process(movesMessage, connector.getGameService()); events.add(new ChatEvent(null, ChatType.MOVES, inboundMessage)); return null; } else { return inboundMessage; } } protected void process(B1Message message, GameService service) { if (LOG.isDebugEnabled()) { LOG.debug("Processing b1: " + message); } Game game = service.getGame(message.gameId); if (game == null) { if (exaimineGamesWaitingOnMoves.containsKey(message.gameId)) { exaimineB1sWaitingOnMoves.put(message.gameId, message); } else { if (LOG.isInfoEnabled()) { LOG.info("Received B1 for a game not in the GameService. " + "You could be ignoring a bug or zh game and get this."); } } } else { if (isBicsParser && isCrazyhouse(game) && !containedStyle12) { // See the documentation on the variable for an explanation of // why this is done. return; } updateGameForB1(game, message); service.fireDroppablePiecesChanged(message.gameId); } } protected void process(G1Message message, GameService service) { unprocessedG1Messages.put(message.gameId, message); } protected void process(GameEndMessage message, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { // Bug game other boards might not be in the game service. // So no need to send a connector.onError. } else { switch (message.type) { case GameEndMessage.ABORTED: case GameEndMessage.ADJOURNED: case GameEndMessage.UNDETERMINED: game.setHeader(PgnHeader.Result, Result.UNDETERMINED.getDescription()); break; case GameEndMessage.BLACK_WON: game.setHeader(PgnHeader.Result, Result.BLACK_WON.getDescription()); break; case GameEndMessage.WHITE_WON: game.setHeader(PgnHeader.Result, Result.WHITE_WON.getDescription()); break; case GameEndMessage.DRAW: game.setHeader(PgnHeader.Result, Result.DRAW.getDescription()); break; default: LOG.error("Undetermined game end type. " + message); break; } game.setHeader(PgnHeader.ResultDescription, message.description); game.setHeader(PgnHeader.PlyCount, "" + game.getHalfMoveCount()); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } if (LOG.isDebugEnabled()) { LOG.debug("Processed game end: " + message); } } protected void process(IllegalMoveMessage message, GameService service) { // Except for simuls you can only place one game at a time. // For now ignore simuls and just send this to the first active game // found in the game service. Game[] allActive = service.getAllActiveGames(); for (Game game : allActive) { service.fireIllegalMove(game.getId(), message.move); } if (LOG.isDebugEnabled()) { LOG.debug("Processed illegal move: " + message); } } protected void process(MovesMessage message, GameService service) { if (LOG.isDebugEnabled()) { LOG.debug("Processing movesMessage: " + message); } Game game = service.getGame(message.gameId); if (game == null) { // Check to see if this was for a newly examined game. Style12Message style12 = exaimineGamesWaitingOnMoves .get(message.gameId); if (style12 != null) { exaimineGamesWaitingOnMoves.remove(message.gameId); game = IcsUtils.createExaminedGame(style12, message); B1Message b1Message = exaimineB1sWaitingOnMoves.get(game .getId()); if (b1Message != null) { updateGameForB1(game, b1Message); exaimineB1sWaitingOnMoves.remove(game.getId()); } service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, style12.isWhiteOnTop ? "1" : "0"); service.fireGameCreated(game.getId()); if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } } else { LOG.warn("Received a MovesMessage for a game not being managed. This can occur if the user manually types in the moves command. " + message.gameId); } } else { Style12Message style12 = exaimineGamesWaitingOnMoves .get(message.gameId); if (style12 != null) { // Both observed games becoming examined games and // setup games becoming examined games will flow through here. // Distinguishes between setup and observed. boolean isSetup = game.isInState(Game.SETUP_STATE); exaimineGamesWaitingOnMoves.remove(message.gameId); game = IcsUtils.createExaminedGame(style12, message); B1Message b1Message = exaimineB1sWaitingOnMoves.get(game .getId()); if (b1Message != null) { updateGameForB1(game, b1Message); exaimineB1sWaitingOnMoves.remove(game.getId()); } service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, style12.isWhiteOnTop ? "1" : "0"); if (isSetup) { if (LOG.isDebugEnabled()) { LOG.debug("Firing fireSetupGameBecameExamined."); } service.fireSetupGameBecameExamined(game.getId()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Firing fireObservedGameBecameExamined."); } // Need a delay for puzzlebot sometimes it opens too fast. try { Thread.sleep(250); } catch (InterruptedException ie) { } service.fireObservedGameBecameExamined(game.getId()); } } else { IcsUtils.updateGamesMoves(game, message); service.fireGameMovesAdded(game.getId()); } } } protected void process(NoLongerExaminingGameMessage message, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { connector.onError( "Received no longer examining game message for a game not in the GameService. " + message, new Exception()); } else { game.setHeader(PgnHeader.ResultDescription, "Interrupted by unexamine."); game.setHeader(PgnHeader.Result, Result.UNDETERMINED.getDescription()); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } if (LOG.isDebugEnabled()) { LOG.debug("Processed no longer examining game message: " + message); } } protected void process(RemovingObsGameMessage message, String entireMessage, GameService service) { Game game = service.getGame(message.gameId); if (game == null) { if (LOG.isDebugEnabled()) { LOG.debug("Received removing obs game message for a game not in the GameService." + message); } } else if (!entireMessage.contains("has made you an examiner of game ")) { boolean processUnobserve = true; if (game.getVariant() == Variant.bughouse) { BughouseGame bughouseGame = (BughouseGame) game; if ((bughouseGame.getOtherBoard().getState() & Game.ACTIVE_STATE) != 0) { bughouseGame.setHeader( PgnHeader.ResultDescription, bughouseGame.getOtherBoard().getHeader( PgnHeader.ResultDescription)); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); processUnobserve = false; } } if (processUnobserve) { game.setHeader(PgnHeader.ResultDescription, "Interrupted by unobserve"); game.setHeader(PgnHeader.Result, Result.UNDETERMINED.getDescription()); game.clearState(Game.ACTIVE_STATE | Game.IS_CLOCK_TICKING_STATE); game.addState(Game.INACTIVE_STATE); service.fireGameInactive(game.getId()); service.removeGame(game); takebackParser.clearTakebackMessages(game.getId()); } } if (LOG.isDebugEnabled()) { LOG.debug("Processed removing obs game: " + message); } } protected void process(Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing style 12: " + message); } long startTime = System.currentTimeMillis(); Game game = service.getGame(message.gameId); if (game != null) { if (game.isInState(Game.SETUP_STATE)) { processStyle12SetupAdjustment(game, message, service, entireMessage); } else { processStyle12Adjustment(game, message, service, entireMessage); } } else { G1Message g1Message = unprocessedG1Messages.get(message.gameId); if (g1Message == null) { processStyle12Creation(message, service, entireMessage); } else { processG1Creation(g1Message, message, service, entireMessage); } } if (LOG.isDebugEnabled()) { LOG.debug("Processed style 12: " + message + " in " + (System.currentTimeMillis() - startTime)); } } protected ChatEvent processBugWho(String message) { ChatEvent result = null; // Bics bugwho is different. Someone needs to write bics bugwho to get // it working. if (bugWhoUParser != null) { Bugger[] buggers = bugWhoUParser.parse(message); if (buggers == null) { Partnership[] partnerships = bugWhoPParser.parse(message); if (partnerships == null) { raptor.chat.BugGame[] bugGames = bugWhoGParser .parse(message); if (bugGames != null) { connector.getBughouseService().setGamesInProgress( bugGames); result = new ChatEvent(null, ChatType.BUGWHO_GAMES, message); } } else { connector.getBughouseService().setAvailablePartnerships( partnerships); result = new ChatEvent(null, ChatType.BUGWHO_AVAILABLE_TEAMS, message); } } else { connector.getBughouseService().setUnpartneredBuggers(buggers); result = new ChatEvent(null, ChatType.BUGWHO_UNPARTNERED_BUGGERS, message); } } return result; } /** * Observed/Playing games starts flow here (i.e. All games that contain a G1 * message) */ protected void processG1Creation(G1Message g1Message, Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing new obs/playing game."); } unprocessedG1Messages.remove(message.gameId); Game game = IcsUtils.createGame(g1Message, message, isBicsParser); IcsUtils.updateNonPositionFields(game, message); IcsUtils.updatePosition(game, message); IcsUtils.verifyLegal(game); if (game instanceof FischerRandomGame) { ((FischerRandomGame) game).initialPositionIsSet(); } else if (game instanceof FischerRandomCrazyhouseGame) { ((FischerRandomCrazyhouseGame) game).initialPositionIsSet(); } else if (game instanceof FischerRandomBughouseGame) { ((FischerRandomBughouseGame) game).initialPositionIsSet(); } else if (game instanceof WildGame) { ((WildGame) game).initialPositionIsSet(); } if (game.getVariant() == Variant.wild || game.getVariant() == Variant.fischerRandom) { game.setHeader(PgnHeader.FEN, game.toFen()); } if (vetoGameCreation(game, g1Message)) { connector.publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Vetoing observing game " + game.getId() + " because you are playing a game.", null)); connector.onUnobserve(game); } else { service.addGame(game); adjustWhiteOnTopHeader(game, message); if (isBughouse(game)) { /** * BICS does'nt have the partner game id in the G1 so you have * to handle BICS and FICS differently. */ if (g1Message.parterGameId.equals("0")) { adjustBughouseHeadersAndFollowPartnersGamesForBics(game, message, service); } else { adjustBughouseHeadersAndFollowPartnersGamesForFics(game, g1Message, message, service); } } if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } service.fireGameCreated(game.getId()); /** * Send a request for the moves. */ if (message.fullMoveNumber > 1 || message.fullMoveNumber == 1 && !message.isWhitesMoveAfterMoveIsMade) { connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } } } protected ChatEvent processGameInfo(String message) { ChatEvent result = null; if (gameInfoParser != null) { GameInfo[] gameInfos = gameInfoParser.parse(message); if (gameInfos != null) { connector.getGameService().fireGameInfoChanged(gameInfos); result = new ChatEvent(null, ChatType.GAMES, message); } } return result; } /** * Handles the fics pendinfo messages. * * @param line * THe line being parsed. * @return True if it was a pendinfo message and was processed, false * otherwise. */ protected boolean processPendInfo(String line) { if (line.startsWith("<pf>")) { RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); Offer offer = new Offer(); offer.setReceiving(true); tok.nextToken(); offer.setId(tok.nextToken()); tok.nextToken(); offer.setSource(tok.nextToken()); tok.nextToken(); String type = tok.nextToken(); if (type.equals("partner")) { offer.setType(OfferType.partner); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclinable(true); offer.setDeclineAllCommand("decline t all"); offer.setCommand("accept " + offer.getId()); offer.setDescription("Accept partnership offer from " + offer.getSource()); offer.setDeclineDescription("Decline partnership offer from " + offer.getSource()); } else if (type.equals("match")) { offer.setType(OfferType.match); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); tok.nextToken(); String challengeDescription = tok.getWhatsLeft(); offer.setDeclineDescription("Decline challenge " + challengeDescription); offer.setDescription("Accept challenge " + challengeDescription); } else if (type.equals("draw")) { offer.setType(OfferType.draw); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDeclineDescription("Decline draw offer from " + offer.getSource()); offer.setDescription("Accept draw offer from " + offer.getSource()); } else if (type.equals("adjourn")) { offer.setType(OfferType.adjourn); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDescription("Accept adjourn offer from " + offer.getSource()); offer.setDeclineDescription("Decline adjourn offer from " + offer.getSource()); } else if (type.equals("abort")) { offer.setType(OfferType.abort); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); offer.setDescription("Accept abort offer from " + offer.getSource()); offer.setDeclineDescription("Decline abort offer from " + offer.getSource()); } else if (type.equals("takeback")) { offer.setType(OfferType.takeback); offer.setCommand("accept " + offer.getId()); offer.setDeclinable(true); offer.setDeclineCommand("decline " + offer.getId()); offer.setDeclineAllCommand("decline t all"); tok.nextToken(); String taokebackMoves = tok.getWhatsLeft(); offer.setDescription("Accept takeback " + taokebackMoves + " halfmoves offer from " + offer.getSource()); offer.setDeclineDescription("Decline takeback " + taokebackMoves + " halfmoves offer from " + offer.getSource()); } else { return true; } connector.getGameService().fireOfferReceived(offer); return true; } else if (line.startsWith("<pt>")) { RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); Offer offer = new Offer(); offer.setReceiving(false); tok.nextToken(); offer.setId(tok.nextToken()); tok.nextToken(); offer.setSource(tok.nextToken()); tok.nextToken(); String type = tok.nextToken(); if (type.equals("partner")) { offer.setType(OfferType.partner); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw partnership offer to " + offer.getSource()); } else if (type.equals("match")) { offer.setType(OfferType.match); offer.setCommand("withdraw " + offer.getId()); tok.nextToken(); offer.setDescription("Withdraw challenge " + tok.getWhatsLeft()); } else if (type.equals("draw")) { offer.setType(OfferType.draw); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw draw offer to " + offer.getSource()); } else if (type.equals("adjourn")) { offer.setType(OfferType.adjourn); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw adjourn offer to " + offer.getSource()); } else if (type.equals("abort")) { offer.setType(OfferType.abort); offer.setCommand("withdraw " + offer.getId()); offer.setDescription("Withdraw abort offer to " + offer.getSource()); } else if (type.equals("takeback")) { offer.setType(OfferType.takeback); offer.setCommand("withdraw " + offer.getId()); tok.nextToken(); offer.setDescription("Withdraw takeback " + tok.getWhatsLeft() + " halfmoves offer to " + offer.getSource()); } else { return true; } connector.getGameService().fireOfferReceived(offer); return true; } else if (line.startsWith("<pr>")) { RaptorStringTokenizer tok = new RaptorStringTokenizer(line, " =", true); tok.nextToken(); connector.getGameService().fireOfferRemoved(tok.nextToken()); return true; } return false; } protected ChatEvent processSought(String message) { ChatEvent result = null; if (soughtParser != null) { Seek[] seeks = soughtParser.parse(message); if (seeks != null) { connector.getSeekService().setSeeks(seeks); result = new ChatEvent(null, ChatType.SEEKS, message); } } return result; } /** * Playing,Observing,Examining style 12 adjustments flow through here. */ protected void processStyle12Adjustment(Game game, Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing obs/playing/ex position move."); } if (entireMessage.contains("- entering examine mode.")) { if (LOG.isDebugEnabled()) { LOG.debug("Handling bsetup to examine mode transition."); } // Handles one case of the transition from bsetup mode to examine // mode. Game examineGame = IcsUtils.createGame(message, entireMessage); if (message.relation == Style12Message.EXAMINING_GAME_RELATION && !examineGame.isInState(Game.SETUP_STATE)) { exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } } else if (game.isInState(Game.OBSERVING_EXAMINED_STATE) && message.relation == Style12Message.EXAMINING_GAME_RELATION) { if (LOG.isDebugEnabled()) { LOG.debug("Handling observer became examiner transition."); } // Handles a user becoming an examiner of a game he/she was // observing. exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else if (game.isInState(Game.EXAMINING_STATE) && entireMessage.contains("Entering setup mode.\n")) { if (LOG.isDebugEnabled()) { LOG.debug("Handling examined game became setup game transition."); } // Handles an examined game becoming a setup game. game = IcsUtils.createGame(message, entireMessage); service.addGame(game); service.fireExaminedGameBecameSetup(game.getId()); } else { // No game state transition occured. if (LOG.isDebugEnabled()) { LOG.debug("No state transitions occured. Processing style12 on existing game."); } // Takebacks may have effected the state of the game so first // adjsut to those. // adjust takebacks will also do nothing on refreshes and end // games // but will return true. if (!IcsUtils.adjustToTakebacks(game, message, connector)) { if (LOG.isDebugEnabled()) { LOG.debug("Making move in obs/playing position."); } // Now add the move to the game. // Game Ends and Refreshes dont involve adding a move. if (IcsUtils.addCurrentMove(game, message)) { if (LOG.isDebugEnabled()) { LOG.debug("Position was a move firing state changed."); } service.fireGameStateChanged(message.gameId, true); } else { // I'm not sure this block of code is ever hit // anymore. // TO DO: look at removing it. if (LOG.isDebugEnabled()) { LOG.debug("Position was not a move firing state changed."); } service.fireGameStateChanged(message.gameId, false); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adjusted for takebacks."); } service.fireGameStateChanged(message.gameId, false); } } } /** * Examined/Bsetup/Isolated Positions game starts flow through here (i.e. * All games that didnt have a G1 message) */ protected void processStyle12Creation(Style12Message message, GameService service, String entireMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Processing new ex or bsetup game."); } if (message.relation == Style12Message.OBSERVING_EXAMINED_GAME_RELATION || message.relation == Style12Message.OBSERVING_GAME_RELATION) { // This is probably from a game that was vetoed because the user was // playing. // Just return the unobserve has'nt taken effect yet. if (LOG.isInfoEnabled()) { LOG.info("A style 12 message was received for an observed game " + "that wasnt being managed. Assuming this was because you " + "are playing a game and have the ignore observed games if playing " + "preference enabled."); } return; } Game game = IcsUtils.createGame(message, entireMessage); if (message.relation == Style12Message.EXAMINING_GAME_RELATION && !game.isInState(Game.SETUP_STATE)) { exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else { service.addGame(game); // Respect the flip variable if its set. game.setHeader(PgnHeader.WhiteOnTop, message.isWhiteOnTop ? "1" : "0"); service.fireGameCreated(game.getId()); if (LOG.isDebugEnabled()) { LOG.debug("Firing game created."); } } } /** * Setup style 12 adjustments flow through here. */ protected void processStyle12SetupAdjustment(Game game, Style12Message message, GameService service, String entireMessage) { // Examined/BSetup/obs ex moves flow through here. if (LOG.isDebugEnabled()) { LOG.debug("Processing bsetup or examine position move."); } if (entireMessage .contains("Game is validated - entering examine mode.\n")) { // Add this game to the games waiting on moves. // Send a moves message. // Transition from BSETUP to EXAMINE when moves arrives. exaimineGamesWaitingOnMoves.put(game.getId(), message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); } else { // Clear out the game and start over. // There is no telling what happened // in a setup or examine game. IcsUtils.resetGame(game, message); service.fireGameStateChanged(message.gameId, true); } } protected void updateGameForB1(Game game, B1Message message) { if (isBughouse(game) && (game.isInState(Game.EXAMINING_STATE) || game .isInState(Game.OBSERVING_EXAMINED_STATE))) { // On Fics when examining a bug game you don't get pieces. // To handle all the issues around that just set 1 of everything. game.setDropCount(WHITE, PAWN, 1); game.setDropCount(WHITE, QUEEN, 1); game.setDropCount(WHITE, ROOK, 1); game.setDropCount(WHITE, KNIGHT, 1); game.setDropCount(WHITE, BISHOP, 1); game.setDropCount(BLACK, PAWN, 1); game.setDropCount(BLACK, QUEEN, 1); game.setDropCount(BLACK, ROOK, 1); game.setDropCount(BLACK, KNIGHT, 1); game.setDropCount(BLACK, BISHOP, 1); } else { for (int i = 1; i < message.whiteHoldings.length; i++) { game.setDropCount(WHITE, i, message.whiteHoldings[i]); } for (int i = 1; i < message.blackHoldings.length; i++) { game.setDropCount(BLACK, i, message.blackHoldings[i]); } } } public synchronized void setParseFullUserInfo(UserInfoDialog b) { fullUserInfoDialog = b; if (b == null) { finger = null; var = null; } } }
package org.neo4j.kernel; import java.io.IOException; import java.io.Serializable; import java.nio.channels.ReadableByteChannel; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.helpers.Pair; import org.neo4j.index.IndexService; import org.neo4j.index.lucene.LuceneIndexService; import org.neo4j.kernel.ha.BrokerFactory; import org.neo4j.kernel.ha.HaCommunicationException; import org.neo4j.kernel.ha.MasterIdGeneratorFactory; import org.neo4j.kernel.ha.MasterServer; import org.neo4j.kernel.ha.SlaveIdGenerator.SlaveIdGeneratorFactory; import org.neo4j.kernel.ha.SlaveLockManager.SlaveLockManagerFactory; import org.neo4j.kernel.ha.SlaveRelationshipTypeCreator; import org.neo4j.kernel.ha.SlaveTxIdGenerator.SlaveTxIdGeneratorFactory; import org.neo4j.kernel.ha.SlaveTxRollbackHook; import org.neo4j.kernel.ha.ZooKeeperLastCommittedTxIdSetter; import org.neo4j.kernel.ha.zookeeper.ZooKeeperBroker; import org.neo4j.kernel.ha.zookeeper.ZooKeeperException; import org.neo4j.kernel.impl.ha.Broker; import org.neo4j.kernel.impl.ha.Response; import org.neo4j.kernel.impl.ha.ResponseReceiver; import org.neo4j.kernel.impl.ha.SlaveContext; import org.neo4j.kernel.impl.ha.TransactionStream; import org.neo4j.kernel.impl.transaction.XaDataSourceManager; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; public class HighlyAvailableGraphDatabase implements GraphDatabaseService, ResponseReceiver { public static final String CONFIG_KEY_HA_MACHINE_ID = "ha.machine_id"; public static final String CONFIG_KEY_HA_ZOO_KEEPER_SERVERS = "ha.zoo_keeper_servers"; public static final String CONFIG_KEY_HA_SERVERS = "ha.servers"; public static final String CONFIG_KEY_HA_PULL_INTERVAL = "ha.pull_interval"; private final String storeDir; private final Map<String, String> config; private final BrokerFactory brokerFactory; private Broker broker; private EmbeddedGraphDbImpl localGraph; private IndexService localIndex; private final int machineId; private MasterServer masterServer; private AtomicBoolean reevaluatingMyself = new AtomicBoolean(); private UpdatePuller updatePuller; // Just "cached" instances which are used internally here private XaDataSourceManager localDataSourceManager; /** * Will instantiate its own ZooKeeper broker */ public HighlyAvailableGraphDatabase( String storeDir, Map<String, String> config ) { this( storeDir, config, defaultBrokerFactory( storeDir, config ) ); } private static BrokerFactory defaultBrokerFactory( final String storeDir, final Map<String, String> config ) { return new BrokerFactory() { public Broker create() { return instantiateBroker( storeDir, config ); } }; } /** * Only for testing */ public HighlyAvailableGraphDatabase( String storeDir, Map<String, String> config, BrokerFactory brokerFactory ) { this.storeDir = storeDir; this.config = config; this.brokerFactory = brokerFactory; this.machineId = getMachineIdFromConfig( config ); this.broker = brokerFactory.create(); reevaluateMyself(); } private static Broker instantiateBroker( String storeDir, Map<String, String> config ) { return new ZooKeeperBroker( storeDir, getMachineIdFromConfig( config ), getZooKeeperServersFromConfig( config ), getHaServersFromConfig( config ) ); } private static Map<Integer, String> getHaServersFromConfig( Map<?, ?> config ) { String value = config.get( CONFIG_KEY_HA_SERVERS ).toString(); Map<Integer, String> result = new HashMap<Integer, String>(); for ( String part : value.split( Pattern.quote( "," ) ) ) { String[] tokens = part.trim().split( Pattern.quote( "=" ) ); result.put( new Integer( tokens[0] ), tokens[1] ); } return result; } private static String getZooKeeperServersFromConfig( Map<String, String> config ) { return config.get( CONFIG_KEY_HA_ZOO_KEEPER_SERVERS ); } private static int getMachineIdFromConfig( Map<String, String> config ) { // Fail fast if null return Integer.parseInt( config.get( CONFIG_KEY_HA_MACHINE_ID ) ); } public Broker getBroker() { return this.broker; } public void pullUpdates() { try { receive( broker.getMaster().pullUpdates( getSlaveContext() ) ); } catch ( ZooKeeperException e ) { somethingIsWrong( e ); throw e; } catch ( HaCommunicationException e ) { somethingIsWrong( e ); throw e; } } public Config getConfig() { return this.localGraph.getConfig(); } protected void reevaluateMyself() { if ( !reevaluatingMyself.compareAndSet( false, true ) ) { return; } try { broker.invalidateMaster(); boolean brokerSaysIAmMaster = brokerSaysIAmMaster(); boolean iAmCurrentlyMaster = masterServer != null; if ( brokerSaysIAmMaster ) { if ( !iAmCurrentlyMaster ) { shutdown(); } if ( this.localGraph == null ) { startAsMaster(); } } else { if ( iAmCurrentlyMaster ) { shutdown(); } if ( this.localGraph == null ) { startAsSlave(); } } this.localDataSourceManager = localGraph.getConfig().getTxModule().getXaDataSourceManager(); } finally { reevaluatingMyself.set( false ); } } private void startAsSlave() { this.broker = brokerFactory.create(); this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, new SlaveLockManagerFactory( broker, this ), new SlaveIdGeneratorFactory( broker, this ), new SlaveRelationshipTypeCreator( broker, this ), new SlaveTxIdGeneratorFactory( broker, this ), new SlaveTxRollbackHook( broker, this ), new ZooKeeperLastCommittedTxIdSetter( broker ) ); instantiateIndexIfNeeded(); } private void startAsMaster() { this.broker = brokerFactory.create(); this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, CommonFactories.defaultLockManagerFactory(), new MasterIdGeneratorFactory(), CommonFactories.defaultRelationshipTypeCreator(), CommonFactories.defaultTxIdGeneratorFactory(), CommonFactories.defaultTxRollbackHook(), new ZooKeeperLastCommittedTxIdSetter( broker ) ); this.masterServer = (MasterServer) broker.instantiateMasterServer( this ); instantiateIndexIfNeeded(); instantiateAutoUpdatePullerIfConfigSaysSo(); } private void instantiateAutoUpdatePullerIfConfigSaysSo() { String pullInterval = this.config.get( CONFIG_KEY_HA_PULL_INTERVAL ); if ( pullInterval != null ) { updatePuller = UpdatePuller.startAutoPull( this, TimeUtil.parseTimeMillis( pullInterval ) ); } } private void instantiateIndexIfNeeded() { if ( Boolean.parseBoolean( config.get( "index" ) ) ) { this.localIndex = new LuceneIndexService( this ); } } private boolean brokerSaysIAmMaster() { return broker.thisIsMaster(); } public Transaction beginTx() { return localGraph.beginTx(); } public Node createNode() { return localGraph.createNode(); } public boolean enableRemoteShell() { return localGraph.enableRemoteShell(); } public boolean enableRemoteShell( Map<String, Serializable> initialProperties ) { return localGraph.enableRemoteShell( initialProperties ); } public Iterable<Node> getAllNodes() { return localGraph.getAllNodes(); } public Node getNodeById( long id ) { return localGraph.getNodeById( id ); } public Node getReferenceNode() { return localGraph.getReferenceNode(); } public Relationship getRelationshipById( long id ) { return localGraph.getRelationshipById( id ); } public Iterable<RelationshipType> getRelationshipTypes() { return localGraph.getRelationshipTypes(); } public KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { return localGraph.registerKernelEventHandler( handler ); } public <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { return localGraph.registerTransactionEventHandler( handler ); } public synchronized void shutdown() { System.out.println( "Shutdown called on HA db " + this ); if ( this.updatePuller != null ) { this.updatePuller.halt(); this.updatePuller = null; } if ( this.broker != null ) { this.broker.shutdown(); this.broker = null; } if ( this.masterServer != null ) { this.masterServer.shutdown(); this.masterServer = null; } if ( this.localIndex != null ) { this.localIndex.shutdown(); this.localIndex = null; } if ( this.localGraph != null ) { this.localGraph.shutdown(); this.localGraph = null; this.localDataSourceManager = null; } } public KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return localGraph.unregisterKernelEventHandler( handler ); } public <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return localGraph.unregisterTransactionEventHandler( handler ); } public SlaveContext getSlaveContext() { Collection<XaDataSource> dataSources = localDataSourceManager.getAllRegisteredDataSources(); @SuppressWarnings("unchecked") Pair<String, Long>[] txs = new Pair[dataSources.size()]; int i = 0; for ( XaDataSource dataSource : dataSources ) { txs[i++] = new Pair<String, Long>( dataSource.getName(), dataSource.getLastCommittedTxId() ); } return new SlaveContext( machineId, txs ); } public <T> T receive( Response<T> response ) { try { for ( Pair<String, TransactionStream> streams : response.transactions().getStreams() ) { String resourceName = streams.first(); XaDataSource dataSource = localDataSourceManager.getXaDataSource( resourceName ); for ( ReadableByteChannel channel : streams.other().getChannels() ) { dataSource.applyCommittedTransaction( channel ); channel.close(); } } return response.response(); } catch ( IOException e ) { somethingIsWrong( e ); throw new RuntimeException( e ); } } public void somethingIsWrong( Exception e ) { new Thread() { @Override public void run() { reevaluateMyself(); } }.start(); } public IndexService getIndexService() { return this.localIndex; } }
package org.neo4j.kernel; import java.io.IOException; import java.io.Serializable; import java.nio.channels.ReadableByteChannel; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.helpers.Pair; import org.neo4j.kernel.ha.HaCommunicationException; import org.neo4j.kernel.ha.MasterServer; import org.neo4j.kernel.ha.SlaveIdGenerator.SlaveIdGeneratorFactory; import org.neo4j.kernel.ha.SlaveLockManager.SlaveLockManagerFactory; import org.neo4j.kernel.ha.SlaveRelationshipTypeCreator; import org.neo4j.kernel.ha.SlaveTxIdGenerator.SlaveTxIdGeneratorFactory; import org.neo4j.kernel.ha.SlaveTxRollbackHook; import org.neo4j.kernel.ha.ZooKeeperLastCommittedTxIdSetter; import org.neo4j.kernel.ha.zookeeper.ZooKeeperBroker; import org.neo4j.kernel.ha.zookeeper.ZooKeeperException; import org.neo4j.kernel.impl.ha.Broker; import org.neo4j.kernel.impl.ha.Response; import org.neo4j.kernel.impl.ha.ResponseReceiver; import org.neo4j.kernel.impl.ha.SlaveContext; import org.neo4j.kernel.impl.ha.TransactionStream; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; public class HighlyAvailableGraphDatabase implements GraphDatabaseService, ResponseReceiver { public static final String CONFIG_KEY_HA_MACHINE_ID = "ha.machine_id"; public static final String CONFIG_KEY_HA_ZOO_KEEPER_SERVERS = "ha.zoo_keeper_servers"; public static final String CONFIG_KEY_HA_SERVERS = "ha.servers"; private final String storeDir; private final Map<String, String> config; private final Broker broker; private EmbeddedGraphDbImpl localGraph; private final int machineId; private MasterServer masterServer; /** * Will instantiate its own ZooKeeper broker */ public HighlyAvailableGraphDatabase( String storeDir, Map<String, String> config ) { this( storeDir, config, instantiateBroker( storeDir, config ) ); } /** * Only for testing */ public HighlyAvailableGraphDatabase( String storeDir, Map<String, String> config, Broker broker ) { this.storeDir = storeDir; this.config = config; this.broker = broker; this.machineId = getMachineIdFromConfig( config ); reevaluateMyself(); } private static Broker instantiateBroker( String storeDir, Map<String, String> config ) { return new ZooKeeperBroker( storeDir, getMachineIdFromConfig( config ), getZooKeeperServersFromConfig( config ), getHaServersFromConfig( config ) ); } private static Map<Integer, String> getHaServersFromConfig( Map<?, ?> config ) { String value = config.get( CONFIG_KEY_HA_SERVERS ).toString(); Map<Integer, String> result = new HashMap<Integer, String>(); for ( String part : value.split( Pattern.quote( "," ) ) ) { String[] tokens = part.trim().split( Pattern.quote( "=" ) ); result.put( new Integer( tokens[0] ), tokens[1] ); } return result; } private static String getZooKeeperServersFromConfig( Map<String, String> config ) { return config.get( CONFIG_KEY_HA_ZOO_KEEPER_SERVERS ); } private static int getMachineIdFromConfig( Map<String, String> config ) { // Fail fast if null return Integer.parseInt( config.get( CONFIG_KEY_HA_MACHINE_ID ) ); } public Broker getBroker() { return this.broker; } public void pullUpdates() { try { receive( broker.getMaster().pullUpdates( getSlaveContext() ) ); } catch ( ZooKeeperException e ) { somethingIsWrong( e ); throw e; } catch ( HaCommunicationException e ) { somethingIsWrong( e ); throw e; } } public Config getConfig() { return localGraph.getConfig(); } protected void reevaluateMyself() { boolean brokerSaysIAmMaster = brokerSaysIAmMaster(); boolean iAmCurrentlyMaster = masterServer != null; if ( brokerSaysIAmMaster ) { if ( !iAmCurrentlyMaster ) { shutdownIfStarted(); } this.masterServer = (MasterServer) broker.instantiateMasterServer( this ); this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, CommonFactories.defaultLockManagerFactory(), CommonFactories.defaultIdGeneratorFactory(), CommonFactories.defaultRelationshipTypeCreator(), CommonFactories.defaultTxIdGeneratorFactory(), CommonFactories.defaultTxRollbackHook(), new ZooKeeperLastCommittedTxIdSetter( broker ) ); } else { if ( iAmCurrentlyMaster ) { shutdownIfStarted(); } this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, new SlaveLockManagerFactory( broker, this ), new SlaveIdGeneratorFactory( broker, this ), new SlaveRelationshipTypeCreator( broker, this ), new SlaveTxIdGeneratorFactory( broker, this ), new SlaveTxRollbackHook( broker, this ), new ZooKeeperLastCommittedTxIdSetter( broker ) ); } this.localGraph.addShellApp( Pullupdates.class ); } private boolean brokerSaysIAmMaster() { return broker.thisIsMaster(); } public Transaction beginTx() { return localGraph.beginTx(); } public Node createNode() { return localGraph.createNode(); } public boolean enableRemoteShell() { return localGraph.enableRemoteShell(); } public boolean enableRemoteShell( Map<String, Serializable> initialProperties ) { return localGraph.enableRemoteShell( initialProperties ); } public Iterable<Node> getAllNodes() { return localGraph.getAllNodes(); } public Node getNodeById( long id ) { return localGraph.getNodeById( id ); } public Node getReferenceNode() { return localGraph.getReferenceNode(); } public Relationship getRelationshipById( long id ) { return localGraph.getRelationshipById( id ); } public Iterable<RelationshipType> getRelationshipTypes() { return localGraph.getRelationshipTypes(); } public KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { return localGraph.registerKernelEventHandler( handler ); } public <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { return localGraph.registerTransactionEventHandler( handler ); } public void shutdown() { shutdownIfStarted(); } private void shutdownIfStarted() { if ( this.masterServer != null ) { System.out.println( "Shutting down master server" ); this.masterServer.shutdown(); this.masterServer = null; } if ( this.localGraph != null ) { System.out.println( "Shutting down local graph" ); this.localGraph.shutdown(); this.localGraph = null; } } public KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return localGraph.unregisterKernelEventHandler( handler ); } public <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return localGraph.unregisterTransactionEventHandler( handler ); } public SlaveContext getSlaveContext() { Config config = getConfig(); Map<String, Long> txs = new HashMap<String, Long>(); for ( XaDataSource dataSource : config.getTxModule().getXaDataSourceManager().getAllRegisteredDataSources() ) { txs.put( dataSource.getName(), dataSource.getLastCommittedTxId() ); } return new SlaveContext( machineId, txs ); } public <T> T receive( Response<T> response ) { try { for ( Pair<String, TransactionStream> streams : response.transactions().getStreams() ) { String resourceName = streams.first(); XaDataSource dataSource = localGraph.getConfig().getTxModule().getXaDataSourceManager() .getXaDataSource( resourceName ); for ( ReadableByteChannel channel : streams.other().getChannels() ) { dataSource.applyCommittedTransaction( channel ); } } return response.response(); } catch ( IOException e ) { somethingIsWrong( e ); throw new RuntimeException( e ); } } public void somethingIsWrong( Exception e ) { new Thread() { @Override public void run() { reevaluateMyself(); } }.start(); } }
package org.pentaho.ui.xul.swt.tags; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TreeItem; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.DefaultBinding; import org.pentaho.ui.xul.binding.InlineBindingExpression; import org.pentaho.ui.xul.components.XulTreeCell; import org.pentaho.ui.xul.components.XulTreeCol; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.containers.XulTreeChildren; import org.pentaho.ui.xul.containers.XulTreeCols; import org.pentaho.ui.xul.containers.XulTreeItem; import org.pentaho.ui.xul.containers.XulTreeRow; import org.pentaho.ui.xul.dnd.DropEffectType; import org.pentaho.ui.xul.dnd.DropEvent; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swt.AbstractSwtXulContainer; import org.pentaho.ui.xul.swt.TableSelection; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeTextCellEditor; import org.pentaho.ui.xul.util.ColumnType; import org.pentaho.ui.xul.util.TreeCellEditor; import org.pentaho.ui.xul.util.TreeCellRenderer; public class SwtTree extends AbstractSwtXulContainer implements XulTree { // Tables and trees // share so much of the same API, I wrapped their common methods // into an interface (TabularWidget) and set the component to two // separate member variables here so that I don't have to reference // them separately. private static final Log logger = LogFactory.getLog(SwtTree.class); protected XulTreeCols columns = null; protected XulTreeChildren rootChildren = null; protected XulComponent parentComponent = null; private Object data = null; private boolean disabled = false; private boolean enableColumnDrag = false; private boolean editable = false; private String onedit; private String onSelect = null; private int rowsToDisplay = 0; private TableSelection selType = TableSelection.SINGLE; private boolean isHierarchical = false; private ColumnType[] currentColumnTypes = null; private int activeRow = -1; private int activeColumn = -1; private XulDomContainer domContainer; private TableViewer table; private TreeViewer tree; private int selectedIndex = -1; protected boolean controlDown; private int[] selectedRows; private boolean hiddenRoot = true; public SwtTree(Element self, XulComponent parent, XulDomContainer container, String tagName) { super(tagName); this.parentComponent = parent; // According to XUL spec, in order for a hierarchical tree to be rendered, a // primary column must be identified AND at least one treeitem must be // listed as a container. // Following code does not work with the current instantiation routine. When // transitioned to onDomReady() instantiation this should work. domContainer = container; } @Override public void layout() { XulComponent primaryColumn = this.getElementByXPath("treecols/treecol[@primary='true']"); XulComponent isaContainer = this.getElementByXPath("treechildren/treeitem[@container='true']"); isHierarchical = (primaryColumn != null) || (isaContainer != null); if (isHierarchical) { int style = (this.selType == TableSelection.MULTIPLE) ? SWT.MULTI : SWT.None; style |= SWT.BORDER; tree = new TreeViewer((Composite) parentComponent.getManagedObject(), style); setManagedObject(tree); } else { table = new TableViewer((Composite) parentComponent.getManagedObject(), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); setManagedObject(table); } if (isHierarchical) { setupTree(); if (getOndrag() != null) { DropEffectType effect = DropEffectType.COPY; if (getDrageffect() != null) { effect = DropEffectType.valueOfIgnoreCase(getDrageffect()); } super.enableDrag(effect); } if (getOndrop() != null) { super.enableDrop(); } } else { setupTable(); } this.initialized = true; } private void setupTree() { tree.setCellEditors(new CellEditor[] { new XulTreeTextCellEditor(tree.getTree()) }); tree.setCellModifier(new XulTreeColumnModifier(this)); tree.setLabelProvider(new XulTreeLabelProvider(this, this.domContainer)); tree.setContentProvider(new XulTreeContentProvider(this)); tree.setInput(this); tree.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); tree.setColumnProperties(new String[] { "0" }); //TreeViewerColumn tc = new TreeViewerColumn(tree, SWT.LEFT); TreeViewerEditor.create(tree, new ColumnViewerEditorActivationStrategy(tree) { @Override protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) { return super.isEditorActivationEvent(event); } }, ColumnViewerEditor.DEFAULT); tree.getTree().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = true; break; case SWT.ESC: // End editing session tree.getTree().deselectAll(); setSelectedRows(new int[] {}); break; } } @Override public void keyReleased(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = false; break; } } }); // Add a focus listener to clear the contol down selector tree.getTree().addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { } public void focusLost(FocusEvent arg0) { if (tree.getCellEditors()[0].isActivated() == false) { SwtTree.this.controlDown = false; } } }); tree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { // if the selection is empty clear the label if (event.getSelection().isEmpty()) { SwtTree.this.setSelectedIndex(-1); return; } if (event.getSelection() instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); int[] selected = new int[selection.size()]; List selectedItems = new ArrayList(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selected[i++] = b.curPos; selectedItems.add(b.selectedItem); } if (selected.length == 0) { setSelectedIndex(-1); } else { setSelectedIndex(selected[0]); } int[] selectedRows = null; if (SwtTree.this.controlDown && Arrays.equals(selected, selectedRows) && tree.getCellEditors()[0].isActivated() == false) { tree.getTree().deselectAll(); selectedRows = new int[] {}; } else { selectedRows = selected; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.get(0) : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } } }); } private class SearchBundle { int curPos; boolean found; Object selectedItem; } private SearchBundle findSelectedIndex(SearchBundle bundle, XulTreeChildren children, XulTreeItem selectedItem) { for (XulComponent c : children.getChildNodes()) { if (c == selectedItem) { bundle.found = true; if (elements != null) { bundle.selectedItem = findSelectedTreeItem(bundle.curPos); } return bundle; } bundle.curPos++; if (c.getChildNodes().size() > 1) { SearchBundle b = findSelectedIndex(bundle, (XulTreeChildren) c.getChildNodes().get(1), selectedItem); if (b.found) { return b; } } } return bundle; } private Object findSelectedTreeItem(int pos) { if (this.isHierarchical && this.elements != null) { if (elements == null || elements.size() == 0) { return null; } String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); if (pos == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, method, new FindSelectedItemTuple(pos, this.isHiddenrootnode())); return tuple != null ? tuple.selectedItem : null; } return null; } private void setupTable() { table.setContentProvider(new XulTableContentProvider(this)); table.setLabelProvider(new XulTableColumnLabelProvider(this)); table.setCellModifier(new XulTableColumnModifier(this)); Table baseTable = table.getTable(); baseTable.setLayoutData(new GridData(GridData.FILL_BOTH)); setupColumns(); table.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); Collection selectedItems = findSelectedTableRows(selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.toArray()[0] : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } }); // Turn on the header and the lines baseTable.setHeaderVisible(true); baseTable.setLinesVisible(true); table.setInput(this); final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); parentComposite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { resizeColumns(); } }); table.getTable().setEnabled(!this.disabled); table.refresh(); } private Collection findSelectedTableRows(int[] selectedRows) { if (elements == null) { return Collections.emptyList(); } List selectedItems = new ArrayList(); for (int i = 0; i < selectedRows.length; i++) { if (selectedRows[i] >= 0 && selectedRows[i] < elements.size()) { selectedItems.add(elements.toArray()[selectedRows[i]]); } } return selectedItems; } private void resizeColumns() { final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); Rectangle area = parentComposite.getClientArea(); Point preferredSize = table.getTable().computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width - 2 * table.getTable().getBorderWidth(); if (preferredSize.y > area.height + table.getTable().getHeaderHeight()) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getTable().getVerticalBar().getSize(); width -= vBarSize.x; } width -= 20; double totalFlex = 0; for (XulComponent col : getColumns().getChildNodes()) { totalFlex += ((XulTreeCol) col).getFlex(); } int colIdx = 0; for (XulComponent col : getColumns().getChildNodes()) { if (colIdx >= table.getTable().getColumnCount()) { break; } TableColumn c = table.getTable().getColumn(colIdx); int colFlex = ((XulTreeCol) col).getFlex(); if (totalFlex == 0) { c.setWidth(Math.round(width / getColumns().getColumnCount())); } else if (colFlex > 0) { c.setWidth(Integer.parseInt("" + Math.round(width * (colFlex / totalFlex)))); } colIdx++; } } private void setSelectedIndex(int idx) { this.selectedIndex = idx; changeSupport.firePropertyChange("selectedRows", null, new int[] { idx }); changeSupport.firePropertyChange("absoluteSelectedRows", null, new int[] { idx }); if (this.onSelect != null) { invoke(this.onSelect, new Object[] { new Integer(idx) }); } } private void createColumnTypesSnapshot() { if (this.columns.getChildNodes().size() > 0) { Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); currentColumnTypes = new ColumnType[xulTreeColArray.length]; for (int i = 0; i < xulTreeColArray.length; i++) { currentColumnTypes[i] = ColumnType.valueOf(((XulTreeCol) xulTreeColArray[i]).getType()); } } else { // Create an empty array to indicate that it has been processed, but contains 0 columns currentColumnTypes = new ColumnType[0]; } } private boolean columnsNeedUpdate() { // Differing number of columsn if (table.getTable().getColumnCount() != this.columns.getColumnCount()) { return true; } // First run, always update if (currentColumnTypes == null) { return true; } // Column Types have changed Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); for (int i = 0; i < xulTreeColArray.length; i++) { if (!currentColumnTypes[i].toString().equalsIgnoreCase(((XulTreeCol) xulTreeColArray[i]).getType())) { // A column has changed its type. Columns need updating return true; } } // Columns have not changed and do not need updating return false; } private void setupColumns() { if (columnsNeedUpdate()) { while (table.getTable().getColumnCount() > 0) { table.getTable().getColumn(0).dispose(); } // Add Columns for (XulComponent col : this.columns.getChildNodes()) { TableColumn tc = new TableColumn(table.getTable(), SWT.LEFT); String lbl = ((XulTreeCol) col).getLabel(); tc.setText(lbl != null ? lbl : ""); //$NON-NLS-1$ } // Pack the columns for (int i = 0; i < table.getTable().getColumnCount(); i++) { table.getTable().getColumn(i).pack(); } } if (table.getCellEditors() != null) { for (int i = 0; i < table.getCellEditors().length; i++) { table.getCellEditors()[i].dispose(); } } CellEditor[] editors = new CellEditor[this.columns.getChildNodes().size()]; String[] names = new String[getColumns().getColumnCount()]; int i = 0; for (XulComponent c : this.columns.getChildNodes()) { XulTreeCol col = (XulTreeCol) c; final int colIdx = i; CellEditor editor; ColumnType type = col.getColumnType(); switch (type) { case CHECKBOX: editor = new CheckboxCellEditor(table.getTable()); break; case COMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}, SWT.READ_ONLY); break; case EDITABLECOMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}); // final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); // editableControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(editableControl.getText()); break; case TEXT: default: editor = new TextCellEditor(table.getTable()); // final Text textControl = (Text) ((TextCellEditor) editor).getControl(); // textControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(textControl.getText()); break; } // Create selection listener for comboboxes. if (type == ColumnType.EDITABLECOMBOBOX || type == ColumnType.COMBOBOX) { final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); editableControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { // TODO Auto-generated method stub super.widgetDefaultSelected(arg0); } @Override public void widgetSelected(SelectionEvent arg0) { super.widgetSelected(arg0); XulTreeCell cell = getCell(colIdx); cell.setSelectedIndex(editableControl.getSelectionIndex()); } }); } editors[i] = editor; names[i] = "" + i; //$NON-NLS-1$ i++; } table.setCellEditors(editors); table.setColumnProperties(names); resizeColumns(); createColumnTypesSnapshot(); } private XulTreeCell getCell(int colIdx) { return ((XulTreeItem) (table.getTable().getSelection()[0]).getData()).getRow().getCell(colIdx); } public boolean isHierarchical() { return isHierarchical; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; if (this.isHierarchical() == false && table != null) { table.getTable().setEnabled(!disabled); } } public int getRows() { return rowsToDisplay; } public void setRows(int rowsToDisplay) { this.rowsToDisplay = rowsToDisplay; if (table != null && (!table.getTable().isDisposed()) && (rowsToDisplay > 0)) { int ht = rowsToDisplay * table.getTable().getItemHeight(); if (table.getTable().getLayoutData() != null) { // tree.setSize(tree.getSize().x,height); ((GridData) table.getTable().getLayoutData()).heightHint = ht; ((GridData) table.getTable().getLayoutData()).minimumHeight = ht; table.getTable().getParent().layout(true); } } } public enum SELECTION_MODE { SINGLE, CELL, MULTIPLE }; public String getSeltype() { return selType.toString(); } public void setSeltype(String selType) { if (selType.equalsIgnoreCase(getSeltype())) { return; // nothing has changed } this.selType = TableSelection.valueOf(selType.toUpperCase()); } public TableSelection getTableSelection() { return selType; } public boolean isEditable() { return editable; } public boolean isEnableColumnDrag() { return enableColumnDrag; } public void setEditable(boolean edit) { editable = edit; } public void setEnableColumnDrag(boolean drag) { enableColumnDrag = drag; } public String getOnselect() { return onSelect; } public void setOnselect(final String method) { if (method == null) { return; } onSelect = method; } public void setColumns(XulTreeCols columns) { this.columns = columns; } public XulTreeCols getColumns() { return columns; } public XulTreeChildren getRootChildren() { if (rootChildren == null) { rootChildren = (XulTreeChildren) this.getChildNodes().get(1); } return rootChildren; } public void setRootChildren(XulTreeChildren rootChildren) { this.rootChildren = rootChildren; } public int[] getActiveCellCoordinates() { return new int[] { activeRow, activeColumn }; } public void setActiveCellCoordinates(int row, int column) { activeRow = row; activeColumn = column; } public Object[][] getValues() { Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()]; int y = 0; for (XulComponent item : getRootChildren().getChildNodes()) { int x = 0; for (XulComponent tempCell : ((XulTreeItem) item).getRow().getChildNodes()) { XulTreeCell cell = (XulTreeCell) tempCell; switch (columns.getColumn(x).getColumnType()) { case CHECKBOX: Boolean flag = (Boolean) cell.getValue(); if (flag == null) { flag = Boolean.FALSE; } data[y][x] = flag; break; case COMBOBOX: Vector values = (Vector) cell.getValue(); int idx = cell.getSelectedIndex(); data[y][x] = values.get(idx); break; default: // label data[y][x] = cell.getLabel(); break; } x++; } y++; } return data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public int[] getSelectedRows() { if (selectedIndex > -1) { return new int[] { selectedIndex }; } else { return new int[] {}; } } public int[] getAbsoluteSelectedRows() { return getSelectedRows(); } public Collection getSelectedItems() { if (elements == null) { return null; } if (isHierarchical()) { List selectedItems = new ArrayList(); IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selectedItems.add(b.selectedItem); } return selectedItems; } else { IStructuredSelection selection = (IStructuredSelection) table.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } return findSelectedTableRows(selectedRows); } } public void addTreeRow(XulTreeRow row) { this.addChild(row); XulTreeItem item = new SwtTreeItem(this.getRootChildren()); row.setParentTreeItem(item); ((SwtTreeRow) row).layout(); } public void removeTreeRows(int[] rows) { // TODO Auto-generated method stub } public void update() { if (this.isHierarchical) { this.tree.setInput(this); this.tree.refresh(); if ("true".equals(getAttributeValue("expanded"))) { tree.expandAll(); } else if(expandBindings.size() > 0 && this.suppressEvents == false){ for(DefaultBinding expBind : expandBindings){ try { expBind.fireSourceChanged(); } catch (Exception e) { logger.error(e); } } expandBindings.clear(); } } else { setupColumns(); this.table.setInput(this); this.table.refresh(); } this.selectedIndex = -1; } public void clearSelection() { } public void setSelectedRows(int[] rows) { if (this.isHierarchical) { Object selected = getSelectedTreeItem(rows); int prevSelected = -1; if (selectedRows != null && selectedRows.length > 0) { prevSelected = selectedRows[0]; // single selection only for now } // tree.setSelection(new StructuredSelection(getSelectedTreeItems(rows))); changeSupport.firePropertyChange("selectedItem", prevSelected, selected); } else { table.getTable().setSelection(rows); } if (rows.length > 0) { this.selectedIndex = rows[0]; // single selection only for now } changeSupport.firePropertyChange("selectedRows", this.selectedRows, rows); changeSupport.firePropertyChange("absoluteSelectedRows", this.selectedRows, rows); this.selectedRows = rows; } public String getOnedit() { return onedit; } public void setOnedit(String onedit) { this.onedit = onedit; } private Collection elements; private boolean suppressEvents = false; public <T> void setElements(Collection<T> elements) { this.elements = elements; this.getRootChildren().removeAll(); if (elements == null) { update(); changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); return; } try { if (this.isHierarchical == false) { for (T o : elements) { XulTreeRow row = this.getRootChildren().addNewRow(); for (int x = 0; x < this.getColumns().getChildNodes().size(); x++) { XulComponent col = this.getColumns().getColumn(x); final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); XulTreeCol column = (XulTreeCol) col; for (InlineBindingExpression exp : ((XulTreeCol) col).getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + o + "]"); String colType = column.getType(); if (StringUtils.isEmpty(colType) == false && colType.equals("dynamic")) { colType = extractDynamicColType(o, x); } Object bob = null; if ((colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")) && column.getCombobinding() != null) { DefaultBinding binding = new DefaultBinding(o, column.getCombobinding(), cell, "value"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); binding = new DefaultBinding(o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex"); binding.setConversion(new BindingConvertor<Object, Integer>() { @Override public Integer sourceToTarget(Object value) { int index = ((Vector) cell.getValue()).indexOf(value); return index > -1 ? index : 0; } @Override public Object targetToSource(Integer value) { return ((Vector) cell.getValue()).get(value); } }); domContainer.addBinding(binding); binding.fireSourceChanged(); if (colType.equalsIgnoreCase("editablecombobox")) { binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!this.editable) { binding.setBindingType(Binding.Type.ONE_WAY); } else { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } domContainer.addBinding(binding); } } else if (colType.equalsIgnoreCase("checkbox")) { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, "value"); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } else { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } } if (column.getDisabledbinding() != null) { String prop = column.getDisabledbinding(); DefaultBinding bind = new DefaultBinding(o, column.getDisabledbinding(), cell, "disabled"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } Method imageMethod; String imageSrc = null; String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(x)).getImagebinding()); if (method != null) { imageMethod = o.getClass().getMethod(method); imageSrc = (String) imageMethod.invoke(o); SwtTreeItem item = (SwtTreeItem)row.getParent(); item.setXulDomContainer(this.domContainer); ((XulTreeItem) row.getParent()).setImage(imageSrc); } row.addCell(cell); } } } else {// tree suppressEvents = true; if(isHiddenrootnode() == false){ SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(elements, newRow); } else { for (T o : elements) { SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(o, newRow); } } suppressEvents = false; } update(); suppressEvents = false; // treat as a selection change changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); changeSupport.firePropertyChange("selectedItems", null, Collections.EMPTY_LIST); changeSupport.firePropertyChange("selectedItem", "", null); } catch (XulException e) { logger.error("error adding elements", e); } catch (Exception e) { logger.error("error adding elements", e); } } private List<DefaultBinding> expandBindings = new ArrayList<DefaultBinding>(); private <T> void addTreeChild(T element, XulTreeRow row) { try { XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)) .getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + element + "]"); // Tree Bindings are one-way for now as you cannot edit tree nodes DefaultBinding binding = new DefaultBinding(element, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (this.isEditable()) { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } else { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } String expBind = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getExpandedbinding(); if(expBind != null){ DefaultBinding binding = new DefaultBinding(element, expBind, row.getParent(), "expanded"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); expandBindings.add(binding); } row.addCell(cell); // find children String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); Method childrenMethod = null; try{ childrenMethod = element.getClass().getMethod(method, new Class[] {}); } catch(NoSuchMethodException e){ logger.debug("Could not find children binding method for object: "+element.getClass().getSimpleName()); } method = ((XulTreeCol)this.getColumns().getChildNodes().get(0)).getImagebinding(); if (method != null) { DefaultBinding binding = new DefaultBinding(element, method, row.getParent(), "image"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); } Collection<T> children = null; if(childrenMethod != null){ children = (Collection<T>) childrenMethod.invoke(element, new Object[] {}); } else if(element instanceof Collection ){ children = (Collection<T>) element; } XulTreeChildren treeChildren = null; if (children != null && children.size() > 0) { treeChildren = (XulTreeChildren) getDocument().createElement("treechildren"); row.getParent().addChild(treeChildren); } if (children == null) { return; } for (T child : children) { SwtTreeItem item = new SwtTreeItem(treeChildren); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); treeChildren.addChild(item); addTreeChild(child, newRow); } } catch (Exception e) { logger.error("error adding elements", e); } } public <T> Collection<T> getElements() { return null; } private String extractDynamicColType(Object row, int columnPos) { try { Method method = row.getClass().getMethod(this.columns.getColumn(columnPos).getColumntypebinding()); return (String) method.invoke(row, new Object[] {}); } catch (Exception e) { logger.debug("Could not extract column type from binding"); } return "text"; // default //$NON-NLS-1$ } private static String toGetter(String property) { if (property == null) { return null; } return "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); } public Object getSelectedItem() { Collection c = getSelectedItems(); if(c != null && c.size() > 0){ return c.toArray()[0]; } return null; } // private List<Object> getSelectedTreeItems(int[] currentSelection) { // if (this.isHierarchical && this.elements != null) { // int[] vals = currentSelection; // if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { // return null; // String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); // List<Object> selection = new ArrayList<Object>(); // for(int pos : currentSelection){ // FindBoundItemTuple tuple = new FindBoundItemTuple(pos); // findBoundItem(this.elements, this, property, tuple); // selection.add(tuple.treeItem); // return selection; // return null; private Object getSelectedTreeItem(int[] currentSelection) { if (this.isHierarchical && this.elements != null) { int[] vals = currentSelection; if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { return null; } String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); int selectedIdx = vals[0]; if (selectedIdx == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(selectedIdx, this.isHiddenrootnode())); return tuple != null ? tuple.selectedItem : null; } return null; } private void fireSelectedItem() { this.changeSupport.firePropertyChange("selectedItem", null, getSelectedItem()); } private static class FindSelectedItemTuple { Object selectedItem = null; int curpos = -1; //ignores first element (root) int selectedIndex; public FindSelectedItemTuple(int selectedIndex, boolean rootHidden) { this.selectedIndex = selectedIndex; if(rootHidden == false){ curpos = 0; } } } private void removeItemFromElements(Object item) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); removeItem(elements, method, item); } private void removeItem(Object parent, String childrenMethodProperty, Object toRemove) { Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null) { return; } Iterator iter = children.iterator(); while (iter.hasNext()) { Object next = iter.next(); if (next == toRemove) { iter.remove(); return; } removeItem(next, childrenMethodProperty, toRemove); } } private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty, FindSelectedItemTuple tuple) { if (tuple.curpos == tuple.selectedIndex) { tuple.selectedItem = parent; return tuple; } Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethodProperty, tuple); if (tuple.selectedItem != null) { return tuple; } } return null; } public void registerCellEditor(String key, TreeCellEditor editor) { // TODO Auto-generated method stub } public void registerCellRenderer(String key, TreeCellRenderer renderer) { // TODO Auto-generated method stub } public void collapseAll() { if (this.isHierarchical) { tree.collapseAll(); } } public void expandAll() { if (this.isHierarchical) { tree.expandAll(); } } private static class FindBoundItemTuple { Object item = null; XulComponent treeItem; public FindBoundItemTuple(Object item) { this.item = item; } } private static Collection getChildCollection(Object obj, String childrenMethodProperty) { Collection children = null; Method childrenMethod = null; try { childrenMethod = obj.getClass().getMethod(childrenMethodProperty, new Class[] {}); } catch (NoSuchMethodException e) { if (obj instanceof Collection) { children = (Collection) obj; } } try { if (childrenMethod != null) { children = (Collection) childrenMethod.invoke(obj, new Object[] {}); } } catch (Exception e) { logger.error(e); return null; } return children; } private static XulTreeChildren getTreeChildren(XulComponent parent) { for(XulComponent c : parent.getChildNodes()) { if (c instanceof XulTreeChildren) { return (XulTreeChildren) c; } } return null; } private FindBoundItemTuple findBoundItem(Object obj, XulComponent parent, String childrenMethodProperty, FindBoundItemTuple tuple) { if (obj.equals(tuple.item)) { tuple.treeItem = parent; return tuple; } Collection children = getChildCollection(obj, childrenMethodProperty); if (children == null || children.size() == 0) { return null; } XulTreeChildren xulChildren = getTreeChildren(parent); Object[] childrenArry = children.toArray(); for (int i=0; i< children.size(); i++) { findBoundItem(childrenArry[i], xulChildren.getChildNodes().get(i), childrenMethodProperty, tuple); if (tuple.treeItem != null) { return tuple; } } return null; } public void setBoundObjectExpanded(Object o, boolean expanded) { FindBoundItemTuple tuple = new FindBoundItemTuple(o); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); findBoundItem(this.elements, this, property, tuple); if(tuple.treeItem != null) { setTreeItemExpanded((XulTreeItem) tuple.treeItem, expanded); } } public void setTreeItemExpanded(XulTreeItem item, boolean expanded){ if (this.isHierarchical) { tree.setExpandedState(item, expanded); } } @Override public void setPopup(Menu m) { final Control control; if (isHierarchical()){ control = tree.getControl(); }else{ control = table.getControl(); } control.setMenu(m); } protected Control getDndObject() { return (Control)tree.getControl(); } protected List<Object> cachedDndItems; @Override protected List<Object> getSwtDragData() { if (!isHierarchical) { throw new UnsupportedOperationException("dnd not implemented for xul tree in table mode."); } // if bound, return a list of bound objects, otherwise return strings. // note, all of these elements must be serializable. if (elements != null) { cachedDndItems = (List<Object>)getSelectedItems(); } else { IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); List<Object> list = new ArrayList<Object>(); int i = 0; for (Object o : selection.toArray()) { list.add(((XulTreeItem)o).getRow().getCell(0).getLabel()); } cachedDndItems = list; } return cachedDndItems; } @Override protected void resolveDndParentAndIndex(DropEvent xulEvent) { if (!isHierarchical) { throw new UnsupportedOperationException("dnd not implemented for xul tree in table mode."); } TreeItem parent = null; int index = -1; DropTargetEvent event = (DropTargetEvent)xulEvent.getNativeEvent(); if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); parent = item.getParentItem(); if (parent != null) { TreeItem[] items = parent.getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE parent, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { // HANDLE parent, index + 1 index++; } else { parent = item; index = 0; } } else { TreeItem[] items = tree.getTree().getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE null, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { index++; } else { // item is parent parent = item; index = 0; } } } else { // ASSUME END OF LIST, null, 0 } Object parentObj = null; if (parent != null) { if (elements != null) { // swt -> xul -> element SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), (XulTreeItem)parent.getData()); parentObj = b.selectedItem; } else { parentObj = parent.getText(); } } xulEvent.setDropParent(parentObj); xulEvent.setDropIndex(index); } @Override protected void onSwtDragDropAccepted(DropEvent xulEvent) { List results = xulEvent.getDataTransfer().getData(); if (elements != null) { // place the new elements in the new location Collection insertInto = elements; if (xulEvent.getDropParent() != null) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); insertInto = getChildCollection(xulEvent.getDropParent(), method); } if (insertInto instanceof List) { List list = (List)insertInto; if (xulEvent.getDropIndex() == -1) { for (Object o : results) { list.add(o); } } else { for (int i = results.size() - 1; i >= 0; i list.add(xulEvent.getDropIndex(), results.get(i)); } } } // todo, can i trigger this through another mechanism? setElements(elements); } else { // non-binding path // TODO: add necessary xul dom } } @Override protected void onSwtDragFinished(DragSourceEvent event, DropEffectType effect) { if (effect == DropEffectType.MOVE) { // ISelection sel = tree.getSelection(); if (elements != null) { // remove cachedDndItems from the tree.. traverse for (Object item : cachedDndItems) { removeItemFromElements(item); } cachedDndItems = null; setElements(elements); } else { tree.remove(tree.getSelection()); } } } protected void onSwtDragOver(DropTargetEvent event) { event.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL; if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); if (pt.y < bounds.y + bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_BEFORE; } else if (pt.y > bounds.y + 2 * bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_AFTER; } else { event.feedback |= DND.FEEDBACK_SELECT; } } } public <T> void setSelectedItems(Collection<T> items) { int[] selIndexes= new int[items.size()]; if (this.isHierarchical && this.elements != null) { List<Object> selection = new ArrayList<Object>(); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); for(T t : items){ FindBoundItemTuple tuple = new FindBoundItemTuple(t); findBoundItem(this.elements, this, property, tuple); selection.add(tuple.treeItem); } tree.setSelection(new StructuredSelection(selection)); } else { int pos = 0; for(T t : items){ selIndexes[pos++] = findIndexOfItem(t); } this.setSelectedRows(selIndexes); } } public int findIndexOfItem(Object o){ String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); Method childrenMethod = null; try { childrenMethod = elements.getClass().getMethod(property, new Class[] {}); } catch (NoSuchMethodException e) { // Since this tree is built recursively, when at a leaf it will throw this exception. logger.debug(e); } FindSelectedIndexTuple tuple = findSelectedItem(this.elements, childrenMethod, new FindSelectedIndexTuple(o)); return tuple.selectedIndex; } private static class FindSelectedIndexTuple { Object selectedItem = null; Object currentItem = null; // ignores first element (root) int curpos = -1; // ignores first element (root) int selectedIndex = -1; public FindSelectedIndexTuple(Object selectedItem) { this.selectedItem = selectedItem; } } private FindSelectedIndexTuple findSelectedItem(Object parent, Method childrenMethod, FindSelectedIndexTuple tuple) { if (tuple.selectedItem == parent) { tuple.selectedIndex = tuple.curpos; return tuple; } Collection children = null; if(childrenMethod != null){ try { children = (Collection) childrenMethod.invoke(parent, new Object[] {}); } catch (Exception e) { logger.error(e); return tuple; } } else if(parent instanceof List){ children = (List) parent; } if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethod, tuple); if (tuple.selectedIndex > -1) { return tuple; } } return tuple; } public boolean isHiddenrootnode() { return hiddenRoot; } public void setHiddenrootnode(boolean hidden) { this.hiddenRoot = hidden; } }
package jonathanfinerty.once; import android.content.Context; import android.content.SharedPreferences; import java.util.HashSet; import java.util.Set; class PersistedSet { private static final String STRING_SET_KEY = "PersistedSetValues"; private SharedPreferences preferences; private Set<String> set; PersistedSet(Context context, String setName) { String preferencesName = "PersistedSet".concat(setName); preferences = context.getSharedPreferences(preferencesName, Context.MODE_PRIVATE); set = new HashSet<>(preferences.getStringSet(STRING_SET_KEY, new HashSet<String>())); } void put(String tag) { set.add(tag); updatePreferences(); } boolean contains(String tag) { return set.contains(tag); } void remove(String tag) { set.remove(tag); updatePreferences(); } void clear() { set.clear(); updatePreferences(); } private void updatePreferences() { SharedPreferences.Editor edit = preferences.edit(); edit.putStringSet(STRING_SET_KEY, set); edit.apply(); } }
package conversioncalculator; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.text.NumberFormat; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.SwingConstants; /** * @author Brian McMahon Conversion Layout class to develop the Swing components * and implement Event Listeners */ /* * TODO finish error handling TODO TextField updates on typing? TODO Add weight and volume radio buttons and * switch JComboBoxes - Add relevant classes */ public class ConversionLayout { NumberFormat df = new DecimalFormat(" JComboBox<?> fromSelection; JComboBox<?> toSelection; JTextField userInput1; JTextField userInput2; JLabel topLabel; JLabel equals; JPanel topPanel; JPanel calcInput; String[] fromUnits; String unit1; String unit2; String result; double amountValue; Conversion ml = new ConvertFromMillilitre(); Conversion cup = new ConvertFromCup(); Conversion gallon = new ConvertFromGallon(); Conversion litre = new ConvertFromLitre(); Conversion oz = new ConvertFromOz(); Conversion pint = new ConvertFromPint(); Conversion quart = new ConvertFromQuart(); Conversion tbsp = new ConvertFromTbsp(); Conversion tsp = new ConvertFromTsp(); public ConversionLayout() { equals = new JLabel("="); equals.setHorizontalAlignment(SwingConstants.CENTER); userInput1 = new JTextField(); userInput2 = new JTextField(); fromUnits = new String[] { "ml", "litre", "oz", "cup", "pint", "tbsp", "tsp", "gallon", "quart" }; fromSelection = new JComboBox<String>(fromUnits); toSelection = new JComboBox<String>(fromUnits); calcInput = new JPanel(new GridLayout(1, 5)); calcInput.add(fromSelection); calcInput.add(userInput1); calcInput.add(equals); calcInput.add(toSelection); calcInput.add(userInput2); topLabel = new JLabel("Please enter your selections below:"); topPanel = new JPanel(); topPanel.add(topLabel); addFromSelection(); addToSelection(); UserEntries entry = new UserEntries(); userInput1.addActionListener(entry); userInput2.addActionListener(entry); }// end layout constructor // ActionListener to set the value of the userInput1 field based on user // selection public void addFromSelection() { fromSelection.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selection = (String) fromSelection.getSelectedItem(); // check the unit user selects from JComboBox and set the value // to unit1 switch (selection) { case "litre": unit1 = "litre"; break; case "oz": unit1 = "oz"; break; case "cup": unit1 = "cup"; break; case "pint": unit1 = "pint"; break; case "ml": unit1 = "ml"; break; case "tbsp": unit1 = "tbsp"; break; case "tsp": unit1 = "tsp"; break; case "gallon": unit1 = "gallon"; break; case "quart": unit1 = "quart"; break; } // System.out.println(unit1); } }); } // ActionListener to set the value of the userInput2 field based on user // selection public void addToSelection() { toSelection.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selection = (String) toSelection.getSelectedItem(); // check the unit user selects from JComboBox and set the value // to unit2 switch (selection) { case "litre": unit2 = "litre"; break; case "oz": unit2 = "oz"; break; case "cup": unit2 = "cup"; break; case "pint": unit2 = "pint"; break; case "ml": unit2 = "ml"; break; case "tbsp": unit2 = "tbsp"; break; case "tsp": unit2 = "tsp"; break; case "gallon": unit2 = "gallon"; break; case "quart": unit2 = "quart"; break; } // System.out.println(unit2); } }); } // sets the values for userInput to each conversion unit public void setValues(double userInput) { ml.setValue(userInput); ml.getValue(); cup.setValue(userInput); cup.getValue(); gallon.setValue(userInput); gallon.getValue(); litre.setValue(userInput); litre.getValue(); oz.setValue(userInput); oz.getValue(); pint.setValue(userInput); pint.getValue(); quart.setValue(userInput); quart.getValue(); tbsp.setValue(userInput); tbsp.getValue(); tsp.setValue(userInput); tsp.getValue(); } // class for setting user input values on either JTextField private class UserEntries implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // if userInput1 triggers ActionEvent we check for unit1 value and // convert to unit2 value if (e.getSource() == userInput1) { String value = userInput1.getText(); // ensure entry is a numerical value try { amountValue = Double.parseDouble(value); if (amountValue < 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(userInput1, "Please enter a numeric value to convert."); } // sets the userInput value to the unit1 setValues(amountValue); try { switch (unit1) { case "ml": result = String.valueOf(ml.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "cup": result = String.valueOf(cup.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "gallon": result = String.valueOf(gallon.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "litre": result = String.valueOf(litre.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "oz": result = String.valueOf(oz.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "pint": result = String.valueOf(pint.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "quart": result = String.valueOf(quart.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "tbsp": result = String.valueOf(tbsp.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; case "tsp": result = String.valueOf(tsp.convertTo(unit2)); userInput2 .setText(df.format(Double.parseDouble(result))); break; } // catches exception is user does not select conversion // units } catch (NullPointerException ex) { fromSelection.setSelectedItem("ml"); JOptionPane.showMessageDialog(topPanel, "Please make unit selections."); } // if userInput2 triggers ActionEvent we check for unit2 value // and convert to unit1 value } else if (e.getSource() == userInput2) { String value = userInput2.getText(); try { amountValue = Double.parseDouble(value); if (amountValue < 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { JOptionPane .showMessageDialog(userInput2, "Please enter a positive numeric value to convert."); } // sets the userInput value to the units setValues(amountValue); try { switch (unit2) { case "ml": result = String.valueOf(ml.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "cup": result = String.valueOf(cup.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "gallon": result = String.valueOf(gallon.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "litre": result = String.valueOf(litre.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "oz": result = String.valueOf(oz.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "pint": result = String.valueOf(pint.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "quart": result = String.valueOf(quart.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "tbsp": result = String.valueOf(tbsp.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; case "tsp": result = String.valueOf(tsp.convertTo(unit1)); userInput1 .setText(df.format(Double.parseDouble(result))); break; } // catches exception is user does not select conversion // units } catch (NullPointerException ex) { JOptionPane.showMessageDialog(topPanel, "Please make unit selections."); } } } }// end UserEntries }// end ConversionLayout
package com.yahoo.squidb.sql; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Default implementation of {@link ArgumentResolver} that unwraps AtomicReferences, AtomicBooleans, ThreadLocals, and * Enum values. Users can extend DefaultArgumentResolver by overriding {@link #canResolveCustomType(Object)} and * {@link #resolveCustomType(Object)} to handle resolving types that are not handled by DefaultArgumentResolver, or to * handle one of the default types in a different way (for example, to resolve Enums using ordinals instead of names). */ public class DefaultArgumentResolver implements ArgumentResolver { @Override public Object resolveArgument(Object arg) { while (true) { if (canResolveCustomType(arg)) { arg = resolveCustomType(arg); } else if (arg instanceof AtomicReference) { arg = ((AtomicReference<?>) arg).get(); } else if (arg instanceof AtomicBoolean) { // Not a subclass of Number so we need to unwrap it return ((AtomicBoolean) arg).get() ? 1 : 0; } else if (arg instanceof Enum<?>) { return ((Enum<?>) arg).name(); } else if (arg instanceof ThreadLocal) { arg = ((ThreadLocal<?>) arg).get(); } else { return arg; } } } /** * Users can override this method if they want to provide custom logic for resolving/unwrapping the given argument. * * @return true if the user wants to handle the argument using {@link #resolveCustomType(Object)}, false if the * default resolution logic should be used for this argument */ protected boolean canResolveCustomType(Object arg) { return false; } /** * Users can override this method if they want to provide custom logic for resolving/unwrapping the given argument. * This method will only be called if {@link #canResolveCustomType(Object)} returns true for some argument. * * @return the result of resolving/unwrapping the given argument. */ protected Object resolveCustomType(Object arg) { throw new UnsupportedOperationException("DefaultArgumentResolver#resolveCustomType unimplemented. This " + "instance of DefaultArgumentResolver declared it could handle a type by returning true in " + "canResolveCustomType, but did not override resolveCustomType to resolve it."); } }
package org.postgresql.jdbc; import static org.postgresql.util.internal.Nullness.castNonNull; import org.postgresql.PGStatement; import org.postgresql.core.JavaVersion; import org.postgresql.core.Oid; import org.postgresql.core.Provider; import org.postgresql.util.ByteConverter; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import java.lang.reflect.Field; import java.sql.Date; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.SimpleTimeZone; import java.util.TimeZone; /** * Misc utils for handling time and date values. */ public class TimestampUtils { /** * Number of milliseconds in one day. */ private static final int ONEDAY = 24 * 3600 * 1000; private static final char[] ZEROS = {'0', '0', '0', '0', '0', '0', '0', '0', '0'}; private static final char[][] NUMBERS; private static final HashMap<String, TimeZone> GMT_ZONES = new HashMap<String, TimeZone>(); private static final int MAX_NANOS_BEFORE_WRAP_ON_ROUND = 999999500; private static final java.time.Duration ONE_MICROSECOND = java.time.Duration.ofNanos(1000); // LocalTime.MAX is 23:59:59.999_999_999, and it wraps to 24:00:00 when nanos exceed 999_999_499 // since PostgreSQL has microsecond resolution only private static final java.time.LocalTime MAX_TIME = java.time.LocalTime.MAX.minus(java.time.Duration.ofNanos(500)); private static final java.time.OffsetDateTime MAX_OFFSET_DATETIME = java.time.OffsetDateTime.MAX.minus(java.time.Duration.ofMillis(500)); private static final java.time.LocalDateTime MAX_LOCAL_DATETIME = java.time.LocalDateTime.MAX.minus(java.time.Duration.ofMillis(500)); // low value for dates is 4713 BC private static final java.time.LocalDate MIN_LOCAL_DATE = java.time.LocalDate.of(4713, 1, 1).with(java.time.temporal.ChronoField.ERA, java.time.chrono.IsoEra.BCE.getValue()); private static final java.time.LocalDateTime MIN_LOCAL_DATETIME = MIN_LOCAL_DATE.atStartOfDay(); private static final java.time.OffsetDateTime MIN_OFFSET_DATETIME = MIN_LOCAL_DATETIME.atOffset(java.time.ZoneOffset.UTC); private static final @Nullable Field DEFAULT_TIME_ZONE_FIELD; private @Nullable TimeZone prevDefaultZoneFieldValue; private @Nullable TimeZone defaultTimeZoneCache; static { // The expected maximum value is 60 (seconds), so 64 is used "just in case" NUMBERS = new char[64][]; for (int i = 0; i < NUMBERS.length; i++) { NUMBERS[i] = ((i < 10 ? "0" : "") + Integer.toString(i)).toCharArray(); } // Backend's gmt-3 means GMT+03 in Java. Here a map is created so gmt-3 can be converted to // java TimeZone for (int i = -12; i <= 14; i++) { TimeZone timeZone; String pgZoneName; if (i == 0) { timeZone = TimeZone.getTimeZone("GMT"); pgZoneName = "GMT"; } else { timeZone = TimeZone.getTimeZone("GMT" + (i <= 0 ? "+" : "-") + Math.abs(i)); pgZoneName = "GMT" + (i >= 0 ? "+" : "-"); } if (i == 0) { GMT_ZONES.put(pgZoneName, timeZone); continue; } GMT_ZONES.put(pgZoneName + Math.abs(i), timeZone); GMT_ZONES.put(pgZoneName + new String(NUMBERS[Math.abs(i)]), timeZone); } // Fast path to getting the default timezone. // Accessing the default timezone over and over creates a clone with regular API. // Because we don't mutate that object in our use of it, we can access the field directly. // This saves the creation of a clone everytime, and the memory associated to all these clones. Field tzField; try { tzField = null; // Avoid reflective access in Java 9+ if (JavaVersion.getRuntimeVersion().compareTo(JavaVersion.v1_8) <= 0) { tzField = TimeZone.class.getDeclaredField("defaultTimeZone"); tzField.setAccessible(true); TimeZone defaultTz = TimeZone.getDefault(); @SuppressWarnings("nulllability") Object tzFromField = tzField.get(null); if (defaultTz == null || !defaultTz.equals(tzFromField)) { tzField = null; } } } catch (Exception e) { tzField = null; } DEFAULT_TIME_ZONE_FIELD = tzField; } private final StringBuilder sbuf = new StringBuilder(); // This calendar is used when user provides calendar in setX(, Calendar) method. // It ensures calendar is Gregorian. private final Calendar calendarWithUserTz = new GregorianCalendar(); private final TimeZone utcTz = TimeZone.getTimeZone("UTC"); private @Nullable Calendar calCache; private int calCacheZone; /** * True if the backend uses doubles for time values. False if long is used. */ private final boolean usesDouble; private final Provider<TimeZone> timeZoneProvider; public TimestampUtils(boolean usesDouble, Provider<TimeZone> timeZoneProvider) { this.usesDouble = usesDouble; this.timeZoneProvider = timeZoneProvider; } private Calendar getCalendar(int sign, int hr, int min, int sec) { int rawOffset = sign * (((hr * 60 + min) * 60 + sec) * 1000); if (calCache != null && calCacheZone == rawOffset) { return calCache; } StringBuilder zoneID = new StringBuilder("GMT"); zoneID.append(sign < 0 ? '-' : '+'); if (hr < 10) { zoneID.append('0'); } zoneID.append(hr); if (min < 10) { zoneID.append('0'); } zoneID.append(min); if (sec < 10) { zoneID.append('0'); } zoneID.append(sec); TimeZone syntheticTZ = new SimpleTimeZone(rawOffset, zoneID.toString()); calCache = new GregorianCalendar(syntheticTZ); calCacheZone = rawOffset; return calCache; } private static class ParsedTimestamp { boolean hasDate = false; int era = GregorianCalendar.AD; int year = 1970; int month = 1; boolean hasTime = false; int day = 1; int hour = 0; int minute = 0; int second = 0; int nanos = 0; @Nullable Calendar tz = null; } private static class ParsedBinaryTimestamp { @Nullable Infinity infinity = null; long millis = 0; int nanos = 0; } enum Infinity { POSITIVE, NEGATIVE; } /** * Load date/time information into the provided calendar returning the fractional seconds. */ private ParsedTimestamp parseBackendTimestamp(String str) throws SQLException { char[] s = str.toCharArray(); int slen = s.length; // This is pretty gross.. ParsedTimestamp result = new ParsedTimestamp(); // We try to parse these fields in order; all are optional // (but some combinations don't make sense, e.g. if you have // both date and time then they must be whitespace-separated). // At least one of date and time must be present. // leading whitespace // yyyy-mm-dd // whitespace // hh:mm:ss // whitespace // timezone in one of the formats: +hh, -hh, +hh:mm, -hh:mm // whitespace // if date is present, an era specifier: AD or BC // trailing whitespace try { int start = skipWhitespace(s, 0); // Skip leading whitespace int end = firstNonDigit(s, start); int num; char sep; // Possibly read date. if (charAt(s, end) == '-') { // Date result.hasDate = true; // year result.year = number(s, start, end); start = end + 1; // Skip '-' // month end = firstNonDigit(s, start); result.month = number(s, start, end); sep = charAt(s, end); if (sep != '-') { throw new NumberFormatException("Expected date to be dash-separated, got '" + sep + "'"); } start = end + 1; // Skip '-' // day of month end = firstNonDigit(s, start); result.day = number(s, start, end); start = skipWhitespace(s, end); // Skip trailing whitespace } // Possibly read time. if (Character.isDigit(charAt(s, start))) { // Time. result.hasTime = true; // Hours end = firstNonDigit(s, start); result.hour = number(s, start, end); sep = charAt(s, end); if (sep != ':') { throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); } start = end + 1; // Skip ':' // minutes end = firstNonDigit(s, start); result.minute = number(s, start, end); sep = charAt(s, end); if (sep != ':') { throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); } start = end + 1; // Skip ':' // seconds end = firstNonDigit(s, start); result.second = number(s, start, end); start = end; // Fractional seconds. if (charAt(s, start) == '.') { end = firstNonDigit(s, start + 1); // Skip '.' num = number(s, start + 1, end); for (int numlength = (end - (start + 1)); numlength < 9; ++numlength) { num *= 10; } result.nanos = num; start = end; } start = skipWhitespace(s, start); // Skip trailing whitespace } // Possibly read timezone. sep = charAt(s, start); if (sep == '-' || sep == '+') { int tzsign = (sep == '-') ? -1 : 1; int tzhr; int tzmin; int tzsec; end = firstNonDigit(s, start + 1); // Skip +/- tzhr = number(s, start + 1, end); start = end; sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start + 1); // Skip ':' tzmin = number(s, start + 1, end); start = end; } else { tzmin = 0; } tzsec = 0; sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start + 1); // Skip ':' tzsec = number(s, start + 1, end); start = end; } // Setting offset does not seem to work correctly in all // cases.. So get a fresh calendar for a synthetic timezone // instead result.tz = getCalendar(tzsign, tzhr, tzmin, tzsec); start = skipWhitespace(s, start); // Skip trailing whitespace } if (result.hasDate && start < slen) { String eraString = new String(s, start, slen - start); if (eraString.startsWith("AD")) { result.era = GregorianCalendar.AD; start += 2; } else if (eraString.startsWith("BC")) { result.era = GregorianCalendar.BC; start += 2; } } if (start < slen) { throw new NumberFormatException( "Trailing junk on timestamp: '" + new String(s, start, slen - start) + "'"); } if (!result.hasTime && !result.hasDate) { throw new NumberFormatException("Timestamp has neither date nor time"); } } catch (NumberFormatException nfe) { throw new PSQLException( GT.tr("Bad value for type timestamp/date/time: {1}", str), PSQLState.BAD_DATETIME_FORMAT, nfe); } return result; } /** * Parse a string and return a timestamp representing its value. * * @param cal calendar to be used to parse the input string * @param s The ISO formated date string to parse. * @return null if s is null or a timestamp of the parsed string s. * @throws SQLException if there is a problem parsing s. */ public synchronized @PolyNull Timestamp toTimestamp(@Nullable Calendar cal, @PolyNull String s) throws SQLException { if (s == null) { return null; } int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } if (slen == 9 && s.equals("-infinity")) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } ParsedTimestamp ts = parseBackendTimestamp(s); Calendar useCal = ts.tz != null ? ts.tz : setupCalendar(cal); useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month - 1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, 0); Timestamp result = new Timestamp(useCal.getTimeInMillis()); result.setNanos(ts.nanos); return result; } /** * Parse a string and return a LocalTime representing its value. * * @param s The ISO formated time string to parse. * @return null if s is null or a LocalTime of the parsed string s. * @throws SQLException if there is a problem parsing s. */ public java.time.@PolyNull LocalTime toLocalTime(@PolyNull String s) throws SQLException { if (s == null) { return null; } if (s.equals("24:00:00")) { return java.time.LocalTime.MAX; } try { return java.time.LocalTime.parse(s); } catch (java.time.format.DateTimeParseException nfe) { throw new PSQLException( GT.tr("Bad value for type timestamp/date/time: {1}", s), PSQLState.BAD_DATETIME_FORMAT, nfe); } } /** * Parse a string and return a LocalDateTime representing its value. * * @param s The ISO formated date string to parse. * @return null if s is null or a LocalDateTime of the parsed string s. * @throws SQLException if there is a problem parsing s. */ public java.time.@PolyNull LocalDateTime toLocalDateTime(@PolyNull String s) throws SQLException { if (s == null) { return null; } int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return java.time.LocalDateTime.MAX; } if (slen == 9 && s.equals("-infinity")) { return java.time.LocalDateTime.MIN; } ParsedTimestamp ts = parseBackendTimestamp(s); // intentionally ignore time zone // 2004-10-19 10:23:54+03:00 is 2004-10-19 10:23:54 locally java.time.LocalDateTime result = java.time.LocalDateTime.of(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, ts.nanos); if (ts.era == GregorianCalendar.BC) { return result.with(java.time.temporal.ChronoField.ERA, java.time.chrono.IsoEra.BCE.getValue()); } else { return result; } } /** * Parse a string and return a LocalDateTime representing its value. * * @param s The ISO formated date string to parse. * @return null if s is null or a LocalDateTime of the parsed string s. * @throws SQLException if there is a problem parsing s. */ public java.time.@PolyNull OffsetDateTime toOffsetDateTime( @PolyNull String s) throws SQLException { if (s == null) { return null; } int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return java.time.OffsetDateTime.MAX; } if (slen == 9 && s.equals("-infinity")) { return java.time.OffsetDateTime.MIN; } ParsedTimestamp ts = parseBackendTimestamp(s); Calendar tz = ts.tz; int offsetSeconds; if (tz == null) { offsetSeconds = 0; } else { offsetSeconds = tz.get(Calendar.ZONE_OFFSET) / 1000; } java.time.ZoneOffset zoneOffset = java.time.ZoneOffset.ofTotalSeconds(offsetSeconds); // Postgres is always UTC java.time.OffsetDateTime result = java.time.OffsetDateTime.of(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, ts.nanos, zoneOffset) .withOffsetSameInstant(java.time.ZoneOffset.UTC); if (ts.era == GregorianCalendar.BC) { return result.with(java.time.temporal.ChronoField.ERA, java.time.chrono.IsoEra.BCE.getValue()); } else { return result; } } /** * Returns the offset date time object matching the given bytes with Oid#TIMETZ. * * @param t the time value * @return the matching offset date time */ public java.time.OffsetDateTime toOffsetDateTime(Time t) { // hardcode utc because the backend does not provide us the timezone // hardcode UNIX epoch, JDBC requires OffsetDateTime but doesn't describe what date should be used return t.toLocalTime().atDate(java.time.LocalDate.of(1970, 1, 1)).atOffset(java.time.ZoneOffset.UTC); } /** * Returns the offset date time object matching the given bytes with Oid#TIMESTAMPTZ. * * @param bytes The binary encoded local date time value. * @return The parsed local date time object. * @throws PSQLException If binary format could not be parsed. */ public java.time.OffsetDateTime toOffsetDateTimeBin(byte[] bytes) throws PSQLException { ParsedBinaryTimestamp parsedTimestamp = this.toProlepticParsedTimestampBin(bytes); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return java.time.OffsetDateTime.MAX; } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return java.time.OffsetDateTime.MIN; } // hardcode utc because the backend does not provide us the timezone // Postgres is always UTC java.time.Instant instant = java.time.Instant.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos); return java.time.OffsetDateTime.ofInstant(instant, java.time.ZoneOffset.UTC); } public synchronized @PolyNull Time toTime( @Nullable Calendar cal, @PolyNull String s) throws SQLException { // 1) Parse backend string if (s == null) { return null; } ParsedTimestamp ts = parseBackendTimestamp(s); Calendar useCal = ts.tz != null ? ts.tz : setupCalendar(cal); if (ts.tz == null) { // When no time zone provided (e.g. time or timestamp) // We get the year-month-day from the string, then truncate the day to 1970-01-01 // This is used for timestamp -> time conversion // Note: this cannot be merged with "else" branch since // timestamps at which the time flips to/from DST depend on the date // For instance, 2000-03-26 02:00:00 is invalid timestamp in Europe/Moscow time zone // and the valid one is 2000-03-26 03:00:00. That is why we parse full timestamp // then set year to 1970 later useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month - 1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); } else { // When time zone is given, we just pick the time part and assume date to be 1970-01-01 // this is used for time, timez, and timestamptz parsing useCal.set(Calendar.ERA, GregorianCalendar.AD); useCal.set(Calendar.YEAR, 1970); useCal.set(Calendar.MONTH, Calendar.JANUARY); useCal.set(Calendar.DAY_OF_MONTH, 1); } useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, 0); long timeMillis = useCal.getTimeInMillis() + ts.nanos / 1000000; if (ts.tz != null || (ts.year == 1970 && ts.era == GregorianCalendar.AD)) { // time with time zone has proper time zone, so the value can be returned as is return new Time(timeMillis); } // 2) Truncate date part so in given time zone the date would be formatted as 01/01/1970 return convertToTime(timeMillis, useCal.getTimeZone()); } public synchronized @PolyNull Date toDate(@Nullable Calendar cal, @PolyNull String s) throws SQLException { // 1) Parse backend string Timestamp timestamp = toTimestamp(cal, s); if (timestamp == null) { return null; } // Note: infinite dates are handled in convertToDate // 2) Truncate date part so in given time zone the date would be formatted as 00:00 return convertToDate(timestamp.getTime(), cal == null ? null : cal.getTimeZone()); } private Calendar setupCalendar(@Nullable Calendar cal) { TimeZone timeZone = cal == null ? null : cal.getTimeZone(); return getSharedCalendar(timeZone); } /** * Get a shared calendar, applying the supplied time zone or the default time zone if null. * * @param timeZone time zone to be set for the calendar * @return The shared calendar. */ public Calendar getSharedCalendar(@Nullable TimeZone timeZone) { if (timeZone == null) { timeZone = getDefaultTz(); } Calendar tmp = calendarWithUserTz; tmp.setTimeZone(timeZone); return tmp; } /** * Returns true when microsecond part of the time should be increased * when rounding to microseconds * @param nanos nanosecond part of the time * @return true when microsecond part of the time should be increased when rounding to microseconds */ private static boolean nanosExceed499(int nanos) { return nanos % 1000 > 499; } public synchronized String toString(@Nullable Calendar cal, Timestamp x) { return toString(cal, x, true); } public synchronized String toString(@Nullable Calendar cal, Timestamp x, boolean withTimeZone) { if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { return "infinity"; } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { return "-infinity"; } cal = setupCalendar(cal); long timeMillis = x.getTime(); // Round to microseconds int nanos = x.getNanos(); if (nanos >= MAX_NANOS_BEFORE_WRAP_ON_ROUND) { nanos = 0; timeMillis++; } else if (nanosExceed499(nanos)) { // PostgreSQL does not support nanosecond resolution yet, and appendTime will just ignore // 0..999 part of the nanoseconds, however we subtract nanos % 1000 to make the value // a little bit saner for debugging reasons nanos += 1000 - nanos % 1000; } cal.setTimeInMillis(timeMillis); sbuf.setLength(0); appendDate(sbuf, cal); sbuf.append(' '); appendTime(sbuf, cal, nanos); if (withTimeZone) { appendTimeZone(sbuf, cal); } appendEra(sbuf, cal); return sbuf.toString(); } public synchronized String toString(@Nullable Calendar cal, Date x) { return toString(cal, x, true); } public synchronized String toString(@Nullable Calendar cal, Date x, boolean withTimeZone) { if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { return "infinity"; } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { return "-infinity"; } cal = setupCalendar(cal); cal.setTime(x); sbuf.setLength(0); appendDate(sbuf, cal); appendEra(sbuf, cal); if (withTimeZone) { sbuf.append(' '); appendTimeZone(sbuf, cal); } return sbuf.toString(); } public synchronized String toString(@Nullable Calendar cal, Time x) { return toString(cal, x, true); } public synchronized String toString(@Nullable Calendar cal, Time x, boolean withTimeZone) { cal = setupCalendar(cal); cal.setTime(x); sbuf.setLength(0); appendTime(sbuf, cal, cal.get(Calendar.MILLISECOND) * 1000000); // The 'time' parser for <= 7.3 doesn't like timezones. if (withTimeZone) { appendTimeZone(sbuf, cal); } return sbuf.toString(); } private static void appendDate(StringBuilder sb, Calendar cal) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); appendDate(sb, year, month, day); } private static void appendDate(StringBuilder sb, int year, int month, int day) { // always use at least four digits for the year so very // early years, like 2, don't get misinterpreted int prevLength = sb.length(); sb.append(year); int leadingZerosForYear = 4 - (sb.length() - prevLength); if (leadingZerosForYear > 0) { sb.insert(prevLength, ZEROS, 0, leadingZerosForYear); } sb.append('-'); sb.append(NUMBERS[month]); sb.append('-'); sb.append(NUMBERS[day]); } private static void appendTime(StringBuilder sb, Calendar cal, int nanos) { int hours = cal.get(Calendar.HOUR_OF_DAY); int minutes = cal.get(Calendar.MINUTE); int seconds = cal.get(Calendar.SECOND); appendTime(sb, hours, minutes, seconds, nanos); } /** * Appends time part to the {@code StringBuilder} in PostgreSQL-compatible format. * The function truncates {@param nanos} to microseconds. The value is expected to be rounded * beforehand. * @param sb destination * @param hours hours * @param minutes minutes * @param seconds seconds * @param nanos nanoseconds */ private static void appendTime(StringBuilder sb, int hours, int minutes, int seconds, int nanos) { sb.append(NUMBERS[hours]); sb.append(':'); sb.append(NUMBERS[minutes]); sb.append(':'); sb.append(NUMBERS[seconds]); // Add nanoseconds. // This won't work for server versions < 7.2 which only want // a two digit fractional second, but we don't need to support 7.1 // anymore and getting the version number here is difficult. if (nanos < 1000) { return; } sb.append('.'); int len = sb.length(); sb.append(nanos / 1000); // append microseconds int needZeros = 6 - (sb.length() - len); if (needZeros > 0) { sb.insert(len, ZEROS, 0, needZeros); } int end = sb.length() - 1; while (sb.charAt(end) == '0') { sb.deleteCharAt(end); end } } private void appendTimeZone(StringBuilder sb, java.util.Calendar cal) { int offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; appendTimeZone(sb, offset); } private void appendTimeZone(StringBuilder sb, int offset) { int absoff = Math.abs(offset); int hours = absoff / 60 / 60; int mins = (absoff - hours * 60 * 60) / 60; int secs = absoff - hours * 60 * 60 - mins * 60; sb.append((offset >= 0) ? "+" : "-"); sb.append(NUMBERS[hours]); if (mins == 0 && secs == 0) { return; } sb.append(':'); sb.append(NUMBERS[mins]); if (secs != 0) { sb.append(':'); sb.append(NUMBERS[secs]); } } private static void appendEra(StringBuilder sb, Calendar cal) { if (cal.get(Calendar.ERA) == GregorianCalendar.BC) { sb.append(" BC"); } } public synchronized String toString(java.time.LocalDate localDate) { if (java.time.LocalDate.MAX.equals(localDate)) { return "infinity"; } else if (localDate.isBefore(MIN_LOCAL_DATE)) { return "-infinity"; } sbuf.setLength(0); appendDate(sbuf, localDate); appendEra(sbuf, localDate); return sbuf.toString(); } public synchronized String toString(java.time.LocalTime localTime) { sbuf.setLength(0); if (localTime.isAfter(MAX_TIME)) { return "24:00:00"; } int nano = localTime.getNano(); if (nanosExceed499(nano)) { // Technically speaking this is not a proper rounding, however // it relies on the fact that appendTime just truncates 000..999 nanosecond part localTime = localTime.plus(ONE_MICROSECOND); } appendTime(sbuf, localTime); return sbuf.toString(); } public synchronized String toString(java.time.OffsetDateTime offsetDateTime) { if (offsetDateTime.isAfter(MAX_OFFSET_DATETIME)) { return "infinity"; } else if (offsetDateTime.isBefore(MIN_OFFSET_DATETIME)) { return "-infinity"; } sbuf.setLength(0); int nano = offsetDateTime.getNano(); if (nanosExceed499(nano)) { // Technically speaking this is not a proper rounding, however // it relies on the fact that appendTime just truncates 000..999 nanosecond part offsetDateTime = offsetDateTime.plus(ONE_MICROSECOND); } java.time.LocalDateTime localDateTime = offsetDateTime.toLocalDateTime(); java.time.LocalDate localDate = localDateTime.toLocalDate(); appendDate(sbuf, localDate); sbuf.append(' '); appendTime(sbuf, localDateTime.toLocalTime()); appendTimeZone(sbuf, offsetDateTime.getOffset()); appendEra(sbuf, localDate); return sbuf.toString(); } /** * Formats {@link java.time.LocalDateTime} to be sent to the backend, thus it adds time zone. * Do not use this method in {@link java.sql.ResultSet#getString(int)} * @param localDateTime The local date to format as a String * @return The formatted local date */ public synchronized String toString(java.time.LocalDateTime localDateTime) { if (localDateTime.isAfter(MAX_LOCAL_DATETIME)) { return "infinity"; } else if (localDateTime.isBefore(MIN_LOCAL_DATETIME)) { return "-infinity"; } // LocalDateTime is always passed with time zone so backend can decide between timestamp and timestamptz java.time.ZonedDateTime zonedDateTime = localDateTime.atZone(getDefaultTz().toZoneId()); return toString(zonedDateTime.toOffsetDateTime()); } private static void appendDate(StringBuilder sb, java.time.LocalDate localDate) { int year = localDate.get(java.time.temporal.ChronoField.YEAR_OF_ERA); int month = localDate.getMonthValue(); int day = localDate.getDayOfMonth(); appendDate(sb, year, month, day); } private static void appendTime(StringBuilder sb, java.time.LocalTime localTime) { int hours = localTime.getHour(); int minutes = localTime.getMinute(); int seconds = localTime.getSecond(); int nanos = localTime.getNano(); appendTime(sb, hours, minutes, seconds, nanos); } private void appendTimeZone(StringBuilder sb, java.time.ZoneOffset offset) { int offsetSeconds = offset.getTotalSeconds(); appendTimeZone(sb, offsetSeconds); } private static void appendEra(StringBuilder sb, java.time.LocalDate localDate) { if (localDate.get(java.time.temporal.ChronoField.ERA) == java.time.chrono.IsoEra.BCE.getValue()) { sb.append(" BC"); } } private static int skipWhitespace(char[] s, int start) { int slen = s.length; for (int i = start; i < slen; i++) { if (!Character.isSpace(s[i])) { return i; } } return slen; } private static int firstNonDigit(char[] s, int start) { int slen = s.length; for (int i = start; i < slen; i++) { if (!Character.isDigit(s[i])) { return i; } } return slen; } private static int number(char[] s, int start, int end) { if (start >= end) { throw new NumberFormatException(); } int n = 0; for (int i = start; i < end; i++) { n = 10 * n + (s[i] - '0'); } return n; } private static char charAt(char[] s, int pos) { if (pos >= 0 && pos < s.length) { return s[pos]; } return '\0'; } /** * Returns the SQL Date object matching the given bytes with {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @return The parsed date object. * @throws PSQLException If binary format could not be parsed. */ public Date toDateBin(@Nullable TimeZone tz, byte[] bytes) throws PSQLException { if (bytes.length != 4) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "date"), PSQLState.BAD_DATETIME_FORMAT); } int days = ByteConverter.int4(bytes, 0); if (tz == null) { tz = getDefaultTz(); } long secs = toJavaSecs(days * 86400L); long millis = secs * 1000L; if (millis <= PGStatement.DATE_NEGATIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_NEGATIVE_INFINITY; } else if (millis >= PGStatement.DATE_POSITIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_POSITIVE_INFINITY; } else { // Here be dragons: backend did not provide us the timezone, so we guess the actual point in // time millis = guessTimestamp(millis, tz); } return new Date(millis); } private TimeZone getDefaultTz() { // Fast path to getting the default timezone. if (DEFAULT_TIME_ZONE_FIELD != null) { try { @SuppressWarnings("nullability") TimeZone defaultTimeZone = (TimeZone) DEFAULT_TIME_ZONE_FIELD.get(null); if (defaultTimeZone == prevDefaultZoneFieldValue) { return castNonNull(defaultTimeZoneCache); } prevDefaultZoneFieldValue = defaultTimeZone; } catch (Exception e) { // If this were to fail, fallback on slow method. } } TimeZone tz = TimeZone.getDefault(); defaultTimeZoneCache = tz; return tz; } public boolean hasFastDefaultTimeZone() { return DEFAULT_TIME_ZONE_FIELD != null; } /** * Returns the SQL Time object matching the given bytes with {@link Oid#TIME} or * {@link Oid#TIMETZ}. * * @param tz The timezone used when received data is {@link Oid#TIME}, ignored if data already * contains {@link Oid#TIMETZ}. * @param bytes The binary encoded time value. * @return The parsed time object. * @throws PSQLException If binary format could not be parsed. */ public Time toTimeBin(@Nullable TimeZone tz, byte[] bytes) throws PSQLException { if ((bytes.length != 8 && bytes.length != 12)) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "time"), PSQLState.BAD_DATETIME_FORMAT); } long millis; int timeOffset; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); millis = (long) (time * 1000); } else { long time = ByteConverter.int8(bytes, 0); millis = time / 1000; } if (bytes.length == 12) { timeOffset = ByteConverter.int4(bytes, 8); timeOffset *= -1000; millis -= timeOffset; return new Time(millis); } if (tz == null) { tz = getDefaultTz(); } // Here be dragons: backend did not provide us the timezone, so we guess the actual point in // time millis = guessTimestamp(millis, tz); return convertToTime(millis, tz); // Ensure date part is 1970-01-01 } /** * Returns the SQL Time object matching the given bytes with {@link Oid#TIME}. * * @param bytes The binary encoded time value. * @return The parsed time object. * @throws PSQLException If binary format could not be parsed. */ public java.time.LocalTime toLocalTimeBin(byte[] bytes) throws PSQLException { if (bytes.length != 8) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "time"), PSQLState.BAD_DATETIME_FORMAT); } long micros; if (usesDouble) { double seconds = ByteConverter.float8(bytes, 0); micros = (long) (seconds * 1000000d); } else { micros = ByteConverter.int8(bytes, 0); } return java.time.LocalTime.ofNanoOfDay(micros * 1000); } /** * Returns the SQL Timestamp object matching the given bytes with {@link Oid#TIMESTAMP} or * {@link Oid#TIMESTAMPTZ}. * * @param tz The timezone used when received data is {@link Oid#TIMESTAMP}, ignored if data * already contains {@link Oid#TIMESTAMPTZ}. * @param bytes The binary encoded timestamp value. * @param timestamptz True if the binary is in GMT. * @return The parsed timestamp object. * @throws PSQLException If binary format could not be parsed. */ public Timestamp toTimestampBin(@Nullable TimeZone tz, byte[] bytes, boolean timestamptz) throws PSQLException { ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(tz, bytes, timestamptz); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } Timestamp ts = new Timestamp(parsedTimestamp.millis); ts.setNanos(parsedTimestamp.nanos); return ts; } private ParsedBinaryTimestamp toParsedTimestampBinPlain(byte[] bytes) throws PSQLException { if (bytes.length != 8) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "timestamp"), PSQLState.BAD_DATETIME_FORMAT); } long secs; int nanos; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); if (time == Double.POSITIVE_INFINITY) { ParsedBinaryTimestamp ts = new ParsedBinaryTimestamp(); ts.infinity = Infinity.POSITIVE; return ts; } else if (time == Double.NEGATIVE_INFINITY) { ParsedBinaryTimestamp ts = new ParsedBinaryTimestamp(); ts.infinity = Infinity.NEGATIVE; return ts; } secs = (long) time; nanos = (int) ((time - secs) * 1000000); } else { long time = ByteConverter.int8(bytes, 0); // compatibility with text based receiving, not strictly necessary // and can actually be confusing because there are timestamps // that are larger than infinite if (time == Long.MAX_VALUE) { ParsedBinaryTimestamp ts = new ParsedBinaryTimestamp(); ts.infinity = Infinity.POSITIVE; return ts; } else if (time == Long.MIN_VALUE) { ParsedBinaryTimestamp ts = new ParsedBinaryTimestamp(); ts.infinity = Infinity.NEGATIVE; return ts; } secs = time / 1000000; nanos = (int) (time - secs * 1000000); } if (nanos < 0) { secs nanos += 1000000; } nanos *= 1000; long millis = secs * 1000L; ParsedBinaryTimestamp ts = new ParsedBinaryTimestamp(); ts.millis = millis; ts.nanos = nanos; return ts; } private ParsedBinaryTimestamp toParsedTimestampBin(@Nullable TimeZone tz, byte[] bytes, boolean timestamptz) throws PSQLException { ParsedBinaryTimestamp ts = toParsedTimestampBinPlain(bytes); if (ts.infinity != null) { return ts; } long secs = ts.millis / 1000L; secs = toJavaSecs(secs); long millis = secs * 1000L; if (!timestamptz) { // Here be dragons: backend did not provide us the timezone, so we guess the actual point in // time millis = guessTimestamp(millis, tz); } ts.millis = millis; return ts; } private ParsedBinaryTimestamp toProlepticParsedTimestampBin(byte[] bytes) throws PSQLException { ParsedBinaryTimestamp ts = toParsedTimestampBinPlain(bytes); if (ts.infinity != null) { return ts; } long secs = ts.millis / 1000L; // postgres epoc to java epoc secs += 946684800L; long millis = secs * 1000L; ts.millis = millis; return ts; } /** * Returns the local date time object matching the given bytes with {@link Oid#TIMESTAMP} or * {@link Oid#TIMESTAMPTZ}. * @param bytes The binary encoded local date time value. * * @return The parsed local date time object. * @throws PSQLException If binary format could not be parsed. */ public java.time.LocalDateTime toLocalDateTimeBin(byte[] bytes) throws PSQLException { ParsedBinaryTimestamp parsedTimestamp = this.toProlepticParsedTimestampBin(bytes); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return java.time.LocalDateTime.MAX; } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return java.time.LocalDateTime.MIN; } // hardcode utc because the backend does not provide us the timezone // Postgres is always UTC return java.time.LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, java.time.ZoneOffset.UTC); } /** * <p>Given a UTC timestamp {@code millis} finds another point in time that is rendered in given time * zone {@code tz} exactly as "millis in UTC".</p> * * <p>For instance, given 7 Jan 16:00 UTC and tz=GMT+02:00 it returns 7 Jan 14:00 UTC == 7 Jan 16:00 * GMT+02:00 Note that is not trivial for timestamps near DST change. For such cases, we rely on * {@link Calendar} to figure out the proper timestamp.</p> * * @param millis source timestamp * @param tz desired time zone * @return timestamp that would be rendered in {@code tz} like {@code millis} in UTC */ private long guessTimestamp(long millis, @Nullable TimeZone tz) { if (tz == null) { // If client did not provide us with time zone, we use system default time zone tz = getDefaultTz(); } // The story here: // Backend provided us with something like '2015-10-04 13:40' and it did NOT provide us with a // time zone. // On top of that, user asked us to treat the timestamp as if it were in GMT+02:00. // The code below creates such a timestamp that is rendered as '2015-10-04 13:40 GMT+02:00' // In other words, its UTC value should be 11:40 UTC == 13:40 GMT+02:00. // It is not sufficient to just subtract offset as you might cross DST change as you subtract. // For instance, on 2000-03-26 02:00:00 Moscow went to DST, thus local time became 03:00:00 // Suppose we deal with 2000-03-26 02:00:01 // If you subtract offset from the timestamp, the time will be "a hour behind" since // "just a couple of hours ago the OFFSET was different" // To make a long story short: we have UTC timestamp that looks like "2000-03-26 02:00:01" when // rendered in UTC tz. // We want to know another timestamp that will look like "2000-03-26 02:00:01" in Europe/Moscow // time zone. if (isSimpleTimeZone(tz.getID())) { // For well-known non-DST time zones, just subtract offset return millis - tz.getRawOffset(); } // For all the other time zones, enjoy debugging Calendar API // Here we do a straight-forward implementation that splits original timestamp into pieces and // composes it back. // Note: cal.setTimeZone alone is not sufficient as it would alter hour (it will try to keep the // same time instant value) Calendar cal = calendarWithUserTz; cal.setTimeZone(utcTz); cal.setTimeInMillis(millis); int era = cal.get(Calendar.ERA); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); int ms = cal.get(Calendar.MILLISECOND); cal.setTimeZone(tz); cal.set(Calendar.ERA, era); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, min); cal.set(Calendar.SECOND, sec); cal.set(Calendar.MILLISECOND, ms); return cal.getTimeInMillis(); } private static boolean isSimpleTimeZone(String id) { return id.startsWith("GMT") || id.startsWith("UTC"); } /** * Extracts the date part from a timestamp. * * @param millis The timestamp from which to extract the date. * @param tz The time zone of the date. * @return The extracted date. */ public Date convertToDate(long millis, @Nullable TimeZone tz) { // no adjustments for the inifity hack values if (millis <= PGStatement.DATE_NEGATIVE_INFINITY || millis >= PGStatement.DATE_POSITIVE_INFINITY) { return new Date(millis); } if (tz == null) { tz = getDefaultTz(); } if (isSimpleTimeZone(tz.getID())) { // Truncate to 00:00 of the day. // Suppose the input date is 7 Jan 15:40 GMT+02:00 (that is 13:40 UTC) // We want it to become 7 Jan 00:00 GMT+02:00 // 1) Make sure millis becomes 15:40 in UTC, so add offset int offset = tz.getRawOffset(); millis += offset; // 2) Truncate hours, minutes, etc. Day is always 86400 seconds, no matter what leap seconds // are millis = floorDiv(millis, ONEDAY) * ONEDAY; // 2) Now millis is 7 Jan 00:00 UTC, however we need that in GMT+02:00, so subtract some // offset millis -= offset; // Now we have brand-new 7 Jan 00:00 GMT+02:00 return new Date(millis); } Calendar cal = calendarWithUserTz; cal.setTimeZone(tz); cal.setTimeInMillis(millis); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Date(cal.getTimeInMillis()); } /** * Extracts the time part from a timestamp. This method ensures the date part of output timestamp * looks like 1970-01-01 in given timezone. * * @param millis The timestamp from which to extract the time. * @param tz timezone to use. * @return The extracted time. */ public Time convertToTime(long millis, TimeZone tz) { if (tz == null) { tz = getDefaultTz(); } if (isSimpleTimeZone(tz.getID())) { // Leave just time part of the day. // Suppose the input date is 2015 7 Jan 15:40 GMT+02:00 (that is 13:40 UTC) // We want it to become 1970 1 Jan 15:40 GMT+02:00 // 1) Make sure millis becomes 15:40 in UTC, so add offset int offset = tz.getRawOffset(); millis += offset; // 2) Truncate year, month, day. Day is always 86400 seconds, no matter what leap seconds are millis = floorMod(millis, ONEDAY); // 2) Now millis is 1970 1 Jan 15:40 UTC, however we need that in GMT+02:00, so subtract some // offset millis -= offset; // Now we have brand-new 1970 1 Jan 15:40 GMT+02:00 return new Time(millis); } Calendar cal = calendarWithUserTz; cal.setTimeZone(tz); cal.setTimeInMillis(millis); cal.set(Calendar.ERA, GregorianCalendar.AD); cal.set(Calendar.YEAR, 1970); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 1); return new Time(cal.getTimeInMillis()); } /** * Returns the given time value as String matching what the current postgresql server would send * in text mode. * * @param time time value * @param withTimeZone whether timezone should be added * @return given time value as String */ public String timeToString(java.util.Date time, boolean withTimeZone) { Calendar cal = null; if (withTimeZone) { cal = calendarWithUserTz; cal.setTimeZone(timeZoneProvider.get()); } if (time instanceof Timestamp) { return toString(cal, (Timestamp) time, withTimeZone); } if (time instanceof Time) { return toString(cal, (Time) time, withTimeZone); } return toString(cal, (Date) time, withTimeZone); } /** * Converts the given postgresql seconds to java seconds. Reverse engineered by inserting varying * dates to postgresql and tuning the formula until the java dates matched. See {@link #toPgSecs} * for the reverse operation. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toJavaSecs(long secs) { // postgres epoc to java epoc secs += 946684800L; // Julian/Gregorian calendar cutoff point if (secs < -12219292800L) { // October 4, 1582 -> October 15, 1582 secs += 86400 * 10; if (secs < -14825808000L) { // 1500-02-28 -> 1500-03-01 int extraLeaps = (int) ((secs + 14825808000L) / 3155760000L); extraLeaps extraLeaps -= extraLeaps / 4; secs += extraLeaps * 86400L; } } return secs; } /** * Converts the given java seconds to postgresql seconds. See {@link #toJavaSecs} for the reverse * operation. The conversion is valid for any year 100 BC onwards. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toPgSecs(long secs) { // java epoc to postgres epoc secs -= 946684800L; // Julian/Gregorian calendar cutoff point if (secs < -13165977600L) { // October 15, 1582 -> October 4, 1582 secs -= 86400 * 10; if (secs < -15773356800L) { // 1500-03-01 -> 1500-02-28 int years = (int) ((secs + 15773356800L) / -3155823050L); years++; years -= years / 4; secs += years * 86400L; } } return secs; } /** * Converts the SQL Date to binary representation for {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @param value value * @throws PSQLException If binary format could not be parsed. */ public void toBinDate(@Nullable TimeZone tz, byte[] bytes, Date value) throws PSQLException { long millis = value.getTime(); if (tz == null) { tz = getDefaultTz(); } // It "getOffset" is UNTESTED // See org.postgresql.jdbc.AbstractJdbc2Statement.setDate(int, java.sql.Date, // java.util.Calendar) // The problem is we typically do not know for sure what is the exact required date/timestamp // type // Thus pgjdbc sticks to text transfer. millis += tz.getOffset(millis); long secs = toPgSecs(millis / 1000); ByteConverter.int4(bytes, 0, (int) (secs / 86400)); } /** * Converts backend's TimeZone parameter to java format. * Notable difference: backend's gmt-3 is GMT+03 in Java. * * @param timeZone time zone to use * @return java TimeZone */ public static TimeZone parseBackendTimeZone(String timeZone) { if (timeZone.startsWith("GMT")) { TimeZone tz = GMT_ZONES.get(timeZone); if (tz != null) { return tz; } } return TimeZone.getTimeZone(timeZone); } private static long floorDiv(long x, long y) { long r = x / y; // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (r * y != x)) { r } return r; } private static long floorMod(long x, long y) { return x - floorDiv(x, y) * y; } }
package org.exist.jetty; import java.io.IOException; import java.io.InputStream; import java.io.LineNumberReader; import java.io.Reader; import java.net.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import javax.servlet.Servlet; import net.jcip.annotations.GuardedBy; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.server.*; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.Jetty; import org.eclipse.jetty.util.MultiException; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.xml.XmlConfiguration; import org.exist.SystemProperties; import org.exist.start.Main; import org.exist.storage.BrokerPool; import org.exist.util.ConfigurationHelper; import org.exist.util.FileUtils; import org.exist.util.SingleInstanceConfiguration; import org.exist.validation.XmlLibraryChecker; import org.exist.xmldb.DatabaseImpl; import org.exist.xmldb.ShutdownListener; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Database; import static org.exist.util.ThreadUtils.newGlobalThread; /** * This class provides a main method to start Jetty with eXist. It registers shutdown * handlers to cleanly shut down the database and the webserver. * * @author wolf */ public class JettyStart extends Observable implements LifeCycle.Listener { public static final String JETTY_HOME_PROP = "jetty.home"; public static final String JETTY_BASE_PROP = "jetty.base"; private static final String JETTY_PROPETIES_FILENAME = "jetty.properties"; private static final Logger logger = LogManager.getLogger(JettyStart.class); public final static String SIGNAL_STARTING = "jetty starting"; public final static String SIGNAL_STARTED = "jetty started"; public final static String SIGNAL_ERROR = "error"; private final static int STATUS_STARTING = 0; private final static int STATUS_STARTED = 1; private final static int STATUS_STOPPING = 2; private final static int STATUS_STOPPED = 3; @GuardedBy("this") private int status = STATUS_STOPPED; @GuardedBy("this") private Optional<Thread> shutdownHookThread = Optional.empty(); @GuardedBy("this") private int primaryPort = 8080; public static void main(final String[] args) { final JettyStart start = new JettyStart(); start.run(args, null); } public JettyStart() { // Additional checks XML libs @@@@ XmlLibraryChecker.check(); } public synchronized void run() { run(true); } public synchronized void run(final boolean standalone) { final String jettyProperty = Optional.ofNullable(System.getProperty(JETTY_HOME_PROP)) .orElseGet(() -> { final Optional<Path> home = ConfigurationHelper.getExistHome(); final Path jettyHome = FileUtils.resolve(home, "tools").resolve("jetty"); final String jettyPath = jettyHome.toAbsolutePath().toString(); System.setProperty(JETTY_HOME_PROP, jettyPath); return jettyPath; }); System.setProperty("org.eclipse.jetty.util.log.class?", "org.eclipse.jetty.util.log.Slf4jLog"); final Path jettyConfig; if (standalone) { jettyConfig = Paths.get(jettyProperty).resolve("etc").resolve(Main.STANDALONE_ENABLED_JETTY_CONFIGS); } else { jettyConfig = Paths.get(jettyProperty).resolve("etc").resolve(Main.STANDARD_ENABLED_JETTY_CONFIGS); } run(new String[] { jettyConfig.toAbsolutePath().toString() }, null); } public synchronized void run(final String[] args, final Observer observer) { if (args.length == 0) { logger.error("No configuration file specified!"); return; } Path jettyConfig = Paths.get(args[0]); boolean configFromClasspath = false; if (Files.notExists(jettyConfig)) { logger.warn("Configuration file: {} does not exist!", jettyConfig.toAbsolutePath().toString()); final String jettyConfigFileName = FileUtils.fileName(jettyConfig.getFileName()); logger.warn("Fallback... searching for configuration file on classpath: {}.etc/{}", getClass().getPackage().getName(), jettyConfigFileName); final URL jettyConfigUrl = getClass().getResource("etc/" + jettyConfigFileName); if (jettyConfigUrl != null) { try { jettyConfig = Paths.get(jettyConfigUrl.toURI()); configFromClasspath = true; } catch (final URISyntaxException e) { logger.error("Unable to retrieve configuration file from classpath: {}", e.getMessage(), e); return; } } else { logger.error("Unable to find configuration file on classpath!"); return; } } final Map<String, String> configProperties; try { configProperties = getConfigProperties(jettyConfig.getParent()); // modify JETTY_HOME and JETTY_BASE properties when running with classpath config if (configFromClasspath) { final String jettyClasspathHome = jettyConfig.getParent().getParent().toAbsolutePath().toString(); System.setProperty(JETTY_HOME_PROP, jettyClasspathHome); configProperties.put(JETTY_HOME_PROP, jettyClasspathHome); configProperties.put(JETTY_BASE_PROP, jettyClasspathHome); } if (observer != null) { addObserver(observer); } logger.info("Running with Java {} [{} ({}) in {}]", System.getProperty("java.version", "(unknown java.version)"), System.getProperty("java.vendor", "(unknown java.vendor)"), System.getProperty("java.vm.name", "(unknown java.vm.name)"), System.getProperty("java.home", "(unknown java.home)") ); logger.info("Running as user '{}'", System.getProperty("user.name", "(unknown user.name)")); logger.info("[eXist Home : {}]", System.getProperty("exist.home", "unknown")); logger.info("[eXist Version : {}]", SystemProperties.getInstance().getSystemProperty("product-version", "unknown")); logger.info("[eXist Build : {}]", SystemProperties.getInstance().getSystemProperty("product-build", "unknown")); logger.info("[Git commit : {}]", SystemProperties.getInstance().getSystemProperty("git-commit", "unknown")); logger.info("[Operating System : {} {} {}]", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")); logger.info("[log4j.configurationFile : {}]", System.getProperty("log4j.configurationFile")); logger.info("[jetty Version: {}]", Jetty.VERSION); logger.info("[{} : {}]", JETTY_HOME_PROP, configProperties.get(JETTY_HOME_PROP)); logger.info("[{} : {}]", JETTY_BASE_PROP, configProperties.get(JETTY_BASE_PROP)); logger.info("[jetty configuration : {}]", jettyConfig.toAbsolutePath().toString()); // configure the database instance SingleInstanceConfiguration config; if (args.length == 2) { config = new SingleInstanceConfiguration(args[1]); } else { config = new SingleInstanceConfiguration(); } logger.info("Configuring eXist from {}", config.getConfigFilePath() .map(Path::normalize).map(Path::toAbsolutePath).map(Path::toString) .orElse("<UNKNOWN>")); BrokerPool.configure(1, 5, config, Optional.ofNullable(observer)); // register the XMLDB driver final Database xmldb = new DatabaseImpl(); xmldb.setProperty("create-database", "false"); DatabaseManager.registerDatabase(xmldb); } catch (final Exception e) { logger.error("configuration error: " + e.getMessage(), e); e.printStackTrace(); return; } try { // load jetty configurations final List<Path> configFiles = getEnabledConfigFiles(jettyConfig); final List<Object> configuredObjects = new ArrayList<>(); XmlConfiguration last = null; for(final Path confFile : configFiles) { logger.info("[loading jetty configuration : {}]", confFile.toString()); try(final InputStream is = Files.newInputStream(confFile)) { final XmlConfiguration configuration = new XmlConfiguration(is); if (last != null) { configuration.getIdMap().putAll(last.getIdMap()); } configuration.getProperties().putAll(configProperties); configuredObjects.add(configuration.configure()); last = configuration; } } // start Jetty final Optional<Server> maybeServer = startJetty(configuredObjects); if(!maybeServer.isPresent()) { logger.error("Unable to find a server to start in jetty configurations"); throw new IllegalStateException(); } final Server server = maybeServer.get(); final Connector[] connectors = server.getConnectors(); // Construct description of all ports opened. final StringBuilder allPorts = new StringBuilder(); if (connectors.length > 1) { // plural s allPorts.append("s"); } boolean establishedPrimaryPort = false; for(final Connector connector : connectors) { if(connector instanceof NetworkConnector) { final NetworkConnector networkConnector = (NetworkConnector)connector; if(!establishedPrimaryPort) { this.primaryPort = networkConnector.getLocalPort(); establishedPrimaryPort = true; } allPorts.append(" "); allPorts.append(networkConnector.getLocalPort()); } } //TODO: use pluggable interface Class<?> iprange = null; try { iprange = Class.forName("org.exist.security.realm.iprange.IPRangeServlet"); } catch (final NoClassDefFoundError | ClassNotFoundException e) { logger.warn("Could not find IPRangeServlet extension. IPRange will be disabled!"); } /** * See {@link Server#getURI()} */ private List<URI> getSeverURIs(final Server server) { final ContextHandler context = server.getChildHandlerByClass(ContextHandler.class); return Arrays.stream(server.getConnectors()) .filter(connector -> connector instanceof NetworkConnector) .map(connector -> (NetworkConnector)connector) .map(networkConnector -> getURI(networkConnector, context)) .filter(Objects::nonNull) .collect(Collectors.toList()); } /** * See {@link Server#getURI()} */ private URI getURI(final NetworkConnector networkConnector, final ContextHandler context) { try { final String protocol = networkConnector.getDefaultConnectionFactory().getProtocol(); final String scheme; if (protocol.startsWith("SSL-") || protocol.equals("SSL")) { scheme = "https"; } else { scheme = "http"; } String host = null; if (context != null && context.getVirtualHosts() != null && context.getVirtualHosts().length > 0) { host = context.getVirtualHosts()[0]; } else { host = networkConnector.getHost(); } if (host == null) { host = InetAddress.getLocalHost().getHostAddress(); } String path = context == null ? null : context.getContextPath(); if (path == null) { path = "/"; } return new URI(scheme, null, host, networkConnector.getLocalPort(), path, null, null); } catch(final UnknownHostException | URISyntaxException e) { logger.warn(e); return null; } } private Optional<Server> startJetty(final List<Object> configuredObjects) throws Exception { Optional<Server> server = Optional.empty(); for (final Object configuredObject : configuredObjects) { if(configuredObject instanceof Server) { final Server _server = (Server)configuredObject; //skip this server if we have already started it if(server.map(configuredServer -> configuredServer == _server).orElse(false)) { continue; } //setup server shutdown _server.addLifeCycleListener(this); BrokerPool.getInstance().registerShutdownListener(new ShutdownListenerImpl(_server)); // register a shutdown hook for the server final BrokerPoolAndJettyShutdownHook brokerPoolAndJettyShutdownHook = new BrokerPoolAndJettyShutdownHook(_server); final Thread shutdownHookThread = newGlobalThread("BrokerPoolsAndJetty.ShutdownHook", brokerPoolAndJettyShutdownHook); this.shutdownHookThread = Optional.of(shutdownHookThread); Runtime.getRuntime().addShutdownHook(shutdownHookThread); server = Optional.of(_server); } if (configuredObject instanceof LifeCycle) { final LifeCycle lc = (LifeCycle)configuredObject; if (!lc.isRunning()) { logger.info("[Starting jetty component : {}]", lc.getClass().getName()); lc.start(); } } } return server; } private Map<String, String> getConfigProperties(final Path configDir) throws IOException { final Map<String, String> configProperties = new HashMap<>(); //load jetty.properties file final Path propertiesFile = configDir.resolve(JETTY_PROPETIES_FILENAME); if(Files.exists(propertiesFile)) { final Properties jettyProperties = new Properties(); try(final Reader reader = Files.newBufferedReader(propertiesFile)) { jettyProperties.load(reader); logger.info("Loaded jetty.properties from: {}", propertiesFile.toAbsolutePath().toString()); for(final Map.Entry<Object, Object> property : jettyProperties.entrySet()) { configProperties.put(property.getKey().toString(), property.getValue().toString()); } } } // set or override jetty.home and jetty.base with System properties configProperties.put(JETTY_HOME_PROP, System.getProperty(JETTY_HOME_PROP)); configProperties.put(JETTY_BASE_PROP, System.getProperty(JETTY_BASE_PROP, System.getProperty(JETTY_HOME_PROP))); return configProperties; } private List<Path> getEnabledConfigFiles(final Path enabledJettyConfigs) throws IOException { if(Files.notExists(enabledJettyConfigs)) { throw new IOException("Cannot find config enabler: " + enabledJettyConfigs.toString()); } else { final List<Path> configFiles = new ArrayList<>(); try (final LineNumberReader reader = new LineNumberReader(Files.newBufferedReader(enabledJettyConfigs))) { String line = null; while ((line = reader.readLine()) != null) { final String tl = line.trim(); if (tl.isEmpty() || tl.charAt(0) == ' continue; } else { final Path configFile = enabledJettyConfigs.getParent().resolve(tl); if (Files.notExists(configFile)) { throw new IOException("Cannot find enabled config: " + configFile.toString()); } else { configFiles.add(configFile); } } } } return configFiles; } } public synchronized void shutdown() { shutdownHookThread.ifPresent(Runtime.getRuntime()::removeShutdownHook); BrokerPool.stopAll(false); while (status != STATUS_STOPPED) { try { wait(); } catch (final InterruptedException e) { // ignore } } } /** * This class gets called after the database received a shutdown request. * * @author wolf */ private static class ShutdownListenerImpl implements ShutdownListener { private final Server server; ShutdownListenerImpl(final Server server) { this.server = server; } @Override public void shutdown(final String dbname, final int remainingInstances) { logger.info("Database shutdown: stopping server in 1sec ..."); if (remainingInstances == 0) { // give the webserver a 1s chance to complete open requests final Timer timer = new Timer("jetty shutdown schedule", true); timer.schedule(new TimerTask() { @Override public void run() { try { // stop the server server.stop(); server.join(); } catch (final Exception e) { e.printStackTrace(); } } }, 1000); // timer.schedule } } } private static class BrokerPoolAndJettyShutdownHook implements Runnable { private final Server server; BrokerPoolAndJettyShutdownHook(final Server server) { this.server = server; } @Override public void run() { BrokerPool.stopAll(true); if (server.isStopping() || server.isStopped()) { return; } try { server.stop(); } catch (final Exception e) { e.printStackTrace(); } } } public synchronized boolean isStarted() { if (status == STATUS_STARTED || status == STATUS_STARTING) { return true; } if (status == STATUS_STOPPED) { return false; } while (status != STATUS_STOPPED) { try { wait(); } catch (final InterruptedException e) { } } return false; } @Override public synchronized void lifeCycleStarting(final LifeCycle lifeCycle) { logger.info("Jetty server starting..."); setChanged(); notifyObservers(SIGNAL_STARTING); status = STATUS_STARTING; notifyAll(); } @Override public synchronized void lifeCycleStarted(final LifeCycle lifeCycle) { logger.info("Jetty server started."); setChanged(); notifyObservers(SIGNAL_STARTED); status = STATUS_STARTED; notifyAll(); } @Override public void lifeCycleFailure(final LifeCycle lifeCycle, final Throwable throwable) { } @Override public synchronized void lifeCycleStopping(final LifeCycle lifeCycle) { logger.info("Jetty server stopping..."); status = STATUS_STOPPING; notifyAll(); } @Override public synchronized void lifeCycleStopped(final LifeCycle lifeCycle) { logger.info("Jetty server stopped"); status = STATUS_STOPPED; notifyAll(); } public synchronized int getPrimaryPort() { return primaryPort; } }
package verification.platu.logicAnalysis; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import javax.swing.JOptionPane; import lpn.parser.Abstraction; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import verification.platu.MDD.MDT; import verification.platu.MDD.Mdd; import verification.platu.MDD.mddNode; import verification.platu.common.IndexObjMap; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.LpnTranList; import verification.platu.main.Options; import verification.platu.partialOrders.DependentSet; import verification.platu.partialOrders.DependentSetComparator; import verification.platu.partialOrders.StaticSets; import verification.platu.project.PrjState; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.StateSet; public class Analysis { private LinkedList<Transition> traceCex; protected Mdd mddMgr = null; private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>(); private String PORdebugFileName; private FileWriter PORdebugFileStream; private BufferedWriter PORdebugBufferedWriter; /* * visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back. */ private HashSet<Transition> visitedTrans; public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) { traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (method.equals("dfs")) { //if (Options.getPOR().equals("off")) { //this.search_dfs(lpnList, initStateArray); //this.search_dfs_mdd_1(lpnList, initStateArray); //this.search_dfs_mdd_2(lpnList, initStateArray); //else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); } else if (method.equals("bfs")==true) this.search_bfs(lpnList, initStateArray); else if (method == "dfs_noDisabling") //this.search_dfs_noDisabling(lpnList, initStateArray); this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * This constructor performs dfs. * @param lpnList */ public Analysis(StateGraph[] lpnList){ traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (Options.getDebugMode()) { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; try { PORdebugFileStream = new FileWriter(PORdebugFileName); } catch (IOException e) { e.printStackTrace(); } PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } // if (method.equals("dfs")) { // //if (Options.getPOR().equals("off")) { // this.search_dfs(lpnList, initStateArray, applyPOR); // //this.search_dfs_mdd_1(lpnList, initStateArray); // //this.search_dfs_mdd_2(lpnList, initStateArray); // //else // // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); // else if (method.equals("bfs")==true) // this.search_bfs(lpnList, initStateArray); // else if (method == "dfs_noDisabling") // //this.search_dfs_noDisabling(lpnList, initStateArray); // this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * Recursively find all reachable project states. */ int iterations = 0; int stack_depth = 0; int max_stack_depth = 0; public void search_recursive(final StateGraph[] lpnList, final State[] curPrjState, final ArrayList<LinkedList<Transition>> enabledList, HashSet<PrjState> stateTrace) { int lpnCnt = lpnList.length; HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); stack_depth++; if (stack_depth > max_stack_depth) max_stack_depth = stack_depth; iterations++; if (iterations % 50000 == 0) System.out.println("iterations: " + iterations + ", # of prjStates found: " + prjStateSet.size() + ", max_stack_depth: " + max_stack_depth); for (int index = 0; index < lpnCnt; index++) { LinkedList<Transition> curEnabledSet = enabledList.get(index); if (curEnabledSet == null) continue; for (Transition firedTran : curEnabledSet) { // while(curEnabledSet.size() != 0) { // LPNTran firedTran = curEnabledSet.removeFirst(); // TODO: (check) Not sure if lpnList[index] is correct State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran); // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. PrjState nextPrjState = new PrjState(nextStateArray); if (stateTrace.contains(nextPrjState) == true) ;// System.out.println("found a cycle"); if (prjStateSet.add(nextPrjState) == false) { continue; } // Get the list of enabled transition sets, and call // findsg_recursive. ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>(); for (int i = 0; i < lpnCnt; i++) { if (curPrjState[i] != nextStateArray[i]) { StateGraph Lpn_tmp = lpnList[i]; nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran, // enabledList.get(i), // false)); } else { nextEnabledList.add(i, enabledList.get(i)); } } stateTrace.add(nextPrjState); search_recursive(lpnList, nextStateArray, nextEnabledList, stateTrace); stateTrace.remove(nextPrjState); } } } /** * An iterative implement of findsg_recursive(). * * @param sgList * @param start * @param curLocalStateArray * @param enabledArray */ public StateGraph[] search_dfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function search_dfs"); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; //Stack<State[]> stateStack = new Stack<State[]>(); HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); //HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // Set of PrjStates that have been seen before. Set class documentation // for how it behaves. Timing Change. StateSet prjStateSet = new StateSet(); PrjState initPrjState; // Create the appropriate type for the PrjState depending on whether timing is // being used or not. Timing Change. if(!Options.getTimingAnalysisFlag()){ // If not doing timing. initPrjState = new PrjState(initStateArray); } else{ // If timing is enabled. initPrjState = new TimedPrjState(initStateArray); // Set the initial values of the inequality variables. //((TimedPrjState) initPrjState).updateInequalityVariables(); } prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% stateStackTop %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) { // printDstLpnList(sgList); } boolean init = true; LpnTranList initEnabled; if(!Options.getTimingAnalysisFlag()){ // Timing Change. initEnabled = sgList[0].getEnabled(initStateArray[0], init); } else { // When timing is enabled, it is the project state that will determine // what is enabled since it contains the zone. This indicates the zeroth zone // contained in the project and the zeroth LPN to get the transitions from. initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0); } lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); init = false; if (Options.getDebugMode()) { // System.out.println("call getEnabled on initStateArray at 0: "); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet(initEnabled, ""); } boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); if (failureTranIsEnabled(curEnabled)) { return null; } if (Options.getDebugMode()) { // printStateArray(curStateArray); // System.out.println("+++++++ curEnabled trans ++++++++"); // printTransLinkedList(curEnabled); } // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); if (Options.getDebugMode()) { // System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // System.out.println(" // printLpnTranStack(lpnTranStack); } curIndexStack.pop(); curIndex++; while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); if(!Options.getTimingAnalysisFlag()){ // Timing Change curEnabled = (sgList[curIndex].getEnabled(curStateArray[curIndex], init)).clone(); } else{ // Get the enabled transitions from the zone that are associated with // the current LPN. curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex); } if (curEnabled.size() > 0) { if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curEnabled); } lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); if (Options.getDebugMode()) { //printIntegerStack("curIndexStack after push 1", curIndexStack); } break; } curIndex++; } } if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curEnabled.removeLast(); if (Options.getDebugMode()) { // System.out.println(" // System.out.println("Fired transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); // System.out.println(" } State[] nextStateArray; PrjState nextPrjState; // Moved this definition up. Timing Change. // The next state depends on whether timing is in use or not. // Timing Change. if(!Options.getTimingAnalysisFlag()){ // Get the next states from the fire method and define the next project state. nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); nextPrjState = new PrjState(nextStateArray); } else{ // Get the next timed state and extract the next un-timed states. nextPrjState = sgList[curIndex].fire(sgList, stateStackTop, (EventSet) firedTran); nextStateArray = nextPrjState.toStateArray(); } tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns]; for (int i = 0; i < numLpns; i++) { StateGraph sg = sgList[i]; LinkedList<Transition> enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(curStateArray[i], init); } else{ // Get the enabled transitions from the Zone for the appropriate // LPN. //enabledList = ((TimedPrjState) stateStackTop).getEnabled(i); enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i); } curEnabledArray[i] = enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(nextStateArray[i], init); } else{ //enabledList = ((TimedPrjState) nextPrjState).getEnabled(i); enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i); } nextEnabledArray[i] = enabledList; if (Options.getReportDisablingError()) { Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } if(!Options.getTimingAnalysisFlag()){ if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } } //PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change. Boolean existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState); if (existingState == false) { prjStateSet.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } } stateStackTop = nextPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextEnabledArray[0], ""); } lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); if (Options.getDebugMode()) { // printLpnTranStack(lpnTranStack); } curIndexStack.push(0); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt //+ ", # of prjStates found: " + totalStateCnt + ", " + prjStateSet.stateString() + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { System.out.println("outputSGPath = " + Options.getPrjSgPath()); drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true); } return sgList; } private boolean failureCheck(LinkedList<Transition> curEnabled) { boolean failureTranIsEnabled = false; for (Transition tran : curEnabled) { if (tran.isFail()) { JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getName() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } private boolean failureTranIsEnabled(LinkedList<Transition> curAmpleTrans) { boolean failureTranIsEnabled = false; for (Transition tran : curAmpleTrans) { if (tran.isFail()) { JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getName() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } private void drawGlobalStateGraph(StateGraph[] sgList, HashSet<PrjState> prjStateSet, boolean fullSG) { try { String fileName = null; if (fullSG) { fileName = Options.getPrjSgPath() + "full_sg.dot"; } else { fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_" + Options.getCycleClosingMthd().toLowerCase() + "_" + Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot"; } BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (PrjState curGlobalState : prjStateSet) { // Build composite current global state. String curVarNames = ""; String curVarValues = ""; String curMarkings = ""; String curEnabledTrans = ""; String curGlobalStateIndex = ""; HashMap<String, Integer> vars = new HashMap<String, Integer>(); for (State curLocalState : curGlobalState.toStateArray()) { LhpnFile curLpn = curLocalState.getLpn(); for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) { //System.out.println(curLpn.getVarIndexMap().getKey(i) + " = " + curLocalState.getVector()[i]); vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVector()[i]); } curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState); if (!boolArrayToString("enabled trans", curLocalState).equals("")) curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState); curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); curVarValues = curVarValues + vValue + ", "; curVarNames = curVarNames + vName + ", "; } if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) { curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(",")); curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(",")); } curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length()); curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length()); curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n"); out.write(curGlobalStateIndex + "[shape=\"ellipse\",label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n"); // // Build composite next global states. HashMap<Transition, PrjState> nextStateMap = curGlobalState.getNextStateMap(); for (Transition outTran : nextStateMap.keySet()) { PrjState nextGlobalState = nextStateMap.get(outTran); String nextVarNames = ""; String nextVarValues = ""; String nextMarkings = ""; String nextEnabledTrans = ""; String nextGlobalStateIndex = ""; for (State nextLocalState : nextGlobalState.toStateArray()) { LhpnFile nextLpn = nextLocalState.getLpn(); for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) { vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVector()[i]); } nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState); if (!boolArrayToString("enabled trans", nextLocalState).equals("")) nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState); nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); nextVarValues = nextVarValues + vValue + ", "; nextVarNames = nextVarNames + vName + ", "; } if (!nextVarNames.isEmpty() && !nextVarValues.isEmpty()) { nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(",")); nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(",")); } nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length()); nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length()); nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + nextVarNames + ">\"]\n"); out.write(nextGlobalStateIndex + "[shape=\"ellipse\",label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n"); String outTranName = outTran.getName(); if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void drawDependencyGraphs(LhpnFile[] lpnList, HashMap<Transition, StaticSets> staticSetsMap) { String fileName = Options.getPrjSgPath() + "dependencyGraph.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (Transition curTran : staticSetsMap.keySet()) { String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getName(); out.write(curTranStr + "[shape=\"box\"];"); out.newLine(); } for (Transition curTran : staticSetsMap.keySet()) { StaticSets curStaticSets = staticSetsMap.get(curTran); String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getName(); for (Transition curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) { String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getName(); out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];"); out.newLine(); } // for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];"); // out.newLine(); // for (Transition curTranInDisable : curStaticSets.getDisableSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];"); // out.newLine(); HashSet<Transition> enableByBringingToken = new HashSet<Transition>(); for (Place p : curTran.getPreset()) { for (Transition presetTran : p.getPreset()) { enableByBringingToken.add(presetTran); } } for (Transition curTranInCanEnable : enableByBringingToken) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getName(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];"); out.newLine(); } for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) { for (Transition curTranInCanEnable : canEnableOneConjunctSet) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getName(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];"); out.newLine(); } } } out.write("}"); out.close(); } catch (IOException e) { e.printStackTrace(); } } private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVector().length; i++) { arrayStr = arrayStr + curState.getVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabled trans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ","; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printStateArray(State[] stateArray) { for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +") -> "); System.out.print("markings: " + intArrayToString("markings", stateArray[i]) + " / "); System.out.print("enabled trans: " + boolArrayToString("enabled trans", stateArray[i]) + " / "); System.out.print("var values: " + intArrayToString("vars", stateArray[i]) + " / "); System.out.print("\n"); } } private void printTransLinkedList(LinkedList<Transition> curPop) { for (int i=0; i< curPop.size(); i++) { System.out.print(curPop.get(i).getName() + " "); } System.out.println(""); } private void printIntegerStack(String stackName, Stack<Integer> curIndexStack) { System.out.println("+++++++++" + stackName + "+++++++++"); for (int i=0; i < curIndexStack.size(); i++) { System.out.println(stackName + "[" + i + "]" + curIndexStack.get(i)); } System.out.println(" } private void printDstLpnList(StateGraph[] lpnList) { System.out.println("++++++ dstLpnList ++++++"); for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); System.out.println("LPN: " + curLPN.getLabel()); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j< allTrans.length; j++) { System.out.print(allTrans[j].getName() + ": "); for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) { System.out.print(allTrans[j].getDstLpnList().get(k).getLabel() + ","); } System.out.print("\n"); } System.out.println(" } System.out.println("++++++++++++++++++++"); } private void constructDstLpnList(StateGraph[] lpnList) { for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j<allTrans.length; j++) { Transition curTran = allTrans[j]; for (int k=0; k<lpnList.length; k++) { curTran.setDstLpnList(lpnList[k].getLpn()); } } } } /** * This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs. * @param sgList * @param initStateArray * @param cycleClosingMthdIndex * @return */ @SuppressWarnings("unchecked") public StateGraph[] search_dfs_por_traceback(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function search_dfsPOR"); System.out.println("---> " + Options.getPOR()); System.out.println("---> " + Options.getCycleClosingMthd()); System.out.println("---> " + Options.getCycleClosingAmpleMethd()); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; LhpnFile[] lpnList = new LhpnFile[numLpns]; for (int i=0; i<numLpns; i++) { lpnList[i] = sgList[i].getLpn(); } HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% stateStackTop %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) { // printDstLpnList(sgList); createPORDebugFile(); } // Find static pieces for POR. HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length); HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>(); HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>(); HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>(); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions()); Abstraction abs = new Abstraction(lpnList[lpnIndex]); abs.decomposeLpnIntoProcesses(); allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs(); HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>(); for (Transition curTran: allProcessTransInOneLpn.keySet()) { Integer procId = allProcessTransInOneLpn.get(curTran); if (!processMapForOneLpn.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (newProcess.getStateMachineFlag() && ((curTran.getPreset().length > 1) || (curTran.getPostset().length > 1))) { newProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { newProcess.addPlaceToProcess(p); } } processMapForOneLpn.put(procId, newProcess); allTransitionsToLpnProcesses.put(curTran, newProcess); } else { LpnProcess curProcess = processMapForOneLpn.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (curProcess.getStateMachineFlag() && (curTran.getPreset().length > 1 || curTran.getPostset().length > 1)) { curProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { curProcess.addPlaceToProcess(p); } } allTransitionsToLpnProcesses.put(curTran, curProcess); } } } HashMap<Transition, Integer> tranFiringFreq = null; if (Options.getUseDependentQueue()) tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size()); // Need to build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets. for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { for (Transition curTran: allTransitions.get(lpnIndex)) { if (curTran.getEnablingTree() != null) curTran.buildConjunctsOfEnabling(curTran.getEnablingTree()); } } for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("=======LPN = " + lpnList[lpnIndex].getLabel() + "======="); } for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitionsToLpnProcesses); curStatic.buildOtherTransSetCurTranEnablingTrue(); curStatic.buildCurTranDisableOtherTransSet(); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(); else curStatic.buildModifyAssignSet(); staticSetsMap.put(curTran, curStatic); if (Options.getUseDependentQueue()) tranFiringFreq.put(curTran, 0); } } if (Options.getDebugMode()) { writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap); } boolean init = true; //LpnTranList initAmpleTrans = new LpnTranList(); LpnTranList initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, lpnList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); init = false; if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++"); // printTransitionSet(initAmpleTrans, ""); drawDependencyGraphs(lpnList, staticSetsMap); } // HashSet<Transition> initAmple = new HashSet<Transition>(); // for (Transition t: initAmpleTrans) { // initAmple.add(t); updateLocalAmpleTbl(initAmpleTrans, sgList, initStateArray); boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); if (failureTranIsEnabled(curAmpleTrans)) { return null; } if (curAmpleTrans.size() == 0) { lpnTranStack.pop(); prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // System.out.println(" // printLpnTranStack(lpnTranStack); //// System.out.println(" //// printStateStack(stateStack); // System.out.println(" // printPrjStateSet(prjStateSet); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); //Transition firedTran = curAmpleTrans.removelast(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" writeStringWithEndOfLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); writeStringWithEndOfLineToPORDebugFile(" } if (Options.getUseDependentQueue()) { Integer freq = tranFiringFreq.get(firedTran) + 1; tranFiringFreq.put(firedTran, freq); if (Options.getDebugMode()) { // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, sgList); } } State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. if (Options.getReportDisablingError()) { for (int i=0; i<numLpns; i++) { Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } LpnTranList nextAmpleTrans = new LpnTranList(); nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop); // check for possible deadlock if (nextAmpleTrans.size() == 0) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } PrjState nextPrjState = new PrjState(nextStateArray); Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); if (existingState == false) { if (Options.getDebugMode()) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); } if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack @ 2++++++++"); // printTransitionSet((LpnTranList) nextAmpleTrans, ""); } lpnTranStack.push((LinkedList<Transition>) nextAmpleTrans.clone()); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) { if (Options.getDebugMode()) { // System.out.println("%%%%%%% Cycle Closing %%%%%%%%"); } HashSet<Transition> nextAmpleSet = new HashSet<Transition>(); HashSet<Transition> curAmpleSet = new HashSet<Transition>(); for (Transition t : nextAmpleTrans) nextAmpleSet.add(t); for (Transition t: curAmpleTrans) curAmpleSet.add(t); curAmpleSet.add(firedTran); HashSet<Transition> newNextAmple = new HashSet<Transition>(); newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap, tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); if (newNextAmple != null && !newNextAmple.isEmpty()) { //LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getDebugMode()) { // System.out.println("nextPrjState: "); // printStateArray(nextPrjState.toStateArray()); // System.out.println("nextStateMap for nextPrjState: "); // printNextStateMap(nextPrjState.getNextStateMap()); } stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("nextStateMap for stateStackTop: "); // printNextStateMap(nextPrjState.getNextStateMap()); } lpnTranStack.push((LinkedList<Transition>) newNextAmple.clone()); if (Options.getDebugMode()) { // System.out.println("+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++"); // printTransitionSet((LpnTranList) newNextAmpleTrans, ""); // printLpnTranStack(lpnTranStack); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); } } if (Options.getDebugMode()) { try { PORdebugBufferedWriter.close(); PORdebugFileStream.close(); } catch (IOException e) { e.printStackTrace(); } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { drawGlobalStateGraph(sgList, prjStateSet, false); } return sgList; } private void createPORDebugFile() { try { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; PORdebugFileStream = new FileWriter(PORdebugFileName, true); PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing the debugging file for partial order reduction."); } } private void writeStringWithEndOfLineToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writeStringToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); //PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt, double peakTotalMem, double peakUsedMem) { try { String fileName = null; if (isPOR) { fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; } else fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log"; BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n"); out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t" + peakUsedMem + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void printLpnTranStack(Stack<LinkedList<Transition>> lpnTranStack) { for (int i=0; i<lpnTranStack.size(); i++) { LinkedList<Transition> tranList = lpnTranStack.get(i); for (int j=0; j<tranList.size(); j++) { System.out.println(tranList.get(j).getName()); } System.out.println(" } } private void printNextStateMap(HashMap<Transition, PrjState> nextStateMap) { for (Transition t: nextStateMap.keySet()) { System.out.print(t.getName() + " -> "); State[] stateArray = nextStateMap.get(t).getStateArray(); for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + ", "); } System.out.print("\n"); } } // private HashSet<Transition> getTransition(LpnTranList ampleTrans) { // HashSet<Transition> ample = new HashSet<Transition>(); // for (Transition tran : ampleTrans) { // ample.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // return ample; private LpnTranList convertToLpnTranList(HashSet<Transition> newNextAmple) { LpnTranList newNextAmpleTrans = new LpnTranList(); for (Transition lpnTran : newNextAmple) { newNextAmpleTrans.add(lpnTran); } return newNextAmpleTrans; } private HashSet<Transition> computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<Transition, StaticSets> staticSetsMap, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet, PrjState nextPrjState, HashSet<Transition> nextAmple, HashSet<Transition> curAmple, HashSet<PrjState> stateStack) { for (State s : nextStateArray) if (s == null) throw new NullPointerException(); String cycleClosingMthd = Options.getCycleClosingMthd(); HashSet<Transition> newNextAmple = new HashSet<Transition>(); HashSet<Transition> nextEnabled = new HashSet<Transition>(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (nextStateArray[lpnIndex].getTranVector()[i]) nextEnabled.add(tran); if (curStateArray[lpnIndex].getTranVector()[i]) curEnabled.add(tran); } } // Cycle closing on global state graph if (Options.getDebugMode()) { //System.out.println("~~~~~~~ existing global state ~~~~~~~~"); } if (cycleClosingMthd.equals("strong")) { newNextAmple.addAll(setSubstraction(curEnabled, nextAmple)); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } else if (cycleClosingMthd.equals("behavioral")) { if (Options.getDebugMode()) { } HashSet<Transition> curReduced = setSubstraction(curEnabled, curAmple); HashSet<Transition> oldNextAmple = new HashSet<Transition>(); DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // TODO: Is oldNextAmple correctly obtained below? if (Options.getDebugMode()) { // printStateArray(nextStateArray); } for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) { if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) { LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]); if (Options.getDebugMode()) { // printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans"); } for (Transition oldLocalTran : oldLocalNextAmpleTrans) oldNextAmple.add(oldLocalTran); } } HashSet<Transition> ignored = setSubstraction(curReduced, oldNextAmple); boolean isCycleClosingAmpleComputation = true; for (Transition seed : ignored) { HashSet<Transition> dependent = new HashSet<Transition>(); dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, isCycleClosingAmpleComputation); if (Options.getDebugMode()) { // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); } // TODO: Is this still necessary? // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); DependentSet dependentSet = new DependentSet(dependent, seed,isDummyTran(seed.getName())); dependentSetQueue.add(dependentSet); } cachedNecessarySets.clear(); if (!dependentSetQueue.isEmpty()) { // System.out.println("depdentSetQueue is NOT empty."); // newNextAmple = dependentSetQueue.poll().getDependent(); // TODO: Will newNextAmpleTmp - oldNextAmple be safe? HashSet<Transition> newNextAmpleTmp = dependentSetQueue.poll().getDependent(); newNextAmple = setSubstraction(newNextAmpleTmp, oldNextAmple); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } if (Options.getDebugMode()) { // printIntegerSet(newNextAmple, sgList, "newNextAmple"); } } else if (cycleClosingMthd.equals("state_search")) { // TODO: complete cycle closing check for state search. } return newNextAmple; } private void updateLocalAmpleTbl(LpnTranList nextAmpleTrans, StateGraph[] sgList, State[] nextStateArray) { // Ample set at each state is stored in the enabledSetTbl in each state graph. for (Transition lpnTran : nextAmpleTrans) { State nextState = nextStateArray[lpnTran.getLpn().getLpnIndex()]; LpnTranList a = sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().get(nextState); if (a != null) { if (!a.contains(lpnTran)) a.add(lpnTran); } else { LpnTranList newLpnTranList = new LpnTranList(); newLpnTranList.add(lpnTran); sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpn().getLpnIndex()], newLpnTranList); if (Options.getDebugMode()) { // System.out.println("@ updateLocalAmpleTbl: "); // System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of " // + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + "."); } } } if (Options.getDebugMode()) { // printEnabledSetTbl(sgList); } } private void printPrjStateSet(HashSet<PrjState> prjStateSet) { for (PrjState curGlobal : prjStateSet) { State[] curStateArray = curGlobal.toStateArray(); printStateArray(curStateArray); System.out.println(" } } // /** // * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back. // * @param sgList // * @param initStateArray // * @param cycleClosingMthdIndex // * @return // */ // public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) { // if (cycleClosingMthdIndex == 1) // else if (cycleClosingMthdIndex == 2) // else if (cycleClosingMthdIndex == 4) // double peakUsedMem = 0; // double peakTotalMem = 0; // boolean failure = false; // int tranFiringCnt = 0; // int totalStates = 1; // int numLpns = sgList.length; // HashSet<PrjState> stateStack = new HashSet<PrjState>(); // Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); // Stack<Integer> curIndexStack = new Stack<Integer>(); // HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // PrjState initPrjState = new PrjState(initStateArray); // prjStateSet.add(initPrjState); // PrjState stateStackTop = initPrjState; // System.out.println("%%%%%%% Add states to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.add(stateStackTop); // // Prepare static pieces for POR // HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>(); // Transition[] allTransitions = sgList[0].getLpn().getAllTransitions(); // HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>(); // HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length); // for (Transition curTran: allTransitions) { // StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions); // curStatic.buildDisableSet(); // curStatic.buildEnableSet(); // curStatic.buildModifyAssignSet(); // tmpMap.put(curTran.getIndex(), curStatic); // tranFiringFreq.put(curTran.getIndex(), 0); // staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap); // printStaticSetMap(staticSetsMap); // System.out.println("call getAmple on initStateArray at 0: "); // boolean init = true; // AmpleSet initAmple = new AmpleSet(); // initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq); // HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl(); // lpnTranStack.push(initAmple.getAmpleSet()); // curIndexStack.push(0); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) initAmple.getAmpleSet(), ""); // main_while_loop: while (failure == false && stateStack.size() != 0) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); // long curTotalMem = Runtime.getRuntime().totalMemory(); // long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); // if (curTotalMem > peakTotalMem) // peakTotalMem = curTotalMem; // if (curUsedMem > peakUsedMem) // peakUsedMem = curUsedMem; // if (stateStack.size() > max_stack_depth) // max_stack_depth = stateStack.size(); // iterations++; // if (iterations % 100000 == 0) { // System.out.println("---> #iteration " + iterations // + "> # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStates // + ", stack_depth: " + stateStack.size() // + " used memory: " + (float) curUsedMem / 1000000 // + " free memory: " // + (float) Runtime.getRuntime().freeMemory() / 1000000); // State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); // int curIndex = curIndexStack.peek(); //// System.out.println("curIndex = " + curIndex); // //AmpleSet curAmple = new AmpleSet(); // //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet(); // LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); //// printStateArray(curStateArray); //// System.out.println("+++++++ curAmple trans ++++++++"); //// printTransLinkedList(curAmpleTrans); // // If all enabled transitions of the current LPN are considered, // // then consider the next LPN // // by increasing the curIndex. // // Otherwise, if all enabled transitions of all LPNs are considered, // // then pop the stacks. // if (curAmpleTrans.size() == 0) { // lpnTranStack.pop(); //// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // curIndexStack.pop(); //// System.out.println("+++++++ Pop index off curIndexStack ++++++++"); // curIndex++; //// System.out.println("curIndex = " + curIndex); // while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); // LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet(); // curAmpleTrans = tmpAmpleTrans.clone(); // //printTransitionSet(curEnabled, "curEnabled set"); // if (curAmpleTrans.size() > 0) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curAmpleTrans); // lpnTranStack.push(curAmpleTrans); // curIndexStack.push(curIndex); // printIntegerStack("curIndexStack after push 1", curIndexStack); // break; // curIndex++; // if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.remove(stateStackTop); // stateStackTop = stateStackTop.getFather(); // continue; // Transition firedTran = curAmpleTrans.removeLast(); // System.out.println(" // System.out.println("Fired transition: " + firedTran.getName()); // System.out.println(" // Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1; // tranFiringFreq.put(firedTran.getIndex(), freq); // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, allTransitions); // State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); // tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. // @SuppressWarnings("unchecked") // LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns]; // @SuppressWarnings("unchecked") // LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns]; // boolean updatedAmpleDueToCycleRule = false; // for (int i = 0; i < numLpns; i++) { // StateGraph sg_tmp = sgList[i]; // System.out.println("call getAmple on curStateArray at 2: i = " + i); // AmpleSet ampleList = new AmpleSet(); // if (init) { // ampleList = initAmple; // sg_tmp.setEnabledSetTbl(initEnabledSetTbl); // init = false; // else // ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq); // curAmpleArray[i] = ampleList.getAmpleSet(); // System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i); // ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq); // nextAmpleArray[i] = ampleList.getAmpleSet(); // if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) { // updatedAmpleDueToCycleRule = true; // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : nextAmpleArray) { //// printTransLinkedList(tranList); // Transition disabledTran = firedTran.disablingError( // curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); // if (disabledTran != null) { // System.err.println("Disabling Error: " // + disabledTran.getFullLabel() + " is disabled by " // + firedTran.getFullLabel()); // failure = true; // break main_while_loop; // if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) { // failure = true; // break main_while_loop; // PrjState nextPrjState = new PrjState(nextStateArray); // Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); // if (existingState == true && updatedAmpleDueToCycleRule) { // // cycle closing // System.out.println("%%%%%%% existingSate == true %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // if (existingState == false) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // totalStates++; // // end of main_while_loop // double totalStateCnt = prjStateSet.size(); // System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStateCnt // + ", max_stack_depth: " + max_stack_depth // + ", peak total memory: " + peakTotalMem / 1000000 + " MB" // + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); // // This currently works for a single LPN. // return sgList; // return null; private void writeStaticSetsMapToPORDebugFile( LhpnFile[] lpnList, HashMap<Transition,StaticSets> staticSetsMap) { try { PORdebugBufferedWriter.write(" PORdebugBufferedWriter.newLine(); for (Transition lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); writeLpnTranPairToPORDebugFile(statSets.getTran(), statSets.getDisableSet(), "disableSet"); for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) { writeLpnTranPairToPORDebugFile(statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct"); } } } catch (IOException e) { e.printStackTrace(); } } // private Transition[] assignStickyTransitions(LhpnFile lpn) { // // allProcessTrans is a hashmap from a transition to its process color (integer). // HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // // create an Abstraction object to call the divideProcesses method. // Abstraction abs = new Abstraction(lpn); // abs.decomposeLpnIntoProcesses(); // allProcessTrans.putAll( // (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); // HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); // for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { // Transition curTran = tranIter.next(); // Integer procId = allProcessTrans.get(curTran); // if (!processMap.containsKey(procId)) { // LpnProcess newProcess = new LpnProcess(procId); // newProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // newProcess.addPlaceToProcess(p); // processMap.put(procId, newProcess); // else { // LpnProcess curProcess = processMap.get(procId); // curProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // curProcess.addPlaceToProcess(p); // for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { // LpnProcess curProc = processMap.get(processMapIter.next()); // curProc.assignStickyTransitions(); // curProc.printProcWithStickyTrans(); // return lpn.getAllTransitions(); // private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran, // HashSet<Transition> curDisable, String setName) { // System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); // if (curDisable.isEmpty()) { // System.out.println("empty"); // else { // for (Transition lpnTranPair: curDisable) { // System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() // + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); // System.out.print("\n"); private void writeLpnTranPairToPORDebugFile(Transition curTran, HashSet<Transition> TransitionSet, String setName) { try { //PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: "); if (TransitionSet.isEmpty()) { PORdebugBufferedWriter.write("empty"); PORdebugBufferedWriter.newLine(); } else { for (Transition lpnTranPair: TransitionSet) PORdebugBufferedWriter.append("(" + lpnTranPair.getLpn().getLabel() + ", " + lpnTranPair.getName() + ")," + " "); PORdebugBufferedWriter.newLine(); } PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void printTransitionSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " is: "); if (transitionSet.isEmpty()) { System.out.println("empty"); } else { for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { Transition tranInDisable = curTranIter.next(); System.out.print(tranInDisable.getName() + " "); } System.out.print("\n"); } } // private void printTransitionSet(LinkedList<Transition> transitionSet, String setName) { // System.out.print(setName + " is: "); // if (transitionSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { // Transition tranInDisable = curTranIter.next(); // System.out.print(tranInDisable.getIndex() + " "); // System.out.print("\n"); /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN. * @param stateArray * @param stateStack * @param enable * @param disableByStealingToken * @param disable * @param init * @param sgList * @return */ public LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticSets> staticSetsMap, boolean init, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList, HashSet<PrjState> stateStack, PrjState stateStackTop) { State[] stateArray = null; if (nextStateArray == null) stateArray = curStateArray; else stateArray = nextStateArray; for (State s : stateArray) if (s == null) throw new NullPointerException(); LpnTranList ample = new LpnTranList(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) { State state = stateArray[lpnIndex]; if (init) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (sgList[lpnIndex].isEnabled(curLpn.getAllTransitions()[i], state)){ curEnabled.add(curLpn.getAllTransitions()[i]); } } } else { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (stateArray[lpnIndex].getTranVector()[i]) { curEnabled.add(curLpn.getAllTransitions()[i]); } } } } if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("******* Partial Order Reduction *******"); writeIntegerSetToPORDebugFile(curEnabled, "Enabled set"); writeStringWithEndOfLineToPORDebugFile("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } HashSet<Transition> ready = partialOrderReduction(stateArray, curEnabled, tranFiringFreq, staticSetsMap, sgList); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("******* End POR *******"); writeIntegerSetToPORDebugFile(ready, "Ample set"); writeStringWithEndOfLineToPORDebugFile("********************"); } if (tranFiringFreq != null) { LinkedList<Transition> readyList = new LinkedList<Transition>(); for (Transition inReady : ready) { readyList.add(inReady); } mergeSort(readyList, tranFiringFreq); for (Transition inReady : readyList) { ample.addFirst(inReady); } } else { for (Transition tran : ready) { ample.add(tran); } } return ample; } private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) { if (array.size() == 1) return array; int middle = array.size() / 2; LinkedList<Transition> left = new LinkedList<Transition>(); LinkedList<Transition> right = new LinkedList<Transition>(); for (int i=0; i<middle; i++) { left.add(i, array.get(i)); } for (int i=middle; i<array.size();i++) { right.add(i-middle, array.get(i)); } left = mergeSort(left, tranFiringFreq); right = mergeSort(right, tranFiringFreq); return merge(left, right, tranFiringFreq); } private LinkedList<Transition> merge(LinkedList<Transition> left, LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) { LinkedList<Transition> result = new LinkedList<Transition>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) { result.addLast(left.poll()); } else { result.addLast(right.poll()); } } else if (left.size()>0) { result.addLast(left.poll()); } else if (right.size()>0) { result.addLast(right.poll()); } } return result; } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. * @param nextState * @param stateStackTop * @param enable * @param disableByStealingToken * @param disable * @param init * @param cycleClosingMthdIndex * @param lpnIndex * @param isNextState * @return */ public LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticSets> staticSetsMap, boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { // AmpleSet nextAmple = new AmpleSet(); // if (nextState == null) { // throw new NullPointerException(); // if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) { // System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: "); // // Cycle closing check // LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet(); // nextAmpleTransOld = ampleSetTbl.get(nextState); // LpnTranList curAmpleTrans = ampleSetTbl.get(curState); // LpnTranList curReduced = new LpnTranList(); // LpnTranList curEnabled = curState.getEnabledTransitions(); // for (int i=0; i<curEnabled.size(); i++) { // if (!curAmpleTrans.contains(curEnabled.get(i))) { // curReduced.add(curEnabled.get(i)); // if (!nextAmpleTransOld.containsAll(curReduced)) { // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // printTransitionSet(curEnabled, "curEnabled:"); // printTransitionSet(curAmpleTrans, "curAmpleTrans:"); // printTransitionSet(curReduced, "curReduced:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:"); // printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:"); // nextAmple.setAmpleChanged(); // HashSet<Transition> curEnabledIndicies = new HashSet<Transition>(); // for (int i=0; i<curEnabled.size(); i++) { // curEnabledIndicies.add(curEnabled.get(i).getIndex()); // // transToAdd = curReduced - nextAmpleOld // LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld); // HashSet<Integer> transToAddIndices = new HashSet<Integer>(); // for (int i=0; i<overlyReducedTrans.size(); i++) { // transToAddIndices.add(overlyReducedTrans.get(i).getIndex()); // HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone(); // for (Integer tranToAdd : transToAddIndices) { // HashSet<Transition> dependent = new HashSet<Transition>(); // //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd]; // dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap); // // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]); // boolean dependentOnlyHasDummyTrans = true; // for (Integer curTranIndex : dependent) { // Transition curTran = this.lpn.getAllTransitions()[curTranIndex]; // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName()); // if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans) // nextAmpleNewIndices = (HashSet<Integer>) dependent.clone(); // if (nextAmpleNewIndices.size() == 1) // break; // LpnTranList nextAmpleNew = new LpnTranList(); // for (Integer nextAmpleNewIndex : nextAmpleNewIndices) { // nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex)); // LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld); // boolean allTransToAddFired = false; // if (cycleClosingMthdIndex == 2) { // // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. // if (transToAdd != null) { // LpnTranList transToAddCopy = transToAdd.copy(); // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // allTransToAddFired = allTransToAddFired(transToAddCopy, // allTransToAddFired, stateVisited, stateStackTop, lpnIndex); // // Update the old ample of the next state // if (!allTransToAddFired || cycleClosingMthdIndex == 1) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(transToAdd); // ampleSetTbl.get(nextState).addAll(transToAdd); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // if (cycleClosingMthdIndex == 4) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(overlyReducedTrans); // ampleSetTbl.get(nextState).addAll(overlyReducedTrans); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // // enabledSetTble stores the ample set at curState. // // The fully enabled set at each state is stored in the tranVector in each state. // return (AmpleSet) nextAmple; // for (State s : nextStateArray) // if (s == null) // throw new NullPointerException(); // cachedNecessarySets.clear(); // String cycleClosingMthd = Options.getCycleClosingMthd(); // AmpleSet nextAmple = new AmpleSet(); // HashSet<Transition> nextEnabled = new HashSet<Transition>(); //// boolean allEnabledAreSticky = false; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State nextState = nextStateArray[lpnIndex]; // if (init) { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // //allEnabledAreSticky = true; // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (sgList[lpnIndex].isEnabled(tran,nextState)){ // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // else { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (nextStateArray[lpnIndex].getTranVector()[i]) { // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // LhpnFile[] lpnList = new LhpnFile[sgList.length]; // for (int i=0; i<sgList.length; i++) // lpnList[i] = sgList[i].getLpn(); // HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>(); // Integer cycleClosingLpnIndex = -1; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State curState = curStateArray[lpnIndex]; // State nextState = nextStateArray[lpnIndex]; // if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true // && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty() // && stateOnStack(lpnIndex, nextState, stateStack) // && nextState.getIndex() != curState.getIndex()) { // cycleClosingLpnIndex = lpnIndex; // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~"); // printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: "); // LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState); // LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState); // LpnTranList reducedLocalTrans = new LpnTranList(); // LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions(); // System.out.println("The firedTran is a cycle closing transition."); // if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) { // // firedTran is a cycle closing transition. // for (int i=0; i<curLocalEnabledTrans.size(); i++) { // if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) { // reducedLocalTrans.add(curLocalEnabledTrans.get(i)); // if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) { // printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:"); // printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:"); // printTransitionSet(reducedLocalTrans, "reducedLocalTrans:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:"); // printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:"); // // nextAmple.setAmpleChanged(); // // ignoredTrans should not be empty here. // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // if (cycleClosingMthd.toLowerCase().equals("behavioral")) { // for (Transition seed : ignored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); //// if (nextAmpleNewIndices.size() == 1) //// break; // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else if (cycleClosingMthd.toLowerCase().equals("state_search")) { // // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState. // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // LpnTranList trulyIgnoredTrans = ignoredTrans.copy(); // trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]); // if (!trulyIgnoredTrans.isEmpty()) { // HashSet<Transition> trulyIgnored = new HashSet<Transition>(); // for (Transition tran : trulyIgnoredTrans) { // trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : trulyIgnored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else { // All ignored transitions were fired before. It is safe to close the current cycle. // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle) // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else if (cycleClosingMthd.toLowerCase().equals("strong")) { // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> allNewNextAmple = new HashSet<Transition>(); // for (Transition seed : ignored) { // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // allNewNextAmple.addAll(newNextAmple); // // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed. // // So each seed should have the same new ample set. // for (Transition seed : ignored) { // DependentSet dependentSet = new DependentSet(allNewNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // firedTran is not a cycle closing transition. Compute next ample. //// if (nextEnabled.size() == 1) //// return nextEnabled; // System.out.println("The firedTran is NOT a cycle closing transition."); // HashSet<Transition> ready = null; // for (Transition seed : nextEnabled) { // System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")"); // HashSet<Transition> dependent = new HashSet<Transition>(); // Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()]; // boolean enabledIsDummy = false; //// if (enabledTransition.isSticky()) { //// dependent = (HashSet<Transition>) nextEnabled.clone(); //// else { //// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList); // dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // if (isDummyTran(enabledTransition.getName())) // enabledIsDummy = true; // for (Transition inDependent : dependent) { // if(inDependent.getLpnIndex() == cycleClosingLpnIndex) { // // check cycle closing condition // break; // DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy); // dependentSetQueue.add(dependentSet); // ready = dependentSetQueue.poll().getDependent(); //// // Update the old ample of the next state //// boolean allTransToAddFired = false; //// if (cycleClosingMthdIndex == 2) { //// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. //// if (transToAdd != null) { //// LpnTranList transToAddCopy = transToAdd.copy(); //// HashSet<Integer> stateVisited = new HashSet<Integer>(); //// stateVisited.add(nextState.getIndex()); //// allTransToAddFired = allTransToAddFired(transToAddCopy, //// allTransToAddFired, stateVisited, stateStackTop, lpnIndex); //// // Update the old ample of the next state //// if (!allTransToAddFired || cycleClosingMthdIndex == 1) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(transToAdd); //// ampleSetTbl.get(nextState).addAll(transToAdd); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// if (cycleClosingMthdIndex == 4) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(ignoredTrans); //// ampleSetTbl.get(nextState).addAll(ignoredTrans); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// // enabledSetTble stores the ample set at curState. //// // The fully enabled set at each state is stored in the tranVector in each state. //// return (AmpleSet) nextAmple; return null; } private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans, HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) { State state = stateStackEntry.get(lpnIndex); System.out.println("state = " + state.getIndex()); State predecessor = stateStackEntry.getFather().get(lpnIndex); if (predecessor != null) System.out.println("predecessor = " + predecessor.getIndex()); if (predecessor == null || stateVisited.contains(predecessor.getIndex())) { return ignoredTrans; } else stateVisited.add(predecessor.getIndex()); LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor); for (Transition oldAmpleTran : predecessorOldAmple) { State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran); if (tmpState.getIndex() == state.getIndex()) { ignoredTrans.remove(oldAmpleTran); break; } } if (ignoredTrans.size()==0) { return ignoredTrans; } else { ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg); } return ignoredTrans; } // for (Transition oldAmpleTran : oldAmple) { // State successor = nextStateMap.get(nextState).get(oldAmpleTran); // if (stateVisited.contains(successor.getIndex())) { // break; // else // stateVisited.add(successor.getIndex()); // LpnTranList successorOldAmple = enabledSetTbl.get(successor); // // Either successor or sucessorOldAmple should not be null for a nonterminal state graph. // HashSet<Transition> transToAddFired = new HashSet<Transition>(); // for (Transition tran : transToAddCopy) { // if (successorOldAmple.contains(tran)) // transToAddFired.add(tran); // transToAddCopy.removeAll(transToAddFired); // if (transToAddCopy.size() == 0) { // allTransFired = true; // break; // else { // allTransFired = allTransToAddFired(successorOldAmple, nextState, successor, // transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex); // return allTransFired; /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) { boolean firingOrder = false; long peakUsedMem = 0; long peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length; HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>(); @SuppressWarnings("unchecked") IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize]; //HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize]; Stack<LpnState[]> stateStack = new Stack<LpnState[]>(); Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>(); //get initial enable transition set LpnTranList initEnabled = new LpnTranList(); LpnTranList initFireFirst = new LpnTranList(); LpnState[] initLpnStateArray = new LpnState[arraySize]; for (int i = 0; i < arraySize; i++) { lpnStateCache[i] = new IndexObjMap<LpnState>(); LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]); HashSet<Transition> enabledSet = new HashSet<Transition>(); if(!enabledTrans.isEmpty()) { for(Transition tran : enabledTrans) { enabledSet.add(tran); initEnabled.add(tran); } } LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet); lpnStateCache[i].add(curLpnState); initLpnStateArray[i] = curLpnState; } LpnTranList[] initEnabledSet = new LpnTranList[2]; initEnabledSet[0] = initFireFirst; initEnabledSet[1] = initEnabled; lpnTranStack.push(initEnabledSet); stateStack.push(initLpnStateArray); globalStateTbl.add(new PrjLpnState(initLpnStateArray)); main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; //if(iterations>2)break; if (iterations % 100000 == 0) System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", current_stack_depth: " + stateStack.size() + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); LpnTranList[] curEnabled = lpnTranStack.peek(); LpnState[] curLpnStateArray = stateStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if(curEnabled[0].size()==0 && curEnabled[1].size()==0){ lpnTranStack.pop(); stateStack.pop(); continue; } Transition firedTran = null; if(curEnabled[0].size() != 0) firedTran = curEnabled[0].removeFirst(); else firedTran = curEnabled[1].removeFirst(); traceCex.addLast(firedTran); State[] curStateArray = new State[arraySize]; for( int i = 0; i < arraySize; i++) curStateArray[i] = curLpnStateArray[i].getState(); StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled(); LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]); HashSet<Transition> nextEnabledSet = new HashSet<Transition>(); for(Transition tran : nextEnabledList) { nextEnabledSet.add(tran); } extendedNextEnabledArray[i] = nextEnabledSet; //non_disabling for(Transition curTran : curEnabledSet) { if(curTran == firedTran) continue; if(nextEnabledSet.contains(curTran) == false) { int[] nextMarking = nextStateArray[i].getMarking(); // Not sure if the code below is correct. int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getName()); boolean included = true; if (preset != null && preset.length > 0) { for (int pp : preset) { boolean temp = false; for (int mi = 0; mi < nextMarking.length; mi++) { if (nextMarking[mi] == pp) { temp = true; break; } } if (temp == false) { included = false; break; } } } if(preset==null || preset.length==0 || included==true) { extendedNextEnabledArray[i].add(curTran); } } } } boolean deadlock=true; for(int i = 0; i < arraySize; i++) { if(extendedNextEnabledArray[i].size() != 0){ deadlock = false; break; } } if(deadlock==true) { failure = true; break main_while_loop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. LpnState[] nextLpnStateArray = new LpnState[arraySize]; for(int i = 0; i < arraySize; i++) { HashSet<Transition> lpnEnabledSet = new HashSet<Transition>(); for(Transition tran : extendedNextEnabledArray[i]) { lpnEnabledSet.add(tran); } LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet); LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp)); nextLpnStateArray[i] = tmpCached; } boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray)); if(newState == false) { traceCex.removeLast(); continue; } stateStack.push(nextLpnStateArray); LpnTranList[] nextEnabledSet = new LpnTranList[2]; LpnTranList fireFirstTrans = new LpnTranList(); LpnTranList otherTrans = new LpnTranList(); for(int i = 0; i < arraySize; i++) { for(Transition tran : nextLpnStateArray[i].getEnabled()) { if(firingOrder == true) if(curLpnStateArray[i].getEnabled().contains(tran)) otherTrans.add(tran); else fireFirstTrans.add(tran); else fireFirstTrans.add(tran); } } nextEnabledSet[0] = fireFirstTrans; nextEnabledSet[1] = otherTrans; lpnTranStack.push(nextEnabledSet); }// END while (stateStack.empty() == false) // graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt, // prjStateSet.size())); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth); /* * by looking at stateStack, generate the trace showing the counter-example. */ if (failure == true) { System.out.println(" System.out.println("the deadlock trace:"); //update traceCex from stateStack // LpnState[] cur = null; // LpnState[] next = null; for(Transition tran : traceCex) System.out.println(tran.getFullLabel()); } System.out.println("Modules' local states: "); for (int i = 0; i < arraySize; i++) { System.out.println("module " + lpnList[i].getLpn().getLabel() + ": " + lpnList[i].reachSize()); } return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * When a state is considered during DFS, only one enabled transition is * selected to fire in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_1"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 500; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean compressed = false; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int arraySize = lpnList.length; int newStateCnt = 0; Stack<State[]> stateStack = new Stack<State[]>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); mddNode reachAll = null; mddNode reach = mddMgr.newNode(); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true); mddMgr.add(reach, localIdxArray, compressed); stateStack.push(initStateArray); LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]); lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); int numMddCompression = 0; main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack depth: " + stateStack.size() + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); numMddCompression++; if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); if(memUpBound < 1500) memUpBound *= numMddCompression; } } State[] curStateArray = stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); curIndexStack.pop(); curIndex++; while (curIndex < arraySize) { LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex])); if (enabledCached.size() > 0) { curEnabled = enabledCached.clone(); lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } else curIndex++; } } if (curIndex == arraySize) { stateStack.pop(); continue; } Transition firedTran = curEnabled.removeLast(); State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. * if not, add it into reachable set, and push it onto stack. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; if (existingState == false) { mddMgr.add(reach, localIdxArray, compressed); newStateCnt++; stateStack.push(nextStateArray); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; } } double totalStateCnt = mddMgr.numberOfStates(reach); System.out.println("---> run statistics: \n" + "# LPN transition firings: " + tranFiringCnt + "\n" + "# of prjStates found: " + totalStateCnt + "\n" + "max_stack_depth: " + max_stack_depth + "\n" + "peak MDD nodes: " + peakMddNodeCnt + "\n" + "peak used memory: " + peakUsedMem / 1000000 + " MB\n" + "peak total memory: " + peakTotalMem / 1000000 + " MB\n"); return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * It is similar to findsg_dfs_mdd_1 except that when a state is considered * during DFS, all enabled transition are fired, and all its successor * states are found in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_2"); int tranFiringCnt = 0; int totalStates = 0; int arraySize = lpnList.length; long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean failure = false; MDT state2Explore = new MDT(arraySize); state2Explore.push(initStateArray); totalStates++; long peakState2Explore = 0; Stack<Integer> searchDepth = new Stack<Integer>(); searchDepth.push(1); boolean compressed = false; mddNode reachAll = null; mddNode reach = mddMgr.newNode(); main_while_loop: while (failure == false && state2Explore.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; iterations++; if (iterations % 100000 == 0) { int mddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt; int state2ExploreSize = state2Explore.size(); peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", # states to explore: " + state2ExploreSize + ", # MDT nodes: " + state2Explore.nodeCnt() + ", total MDD nodes: " + mddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } } State[] curStateArray = state2Explore.pop(); State[] nextStateArray = null; int states2ExploreCurLevel = searchDepth.pop(); if(states2ExploreCurLevel > 1) searchDepth.push(states2ExploreCurLevel-1); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false); mddMgr.add(reach, localIdxArray, compressed); int nextStates2Explore = 0; for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; State curState = curStateArray[index]; LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState); LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone(); while (curEnabled.size() > 0) { Transition firedTran = curEnabled.removeLast(); // TODO: (check) Not sure if curLpn.fire is correct. nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; if (curStateArray[i] == nextStateArray[i]) continue; LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.err.println("Verification failed: deadlock."); failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; else if(state2Explore.contains(nextStateArray)==true) existingState = true; if (existingState == false) { totalStates++; //mddMgr.add(reach, localIdxArray, compressed); state2Explore.push(nextStateArray); nextStates2Explore++; } } } if(nextStates2Explore > 0) searchDepth.push(nextStates2Explore); } System.out.println(" + "---> run statistics: \n" + " # Depth of search (Length of Cex): " + searchDepth.size() + "\n" + " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n" + " # of prjStates found: " + (double)totalStates / 1000000 + " M\n" + " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n" + " peak MDD nodes: " + peakMddNodeCnt + "\n" + " peak used memory: " + peakUsedMem / 1000000 + " MB\n" + " peak total memory: " + peakTotalMem /1000000 + " MB\n" + "_____________________________________"); return null; } public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. int arraySize = sgList.length; for (int i = 0; i < arraySize; i++) sgList[i].addState(initStateArray[i]); mddNode reachSet = null; mddNode reach = mddMgr.newNode(); MDT frontier = new MDT(arraySize); MDT image = new MDT(arraySize); frontier.push(initStateArray); State[] curStateArray = null; int tranFiringCnt = 0; int totalStates = 0; int imageSize = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachSet == null) reachSet = reach; else { mddNode newReachSet = mddMgr.union(reachSet, reach); if (newReachSet != reachSet) { mddMgr.remove(reachSet); reachSet = newReachSet; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } while(frontier.empty() == false) { boolean deadlock = true; // Stack<State[]> curStateArrayList = frontier.pop(); // while(curStateArrayList.empty() == false) { // curStateArray = curStateArrayList.pop(); { curStateArray = frontier.pop(); int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false); mddMgr.add(reach, localIdxArray, false); totalStates++; for (int i = 0; i < arraySize; i++) { LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]); if (curEnabled.size() > 0) deadlock = false; for (Transition firedTran : curEnabled) { // TODO: (check) Not sure if sgList[i].fire is correct. State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran); tranFiringCnt++; /* * Check if any transitions can be disabled by fireTran. */ LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled); if (disabledTran != null) { System.err.println("*** Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false); if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) { if(image.contains(nextStateArray)==false) { image.push(nextStateArray); imageSize++; } } } } } /* * If curStateArray deadlocks (no enabled transitions), terminate. */ if (deadlock == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } } if(image.empty()==true) break; System.out.println("---> size of image: " + imageSize); frontier = image; image = new MDT(arraySize); imageSize = 0; } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n" + "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MDD nodes: " + peakMddNodeCnt); return null; } /** * BFS findsg using iterative approach. THe states found are stored in MDD. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; int arraySize = lpnList.length; for (int i = 0; i < arraySize; i++) lpnList[i].addState(initStateArray[i]); // mddNode reachSet = mddMgr.newNode(); // mddMgr.add(reachSet, curLocalStateArray); mddNode reachSet = null; mddNode exploredSet = null; LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]); for (int i = 0; i < arraySize; i++) nextSetArray[i] = new LinkedList<State>(); mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null); mddNode curMdd = initMdd; reachSet = curMdd; mddNode nextMdd = null; int[] curStateArray = null; int tranFiringCnt = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; curStateArray = mddMgr.next(curMdd, curStateArray); if (curStateArray == null) { // Break the loop if no new next states are found. // System.out.println("nextSet size " + nextSet.size()); if (nextMdd == null) break bfsWhileLoop; if (exploredSet == null) exploredSet = curMdd; else { mddNode newExplored = mddMgr.union(exploredSet, curMdd); if (newExplored != exploredSet) mddMgr.remove(exploredSet); exploredSet = newExplored; } mddMgr.remove(curMdd); curMdd = nextMdd; nextMdd = null; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of union calls: " + mddNode.numCalls + ", # of union cache nodes: " + mddNode.cacheNodes + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet) + ", CurSet.Size = " + mddMgr.numberOfStates(curMdd)); continue; } if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true) continue; // If curStateArray deadlocks (no enabled transitions), terminate. if (Analysis.deadLock(lpnList, curStateArray) == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } // Do firings of non-local LPN transitions. for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]); if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true) continue; for (Transition firedTran : curLocalEnabled) { if (firedTran.isLocal() == true) continue; // TODO: (check) Not sure if curLpn.fire is correct. State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; @SuppressWarnings("unused") ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1); for (int i = 0; i < arraySize; i++) { if (curStateArray[i] == nextStateArray[i].getIndex()) continue; StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex()); Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + ": is disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { verifyError = true; break bfsWhileLoop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the // next // enabled transition. int[] nextIdxArray = Analysis.getIdxArray(nextStateArray); if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true) continue; mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet); mddNode newReachSet = mddMgr.union(reachSet, newNextMdd); if (newReachSet != reachSet) mddMgr.remove(reachSet); reachSet = newReachSet; if (nextMdd == null) nextMdd = newNextMdd; else { mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd); if (tmpNextMdd != nextMdd) mddMgr.remove(nextMdd); nextMdd = tmpNextMdd; mddMgr.remove(newNextMdd); } } } } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + "\n" + "---> # of prjStates found: " + (mddMgr.numberOfStates(reachSet)) + "\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt()); return null; } /** * partial order reduction (Hao's POR with behavioral analysis) * * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> Calling search_dfs with partial order reduction"); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; boolean useMdd = true; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); //System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel()); // TODO: (??) Not sure if the state graph sg below is correct. StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return null; } // /** // * Check if this project deadlocks in the current state 'stateArray'. // * @param sgList // * @param stateArray // * @param staticSetsMap // * @param enableSet // * @param disableByStealingToken // * @param disableSet // * @param init // * @return // */ // // Called by search search_dfsPOR // public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap, // boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) { // boolean deadlock = true; // System.out.println("@ deadlock:"); //// for (int i = 0; i < stateArray.length; i++) { //// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); //// if (tmp.size() > 0) { //// deadlock = false; //// break; // LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); // if (tmp.size() > 0) { // deadlock = false; // System.out.println("@ end of deadlock"); // return deadlock; public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) { boolean deadlock = true; for (int i = 0; i < stateArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) { boolean deadlock = true; for (int i = 0; i < stateIdxArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } // /* // * Scan enabledArray, identify all sticky transitions other the firedTran, and return them. // * // * Arguments remain constant. // */ // public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) { // int arraySize = enabledArray.length; // LpnTranList[] stickyTranArray = new LpnTranList[arraySize]; // for (int i = 0; i < arraySize; i++) { // stickyTranArray[i] = new LpnTranList(); // for (Transition tran : enabledArray[i]) { // if (tran != firedTran) // stickyTranArray[i].add(tran); // if(stickyTranArray[i].size()==0) // stickyTranArray[i] = null; // return stickyTranArray; /** * Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to * nextStickyTransArray. * * Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions * from curStickyTransArray. * * Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState. */ public static LpnTranList[] checkStickyTrans( LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray, LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) { int arraySize = curStickyTransArray.length; LpnTranList[] stickyTransArray = new LpnTranList[arraySize]; boolean[] hasStickyTrans = new boolean[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> tmp = new HashSet<Transition>(); if(nextStickyTransArray[i] != null) for(Transition tran : nextStickyTransArray[i]) tmp.add(tran); stickyTransArray[i] = new LpnTranList(); hasStickyTrans[i] = false; for (Transition tran : curStickyTransArray[i]) { if (tran.isPersistent() == true && tmp.contains(tran)==false) { int[] nextMarking = nextState.getMarking(); int[] preset = LPN.getPresetIndex(tran.getName());//tran.getPreSet(); boolean included = false; if (preset != null && preset.length > 0) { for (int pp : preset) { for (int mi = 0; i < nextMarking.length; i++) { if (nextMarking[mi] == pp) { included = true; break; } } if (included == false) break; } } if(preset==null || preset.length==0 || included==true) { stickyTransArray[i].add(tran); hasStickyTrans[i] = true; } } } if(stickyTransArray[i].size()==0) stickyTransArray[i] = null; } return stickyTransArray; } /* * Return an array of indices for the given stateArray. */ private static int[] getIdxArray(State[] stateArray) { int[] idxArray = new int[stateArray.length]; for(int i = 0; i < stateArray.length; i++) { idxArray[i] = stateArray[i].getIndex(); } return idxArray; } private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) { int arraySize = sgList.length; int[] localIdxArray = new int[arraySize]; for(int i = 0; i < arraySize; i++) { if(reverse == false) localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex(); else localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex(); //System.out.print(localIdxArray[i] + " "); } //System.out.println(); return localIdxArray; } private void printEnabledSetTbl(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { System.out.println("******* enabledSetTbl for " + sgList[i].getLpn().getLabel() + " **********"); for (State s : sgList[i].getEnabledSetTbl().keySet()) { System.out.print("S" + s.getIndex() + " -> "); printTransitionSet(sgList[i].getEnabledSetTbl().get(s), ""); } } } private HashSet<Transition> partialOrderReduction(State[] curStateArray, HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, HashMap<Transition, StaticSets> staticMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; if (Options.getUseDependentQueue()) { DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()){ writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); } HashSet<Transition> dependent = new HashSet<Transition>(); boolean enabledIsDummy = false; boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) if(isDummyTran(enabledTran.getName())) enabledIsDummy = true; DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); dependentSetQueue.add(dependentSet); } //cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); //return ready; } else { for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()){ writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); } HashSet<Transition> dependent = new HashSet<Transition>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } if (ready.isEmpty() || dependent.size() < ready.size()) ready = dependent; if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } } cachedNecessarySets.clear(); return ready; } // private HashSet<Transition> partialOrderReduction(State[] curStateArray, // HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap, // HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) { // if (curEnabled.size() == 1) // return curEnabled; // HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; // if (Options.getUseDependentQueue()) { // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean enabledIsDummy = false; // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) // if(isDummyTran(enabledTran.getName())) // enabledIsDummy = true; // DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); // dependentSetQueue.add(dependentSet); // //cachedNecessarySets.clear(); // ready = dependentSetQueue.poll().getDependent(); // //return ready; // else { // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // if (ready.isEmpty() || dependent.size() < ready.size()) // ready = dependent;//(HashSet<Transition>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // cachedNecessarySets.clear(); // return ready; private boolean isDummyTran(String tranName) { if (tranName.contains("_dummy")) return true; else return false; } private HashSet<Transition> computeDependent(State[] curStateArray, Transition seedTran, HashSet<Transition> dependent, HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap, boolean isCycleClosingAmpleComputation) { // disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran. HashSet<Transition> disableSet = staticMap.get(seedTran).getDisableSet(); HashSet<Transition> otherTransDisableEnabledTran = staticMap.get(seedTran).getOtherTransDisableCurTranSet(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ beginning of computeDependent, consider transition " + getNamesOfLPNandTrans(seedTran)); writeIntegerSetToPORDebugFile(disableSet, "Disable set for " + getNamesOfLPNandTrans(seedTran)); } dependent.add(seedTran); // for (Transition lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ computeDependent at 0, dependent set for " + getNamesOfLPNandTrans(seedTran)); } // dependent is equal to enabled. Terminate. if (dependent.size() == curEnabled.size()) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Check 0: Size of dependent is equal to enabled. Return dependent."); } return dependent; } for (Transition tranInDisableSet : disableSet) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Consider transition in the disable set of " + getNamesOfLPNandTrans(seedTran) + ": " + getNamesOfLPNandTrans(tranInDisableSet)); } if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet) && (!tranInDisableSet.isPersistent() || otherTransDisableEnabledTran.contains(tranInDisableSet))) { dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,staticMap, isCycleClosingAmpleComputation)); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ computeDependent at 1 for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (!curEnabled.contains(tranInDisableSet)) { if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back || (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) { dependent.addAll(curEnabled); break; } HashSet<Transition> necessary = null; if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ computeDependent: Found transition " + getNamesOfLPNandTrans(tranInDisableSet) + "in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("==== Compute necessary using DFS ===="); } if (visitedTrans == null) visitedTrans = new HashSet<Transition>(); else visitedTrans.clear(); necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap);//, tranInDisableSet.getFullLabel()); } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(necessary, "@ computeDependent, necessary set for transition " + getNamesOfLPNandTrans(tranInDisableSet)); } for (Transition tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"Check if the newly found necessary transition is in the dependent set of " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("It does not contain this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, isCycleClosingAmpleComputation)); } else { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("It already contains this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + "."); } } } } else { if (Options.getDebugMode()) { if (necessary == null) { writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is null."); } else { writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is empty."); } } dependent.addAll(curEnabled); } if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"@ computeDependent at 2, dependent set for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (dependent.contains(tranInDisableSet)) { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"@ computeDependent at 3 for transition " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("Transition " + getNamesOfLPNandTrans(tranInDisableSet) + " is already in the dependent set of " + getNamesOfLPNandTrans(seedTran) + "."); } } } return dependent; } private String getNamesOfLPNandTrans(Transition tran) { return tran.getLpn().getLabel() + "(" + tran.getName() + ")"; } private HashSet<Transition> computeNecessary(State[] curStateArray, Transition tran, HashSet<Transition> dependent, HashSet<Transition> curEnabledIndices, HashMap<Transition, StaticSets> staticMap) { // LhpnFile[] lpnList, Transition seedTran) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + getNamesOfLPNandTrans(tran)); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ computeNecessary: Found transition " + getNamesOfLPNandTrans(tran) + "'s necessary set in the cached necessary sets. Return the cached necessary set."); } return cachedNecessarySets.get(tran); } // Search for transition(s) that can help to bring the marking(s). HashSet<Transition> nMarking = null; //Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()); //int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName()); for (int i=0; i < tran.getPreset().length; i++) { int placeIndex = tran.getLpn().getPresetIndex(tran.getName())[i]; if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" } HashSet<Transition> nMarkingTemp = new HashSet<Transition>(); String placeName = tran.getLpn().getPlaceList()[placeIndex]; Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Consider preset place of " + getNamesOfLPNandTrans(tran) + ": " + placeName); } for (int j=0; j < presetTrans.length; j++) { Transition presetTran = presetTrans[j]; if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Preset of place " + placeName + " has transition(s): "); for (int k=0; k<presetTrans.length; k++) { writeStringToPORDebugFile(getNamesOfLPNandTrans(presetTrans[k]) + ", "); } writeStringWithEndOfLineToPORDebugFile(""); writeStringWithEndOfLineToPORDebugFile("@ nMarking: Consider transition of " + getNamesOfLPNandTrans(presetTran)); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: curEnabled contains transition " + getNamesOfLPNandTrans(presetTran) + "). Add to nMarkingTmp."); } nMarkingTemp.add(presetTran); } else { if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Transition " + getNamesOfLPNandTrans(presetTran) + " was visted before"); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@nMarking: Found transition " + getNamesOfLPNandTrans(presetTran) + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } // if (curEnabledIndices.contains(presetTran)) { // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile("@ nMarking: curEnabled contains transition " // + getNamesOfLPNandTrans(presetTran) + "). Add to nMarkingTmp."); // nMarkingTemp.add(presetTran);; continue; } else visitedTrans.add(presetTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~ transVisited ~~~~~~~~~"); for (Transition visitedTran :visitedTrans) { writeStringWithEndOfLineToPORDebugFile(getNamesOfLPNandTrans(visitedTran)); } writeStringWithEndOfLineToPORDebugFile("@ nMarking, before call computeNecessary: consider transition: " + getNamesOfLPNandTrans(presetTran)); } if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: transition " + getNamesOfLPNandTrans(presetTran) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabledIndices, staticMap); if (tmp != null) { nMarkingTemp.addAll(tmp); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(presetTran) + " is not null."); writeIntegerSetToPORDebugFile(nMarkingTemp, getNamesOfLPNandTrans(presetTran) + "'s nMarkingTemp"); } } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: necessary set for transition " + getNamesOfLPNandTrans(presetTran) + " is null."); } } } if (!nMarkingTemp.isEmpty()) //if (nMarking == null || nMarkingTemp.size() < nMarking.size()) if (nMarking == null || setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size()) nMarking = nMarkingTemp; } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Place " + tran.getLpn().getLabel() + "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked."); } } if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Return nMarking as necessary set."); writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } // Search for transition(s) that can help to enable the current transition. HashSet<Transition> nEnable = null; int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVector(); //HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); ArrayList<HashSet<Transition>> canEnable = staticMap.get(tran).getOtherTransSetCurTranEnablingTrue(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" writeIntegerSetToPORDebugFile(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); } if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && !canEnable.isEmpty()) { for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) { ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index); HashSet<Transition> nEnableForOneConjunct = null; if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); writeStringWithEndOfLineToPORDebugFile("@ nEnable: Consider conjunct for transition " + getNamesOfLPNandTrans(tran) + ": " + conjunctExprTree.toString()); } if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) { HashSet<Transition> canEnableOneConjunctSet = staticMap.get(tran).getOtherTransSetCurTranEnablingTrue().get(index); nEnableForOneConjunct = new HashSet<Transition>(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to FALSE."); writeIntegerSetToPORDebugFile(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are"); } for (Transition tranCanEnable : canEnableOneConjunctSet) { if (curEnabledIndices.contains(tranCanEnable)) { nEnableForOneConjunct.add(tranCanEnable); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: curEnabled contains transition " + getNamesOfLPNandTrans(tranCanEnable) + ". Add to nEnableOfOneConjunct."); } } else { if (visitedTrans.contains(tranCanEnable)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " was visted before."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ nEnable: Found transition " + getNamesOfLPNandTrans(tranCanEnable) + "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct."); } nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else visitedTrans.add(tranCanEnable); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabledIndices, staticMap); if (tmp != null) { nEnableForOneConjunct.addAll(tmp); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(tranCanEnable) + ": "); writeIntegerSetToPORDebugFile(tmp, ""); writeIntegerSetToPORDebugFile(nEnableForOneConjunct, getNamesOfLPNandTrans(tranCanEnable) + "'s nEnableOfOneConjunct"); } } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: necessary set for transition " + getNamesOfLPNandTrans(tranCanEnable) + " is null."); } } } if (!nEnableForOneConjunct.isEmpty()) { if (nEnable == null || setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) { //&& !nEnableForOneConjunct.isEmpty())) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" is replaced by nEnableForOneConjunct."); writeIntegerSetToPORDebugFile(nEnable, "nEnable"); writeIntegerSetToPORDebugFile(nEnableForOneConjunct, "nEnableForOneConjunct"); } nEnable = nEnableForOneConjunct; } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" remains unchanged."); writeIntegerSetToPORDebugFile(nEnable, "nEnable"); } } } } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it."); } } } } else { if (Options.getDebugMode()) { if (tran.getEnablingTree() == null) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + " has no enabling condition."); } else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is true."); } else if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is false, but no other transitions that can help to enable it were found ."); } writeIntegerSetToPORDebugFile(nMarking, "=== nMarking for transition " + getNamesOfLPNandTrans(tran)); writeIntegerSetToPORDebugFile(nEnable, "=== nEnable for transition " + getNamesOfLPNandTrans(tran)); } } if (nMarking != null && nEnable == null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } else if (nMarking == null && nEnable == null) { return null; } else { if (!nMarking.isEmpty() && !nEnable.isEmpty()) { if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } else { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } } } // private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray, // Transition tran, HashSet<Transition> curEnabled, // HashMap<Transition, StaticSets> staticMap, // LhpnFile[] lpnList, Transition seedTran) { // if (Options.getDebugMode()) { //// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // // Use breadth-first search to find the shorted path from the seed transition to an enabled transition. // LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>(); // HashSet<Transition> allExploredTrans = new HashSet<Transition>(); // exploredTransQueue.add(tran); // //boolean foundEnabledTran = false; // HashSet<Transition> canEnable = new HashSet<Transition>(); // while(!exploredTransQueue.isEmpty()){ // Transition curTran = exploredTransQueue.poll(); // allExploredTrans.add(curTran); // if (cachedNecessarySets.containsKey(curTran)) { // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" // + "'s necessary set in the cached necessary sets. Terminate BFS."); // return cachedNecessarySets.get(curTran); // canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // // Decide if canSetEnablingTrue set can help to enable curTran. // Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); // int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector(); // if (curTransition.getEnablingTree() != null // && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) { // canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue()); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // for (Transition neighborTran : canEnable) { // if (curEnabled.contains(neighborTran)) { // if (!neighborTran.equals(seedTran)) { // HashSet<Transition> necessarySet = new HashSet<Transition>(); // necessarySet.add(neighborTran); // // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed? // cachedNecessarySets.put(tran, necessarySet); // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // return necessarySet; // else if (neighborTran.equals(seedTran) && canEnable.size()==1) { // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // return null; //// if (exploredTransQueue.isEmpty()) { //// System.out.println("exploredTransQueue is empty. Return null necessary set."); //// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set."); //// return null; // if (!allExploredTrans.contains(neighborTran)) { // allExploredTrans.add(neighborTran); // exploredTransQueue.add(neighborTran); // canEnable.clear(); // return null; private void writeCachedNecessarySetsToPORDebugFile() { writeStringWithEndOfLineToPORDebugFile("================ cached necessary sets ================="); for (Transition key : cachedNecessarySets.keySet()) { writeStringToPORDebugFile(key.getLpn().getLabel() + "(" + key.getName() + ") => "); for (Transition necessary : cachedNecessarySets.get(key)) { writeStringToPORDebugFile(necessary.getLpn().getLabel() + "(" + necessary.getName() + ") "); } writeStringWithEndOfLineToPORDebugFile(""); } } private HashSet<Transition> setSubstraction( HashSet<Transition> left, HashSet<Transition> right) { HashSet<Transition> sub = new HashSet<Transition>(); for (Transition lpnTranPair : left) { if (!right.contains(lpnTranPair)) sub.add(lpnTranPair); } return sub; } public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) { isStateOnStack = true; break; } } return isStateOnStack; } private void writeIntegerSetToPORDebugFile(HashSet<Transition> Trans, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (Trans == null) { writeStringWithEndOfLineToPORDebugFile("null"); } else if (Trans.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("empty"); } else { for (Transition lpnTranPair : Trans) { writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getName() + "),"); } writeStringWithEndOfLineToPORDebugFile(""); } } // private void writeIntegerSetToPORDebugFile(HashSet<Transition> trans, String setName) { // if (!setName.isEmpty()) // writeStringToPORDebugFile(setName + ": "); // if (trans == null) { // writeStringWithEndOfLineToPORDebugFile("null"); // else if (trans.isEmpty()) { // writeStringWithEndOfLineToPORDebugFile("empty"); // else { // for (Transition lpnTranPair : trans) { // writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" // + lpnTranPair.getName() + "),"); // writeStringWithEndOfLineToPORDebugFile(""); private void writeIntegerSetToPORDebugFile(ArrayList<HashSet<Transition>> transSet, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (transSet == null) { writeStringWithEndOfLineToPORDebugFile("null"); } else if (transSet.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("empty"); } else { for (HashSet<Transition> lpnTranPairSet : transSet) { for (Transition lpnTranPair : lpnTranPairSet) writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getName() + "),"); } writeStringWithEndOfLineToPORDebugFile(""); } } }
package org.minimalj.rest; import java.io.IOException; import java.util.logging.Logger; import org.minimalj.application.Application; import org.minimalj.application.Configuration; import org.minimalj.model.test.ModelTest; import org.minimalj.util.StringUtils; import fi.iki.elonen.NanoHTTPD; public class RestServer { private static final Logger LOG = Logger.getLogger(RestServer.class.getName()); private static final boolean SECURE = true; private static final int TIME_OUT = 5 * 60 * 1000; public static void start(boolean secure) { int port = getPort(secure); if (port > 0) { LOG.info("Start " + Application.getInstance().getClass().getSimpleName() + " rest server on port " + port + (secure ? " (Secure)" : "")); NanoHTTPD nanoHTTPD = new RestHTTPD(port, secure); try { nanoHTTPD.start(TIME_OUT, false); // false -> this will not start a 'java' daemon, but a normal thread which keeps JVM alive LOG.info("Swagger available on http" + (secure ? "s" : "") + "://localhost:" + port + "/swagger-ui/"); } catch (IOException x) { throw new RuntimeException(x); } } } private static int getPort(boolean secure) { String portString = Configuration.get("MjRestPort" + (secure ? "Ssl" : ""), secure ? "-1" : "8090"); return !StringUtils.isEmpty(portString) ? Integer.valueOf(portString) : -1 ; } public static void start() { if (Application.getInstance().getEntityClasses().length == 0) { LOG.severe("Server not started! You must have at least declare one entity class in your application. Please override 'getEntityClasses'."); return; } ModelTest.exitIfProblems(); start(!SECURE); start(SECURE); } public static void start(Application application) { Application.setInstance(application); start(); } public static void main(String... args) { Application.initApplication(args); start(); } }
package org.jgrapes.portal; import freemarker.template.Configuration; import freemarker.template.SimpleScalar; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.nio.CharBuffer; import java.text.Collator; import java.text.ParseException; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Optional; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.Set; import java.util.function.Function; import java.util.stream.StreamSupport; import javax.json.Json; import javax.json.JsonReader; import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; import org.jdrupes.httpcodec.protocols.http.HttpField; import org.jdrupes.httpcodec.protocols.http.HttpRequest; import org.jdrupes.httpcodec.protocols.http.HttpResponse; import org.jdrupes.httpcodec.types.Converters; import org.jdrupes.httpcodec.types.Directive; import org.jdrupes.httpcodec.types.MediaType; import org.jdrupes.json.JsonDecodeException; import org.jgrapes.core.Channel; import org.jgrapes.core.CompletionLock; import org.jgrapes.core.Component; import org.jgrapes.core.annotation.Handler; import org.jgrapes.http.LanguageSelector.Selection; import org.jgrapes.http.Session; import org.jgrapes.http.annotation.RequestHandler; import org.jgrapes.http.events.GetRequest; import org.jgrapes.http.events.Response; import org.jgrapes.http.events.WebSocketAccepted; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.events.IOError; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.ByteBufferOutputStream; import org.jgrapes.io.util.CharBufferWriter; import org.jgrapes.io.util.InputStreamPipeline; import org.jgrapes.io.util.LinkedIOSubchannel; import org.jgrapes.io.util.ManagedCharBuffer; import org.jgrapes.portal.events.JsonInput; import org.jgrapes.portal.events.JsonOutput; import org.jgrapes.portal.events.PortalReady; import org.jgrapes.portal.events.PortletResourceRequest; import org.jgrapes.portal.events.PortletResourceResponse; import org.jgrapes.portal.events.SetLocale; import org.jgrapes.portal.events.SetTheme; import org.jgrapes.portal.themes.base.Provider; import org.jgrapes.util.events.KeyValueStoreData; import org.jgrapes.util.events.KeyValueStoreQuery; import org.jgrapes.util.events.KeyValueStoreUpdate; public class PortalView extends Component { private Portal portal; private ServiceLoader<ThemeProvider> themeLoader; private static Configuration fmConfig = null; private Function<Locale,ResourceBundle> resourceSupplier; private Set<Locale> supportedLocales; private ThemeProvider baseTheme; private Map<String,Object> portalBaseModel = new HashMap<>(); private RenderSupport renderSupport = new RenderSupportImpl(); /** * @param componentChannel */ public PortalView(Portal portal, Channel componentChannel) { super(componentChannel); this.portal = portal; if (fmConfig == null) { fmConfig = new Configuration(Configuration.VERSION_2_3_26); fmConfig.setClassLoaderForTemplateLoading( getClass().getClassLoader(), "org/jgrapes/portal"); fmConfig.setDefaultEncoding("utf-8"); fmConfig.setTemplateExceptionHandler( TemplateExceptionHandler.RETHROW_HANDLER); fmConfig.setLogTemplateExceptions(false); } baseTheme = new Provider(); supportedLocales = new HashSet<>(); for (Locale locale: Locale.getAvailableLocales()) { if (locale.getLanguage().equals("")) { continue; } if (resourceSupplier != null) { ResourceBundle rb = resourceSupplier.apply(locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } ResourceBundle rb = ResourceBundle.getBundle(getClass() .getPackage().getName() + ".l10n", locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } RequestHandler.Evaluator.add(this, "onGet", portal.prefix() + "**"); RequestHandler.Evaluator.add(this, "onGetRedirect", portal.prefix().getPath().substring( 0, portal.prefix().getPath().length() - 1)); // Create portal model portalBaseModel.put("resourceUrl", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } return portal.prefix().resolve( ((SimpleScalar)args.get(0)).getAsString()).getRawPath(); } }); portalBaseModel = Collections.unmodifiableMap(portalBaseModel); // Handlers attached to the portal side channel Handler.Evaluator.add(this, "onPortalReady", portal.channel()); Handler.Evaluator.add(this, "onKeyValueStoreData", portal.channel()); Handler.Evaluator.add( this, "onPortletResourceResponse", portal.channel()); Handler.Evaluator.add(this, "onJsonOutput", portal.channel()); Handler.Evaluator.add(this, "onSetLocale", portal.channel()); Handler.Evaluator.add(this, "onSetTheme", portal.channel()); } /** * The service loader must be created lazily, else the OSGi * service mediator doesn't work properly. * * @return */ private ServiceLoader<ThemeProvider> themeLoader() { if (themeLoader != null) { return themeLoader; } return themeLoader = ServiceLoader.load(ThemeProvider.class); } void setResourceSupplier( Function<Locale,ResourceBundle> resourceSupplier) { this.resourceSupplier = resourceSupplier; } RenderSupport renderSupport() { return renderSupport; } private LinkedIOSubchannel portalChannel(IOSubchannel channel) { @SuppressWarnings("unchecked") Optional<LinkedIOSubchannel> portalChannel = (Optional<LinkedIOSubchannel>)LinkedIOSubchannel .downstreamChannel(portal, channel); return portalChannel.orElseGet( () -> new LinkedIOSubchannel(portal, channel)); } @RequestHandler(dynamic=true) public void onGetRedirect(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException, ParseException { HttpResponse response = event.httpRequest().response().get(); response.setStatus(HttpStatus.MOVED_PERMANENTLY) .setContentType("text", "plain", "utf-8") .setField(HttpField.LOCATION, portal.prefix()); fire(new Response(response), channel); try { fire(Output.wrap(portal.prefix().toString() .getBytes("utf-8"), true), channel); } catch (UnsupportedEncodingException e) { // Supported by definition } event.stop(); } @RequestHandler(dynamic=true) public void onGet(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException { URI requestUri = event.requestUri(); // Append trailing slash, if missing if ((requestUri.getRawPath() + "/").equals( portal.prefix().getRawPath())) { requestUri = portal.prefix(); } // Request for portal? if (!requestUri.getRawPath().startsWith(portal.prefix().getRawPath())) { return; } // Normalize and evaluate requestUri = portal.prefix().relativize( URI.create(requestUri.getRawPath())); if (requestUri.getRawPath().isEmpty()) { if (event.httpRequest().findField( HttpField.UPGRADE, Converters.STRING_LIST) .map(f -> f.value().containsIgnoreCase("websocket")) .orElse(false)) { channel.setAssociated(this, new PortalInfo()); channel.respond(new WebSocketAccepted(event)); event.stop(); return; } renderPortal(event, channel); return; } URI subUri = uriFromPath("portal-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendPortalResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("theme-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendThemeResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("portlet-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { requestPortletResource(event, channel, subUri); return; } } private void renderPortal(GetRequest event, IOSubchannel channel) throws IOException, InterruptedException { event.stop(); // Because language is changed via websocket, locale cookie // may be out-dated event.associated(Selection.class) .ifPresent(s -> s.prefer(s.get()[0])); // Prepare response HttpResponse response = event.httpRequest().response().get(); MediaType mediaType = MediaType.builder().setType("text", "html") .setParameter("charset", "utf-8").build(); response.setField(HttpField.CONTENT_TYPE, mediaType); response.setStatus(HttpStatus.OK); response.setHasPayload(true); channel.respond(new Response(response)); try (Writer out = new OutputStreamWriter(new ByteBufferOutputStream( channel, channel.responsePipeline()), "utf-8")) { Map<String,Object> portalModel = new HashMap<>(portalBaseModel); // Add locale final Locale locale = event.associated(Selection.class).map( s -> s.get()[0]).orElse(Locale.getDefault()); portalModel.put("locale", locale); // Add supported locales final Collator coll = Collator.getInstance(locale); final Comparator<LanguageInfo> comp = new Comparator<PortalView.LanguageInfo>() { @Override public int compare(LanguageInfo o1, LanguageInfo o2) { return coll.compare(o1.getLabel(), o2.getLabel()); } }; LanguageInfo[] languages = supportedLocales.stream() .map(l -> new LanguageInfo(l)) .sorted(comp).toArray(size -> new LanguageInfo[size]); portalModel.put("supportedLanguages", languages); // Add localization final ResourceBundle additionalResources = resourceSupplier == null ? null : resourceSupplier.apply(locale); final ResourceBundle baseResources = ResourceBundle.getBundle( getClass().getPackage().getName() + ".l10n", locale, ResourceBundle.Control.getNoFallbackControl( ResourceBundle.Control.FORMAT_DEFAULT)); portalModel.put("_", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } String key = ((SimpleScalar)args.get(0)).getAsString(); try { return additionalResources.getString(key); } catch (MissingResourceException e) { // try base resources } try { return baseResources.getString(key); } catch (MissingResourceException e) { // no luck } return key; } }); // Add themes. Doing this on every reload allows themes // to be added dynamically. Note that we must load again // (not reload) in order for this to work in an OSGi environment. themeLoader = ServiceLoader.load(ThemeProvider.class); portalModel.put("themeInfos", StreamSupport.stream(themeLoader().spliterator(), false) .map(t -> new ThemeInfo(t.themeId(), t.themeName())) .sorted().toArray(size -> new ThemeInfo[size])); Template tpl = fmConfig.getTemplate("portal.ftlh"); tpl.process(portalModel, out); } catch (TemplateException e) { throw new IOException(e); } } private void sendPortalResource(GetRequest event, IOSubchannel channel, String resource) { // Look for content InputStream in = this.getClass().getResourceAsStream(resource); if (in == null) { return; } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(in, channel)); // Done event.stop(); } private void sendThemeResource(GetRequest event, IOSubchannel channel, String resource) { try { // Get resource ThemeProvider themeProvider = event.associated(Session.class) .map(session -> (ThemeProvider)session.get("themeProvider")) .orElse(baseTheme); InputStream resIn; try { resIn = themeProvider.getResourceAsStream(resource); } catch (ResourceNotFoundException e) { resIn = baseTheme.getResourceAsStream(resource); } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(resIn, channel)); // Done event.stop(); } catch (ResourceNotFoundException e) { return; } } public static void prepareResourceResponse( HttpResponse response, URI request) { response.setContentType(request); // Set max age in cache-control header List<Directive> directives = new ArrayList<>(); directives.add(new Directive("max-age", 600)); response.setField(HttpField.CACHE_CONTROL, directives); response.setField(HttpField.LAST_MODIFIED, Instant.now()); response.setStatus(HttpStatus.OK); } private void requestPortletResource(GetRequest event, IOSubchannel channel, URI resource) throws InterruptedException { String resPath = resource.getPath(); int sep = resPath.indexOf('/'); // Send events to portlets on portal's channel if (Boolean.TRUE.equals(newEventPipeline().fire( new PortletResourceRequest(resPath.substring(0, sep), uriFromPath(resPath.substring(sep + 1)), event.httpRequest(), channel), portalChannel(channel)) .get())) { event.stop(); } } @Handler public void onInput(Input<ManagedCharBuffer> event, IOSubchannel channel) throws IOException { Optional<PortalInfo> optPortalInfo = channel.associated(this, PortalInfo.class); if (!optPortalInfo.isPresent()) { return; } optPortalInfo.get().toEvent(portalChannel(channel), event.buffer().backingBuffer(), event.isEndOfRecord()); } @Handler(dynamic=true) public void onPortalReady(PortalReady event, IOSubchannel channel) { KeyValueStoreQuery query = new KeyValueStoreQuery( "/themeProvider", true); channel.setAssociated(this, new CompletionLock(event, 3000)); fire(query, channel); } @Handler(dynamic=true) public void onKeyValueStoreData( KeyValueStoreData event, IOSubchannel channel) throws JsonDecodeException { if (!event.event().query().equals("/themeProvider")) { return; } channel.associated(this, CompletionLock.class) .ifPresent(lock -> lock.remove()); String themeId = event.data().values().iterator().next(); ThemeProvider themeProvider = channel.associated(Session.class) .map(session -> (ThemeProvider)session.get("themeProvider")) .orElse(baseTheme); if (!themeProvider.themeId().equals(themeId)) { fire(new SetTheme(themeId), channel); } } @Handler(dynamic=true) public void onPortletResourceResponse(PortletResourceResponse event, LinkedIOSubchannel channel) { HttpRequest request = event.request().httpRequest(); // Send header HttpResponse response = request.response().get(); prepareResourceResponse(response, request.requestUri()); channel.upstreamChannel().respond(new Response(response)); // Send content activeEventPipeline().executorService().submit( new InputStreamPipeline( event.stream(), channel.upstreamChannel())); } @Handler(dynamic=true) public void onSetLocale(SetLocale event, LinkedIOSubchannel channel) throws InterruptedException, IOException { supportedLocales.stream() .filter(l -> l.equals(event.locale())).findFirst() .ifPresent(l -> channel.associated(Selection.class) .map(s -> s.prefer(l))); fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onSetTheme(SetTheme event, LinkedIOSubchannel channel) throws InterruptedException, IOException { ThemeProvider themeProvider = StreamSupport .stream(themeLoader().spliterator(), false) .filter(t -> t.themeId().equals(event.theme())).findFirst() .orElse(baseTheme); channel.associated(Session.class).ifPresent(session -> session.put("themeProvider", themeProvider)); channel.respond(new KeyValueStoreUpdate().update( "/themeProvider", themeProvider.themeId())).get(); fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onJsonOutput(JsonOutput event, LinkedIOSubchannel channel) throws InterruptedException, IOException { IOSubchannel upstream = channel.upstreamChannel(); @SuppressWarnings("resource") CharBufferWriter out = new CharBufferWriter(upstream, upstream.responsePipeline()).suppressClose(); event.toJson(out); out.close(); } private class PortalInfo { private PipedWriter decodeWriter; public void toEvent(IOSubchannel channel, CharBuffer buffer, boolean last) throws IOException { if (decodeWriter == null) { decodeWriter = new PipedWriter(); PipedReader reader = new PipedReader( decodeWriter, buffer.capacity()); activeEventPipeline().executorService() .submit(new DecodeTask(reader, channel)); } decodeWriter.append(buffer); if (last) { decodeWriter.close(); decodeWriter = null; } } private class DecodeTask implements Runnable { IOSubchannel channel; private Reader reader; public DecodeTask(Reader reader, IOSubchannel channel) { this.reader = reader; this.channel = channel; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { try (Reader in = reader) { JsonReader reader = Json.createReader(in); fire(new JsonInput(reader.readObject()), channel); } catch (IOException e) { fire(new IOError(null, e)); } } } } public static class LanguageInfo { private Locale locale; /** * @param locale */ public LanguageInfo(Locale locale) { this.locale = locale; } /** * @return the locale */ public Locale getLocale() { return locale; } public String getLabel() { String str = locale.getDisplayName(locale); return Character.toUpperCase(str.charAt(0)) + str.substring(1); } } public static class ThemeInfo implements Comparable<ThemeInfo> { private String id; private String name; /** * @param id * @param name */ public ThemeInfo(String id, String name) { super(); this.id = id; this.name = name; } /** * @return the id */ public String id() { return id; } /** * @return the name */ public String name() { return name; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(ThemeInfo other) { return name().compareToIgnoreCase(other.name()); } } public static URI uriFromPath(String path) throws IllegalArgumentException { try { return new URI(null, null, path, null); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private class RenderSupportImpl implements RenderSupport { /* (non-Javadoc) * @see org.jgrapes.portal.RenderSupport#portletResource(java.lang.String, java.net.URI) */ @Override public URI portletResource(String portletType, URI uri) { return portal.prefix().resolve(uriFromPath( "portlet-resource/" + portletType + "/")).resolve(uri); } } }
package org.xwiki.wiki.script; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.context.Execution; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.WikiReference; import org.xwiki.script.service.ScriptService; import org.xwiki.script.service.ScriptServiceManager; import org.xwiki.security.authorization.AccessDeniedException; import org.xwiki.security.authorization.AuthorizationException; import org.xwiki.security.authorization.AuthorizationManager; import org.xwiki.security.authorization.Right; import org.xwiki.url.internal.standard.StandardURLConfiguration; import org.xwiki.wiki.configuration.WikiConfiguration; import org.xwiki.wiki.descriptor.WikiDescriptor; import org.xwiki.wiki.descriptor.WikiDescriptorManager; import org.xwiki.wiki.internal.descriptor.document.WikiDescriptorDocumentHelper; import org.xwiki.wiki.manager.WikiManager; import org.xwiki.wiki.manager.WikiManagerException; import com.xpn.xwiki.XWikiContext; /** * Script service to manage wikis. * * @version $Id$ * @since 5.3M2 */ @Component @Named(WikiManagerScriptService.ROLEHINT) @Singleton public class WikiManagerScriptService implements ScriptService { /** * Hint of the component. */ public static final String ROLEHINT = "wiki"; /** * Field name of the last API exception inserted in context. */ @Deprecated public static final String CONTEXT_LASTEXCEPTION = "lastexception"; /** * The key under which the last encountered error is stored in the current execution context. */ private static final String WIKIERROR_KEY = "scriptservice.wiki.error"; @Inject private WikiManager wikiManager; @Inject private WikiDescriptorManager wikiDescriptorManager; @Inject private Provider<XWikiContext> xcontextProvider; /** * Execution context. */ @Inject private Execution execution; @Inject private AuthorizationManager authorizationManager; @Inject private DocumentReferenceResolver<String> documentReferenceResolver; @Inject private EntityReferenceSerializer<String> entityReferenceSerializer; @Inject private ScriptServiceManager scriptServiceManager; @Inject private StandardURLConfiguration standardURLConfiguration; @Inject private WikiConfiguration wikiConfiguration; @Inject private WikiDescriptorDocumentHelper wikiDescriptorDocumentHelper; /** * Logging tool. */ @Inject private Logger logger; /** * Get a sub script service related to wiki. (Note that we're voluntarily using an API name of "get" to make it * extra easy to access Script Services from Velocity (since in Velocity writing <code>$services.wiki.name</code> is * equivalent to writing <code>$services.wiki.get("name")</code>). It also makes it a short and easy API name for * other scripting languages. * * @param serviceName id of the script service * @return the service asked or null if none could be found */ public ScriptService get(String serviceName) { return scriptServiceManager.get(ROLEHINT + '.' + serviceName); } /** * Get the error generated while performing the previously called action. * * @return an eventual exception or {@code null} if no exception was thrown */ public Exception getLastError() { return (Exception) this.execution.getContext().getProperty(WIKIERROR_KEY); } /** * Store a caught exception in the context, so that it can be later retrieved using {@link #getLastError()}. * * @param e the exception to store, can be {@code null} to clear the previously stored exception * @see #getLastError() */ private void setLastError(Exception e) { this.execution.getContext().setProperty(WIKIERROR_KEY, e); } // TODO: move to new API a soon as a proper helper is provided private void checkProgrammingRights() throws AuthorizationException { XWikiContext xcontext = this.xcontextProvider.get(); authorizationManager.checkAccess(Right.PROGRAM, xcontext.getDoc().getAuthorReference(), xcontext.getDoc() .getDocumentReference()); } /** * Create a new wiki. * * @param wikiId unique identifier of the new wiki * @param wikiAlias default alias of the new wiki * @param ownerId Id of the user that will own the wiki * @param failOnExist Fail the operation if the wiki id already exists * @return the wiki descriptor of the new wiki, or null if problems occur */ public WikiDescriptor createWiki(String wikiId, String wikiAlias, String ownerId, boolean failOnExist) { WikiDescriptor descriptor = null; XWikiContext context = xcontextProvider.get(); try { // Check if the current script has the programing rights checkProgrammingRights(); // Check right access WikiReference mainWikiReference = new WikiReference(getMainWikiId()); authorizationManager.checkAccess(Right.CREATE_WIKI, context.getUserReference(), mainWikiReference); if (!failOnExist) { authorizationManager.checkAccess(Right.PROGRAM, context.getUserReference(), mainWikiReference); } // Create the wiki descriptor = wikiManager.create(wikiId, wikiAlias, failOnExist); // Set the owner descriptor.setOwnerId(ownerId); wikiDescriptorManager.saveDescriptor(descriptor); } catch (Exception e) { error(e); } return descriptor; } /** * Delete the specified wiki. * * @param wikiId unique identifier of the wiki to delete * @return true if the wiki has been successfully deleted */ public boolean deleteWiki(String wikiId) { // Test if the script has the programming right XWikiContext context = xcontextProvider.get(); try { // Check if the current script has the programming rights checkProgrammingRights(); // Test right if (!canDeleteWiki(entityReferenceSerializer.serialize(context.getUserReference()), wikiId)) { throw new AuthorizationException("You don't have the right to delete the wiki"); } // Delete the wiki wikiManager.delete(wikiId); // Return success return true; } catch (Exception e) { error(String.format("Failed to delete wiki [%s]", wikiId), e); } return false; } /** * Test if a given user can delete a given wiki. * * @param userId the id of the user to test * @param wikiId the id of the wiki * @return whether or not the user can delete the specified wiki */ public boolean canDeleteWiki(String userId, String wikiId) { try { // Get target wiki descriptor WikiDescriptor descriptor = wikiDescriptorManager.getById(wikiId); if (descriptor == null) { error(new Exception(String.format("Could not find wiki [%s]]", wikiId))); return false; } // Get the full reference of the given user DocumentReference userReference = documentReferenceResolver.resolve(userId); String fullUserId = entityReferenceSerializer.serialize(userReference); // If the user is the owner String owner = descriptor.getOwnerId(); if (fullUserId.equals(owner)) { return true; } // If the user is an admin WikiReference wikiReference = new WikiReference(wikiId); if (authorizationManager.hasAccess(Right.ADMIN, userReference, wikiReference)) { return true; } } catch (WikiManagerException e) { error(String.format("Error while getting the descriptor of wiki [%s]", wikiId), e); } return false; } /** * Get a wiki descriptor from one of its alias. * * @param wikiAlias alias to search * @return the wiki descriptor corresponding to the alias, or null if no descriptors match the alias */ public WikiDescriptor getByAlias(String wikiAlias) { WikiDescriptor descriptor = null; try { descriptor = wikiDescriptorManager.getByAlias(wikiAlias); } catch (WikiManagerException e) { error(e); } return descriptor; } /** * Get a wiki descriptor from its unique identifier. * * @param wikiId unique identifier of the wiki to search * @return the wiki descriptor corresponding to the Id, or null if no descriptors match the id */ public WikiDescriptor getById(String wikiId) { WikiDescriptor descriptor = null; try { descriptor = wikiDescriptorManager.getById(wikiId); } catch (WikiManagerException e) { error(e); } return descriptor; } /** * Get all the wiki descriptors. * * @return the list of all wiki descriptors */ public Collection<WikiDescriptor> getAll() { Collection<WikiDescriptor> wikis; try { wikis = wikiDescriptorManager.getAll(); } catch (WikiManagerException e) { error(e); wikis = new ArrayList<WikiDescriptor>(); } return wikis; } /** * Get all the wiki identifiers. * * @return the list of all wiki identifiers * @since 6.2M1 */ public Collection<String> getAllIds() { Collection<String> wikis; try { wikis = wikiDescriptorManager.getAllIds(); } catch (WikiManagerException e) { error(e); wikis = new ArrayList<String>(); } return wikis; } /** * Test if a wiki exists. * * @param wikiId unique identifier to test * @return true if a wiki with this Id exists on the system or null if some error occurs. */ public Boolean exists(String wikiId) { try { return wikiDescriptorManager.exists(wikiId); } catch (WikiManagerException e) { error(e); return null; } } /** * Check if the wikiId is valid and available (the name is not already taken for technical reasons). * * @param wikiId the Id to test * @return true if the Id is valid and available or null if some error occurs */ public Boolean idAvailable(String wikiId) { try { return wikiManager.idAvailable(wikiId); } catch (WikiManagerException e) { error(e); return null; } } /** * @return the descriptor of the main wiki or null if problems occur */ public WikiDescriptor getMainWikiDescriptor() { WikiDescriptor descriptor = null; try { descriptor = wikiDescriptorManager.getMainWikiDescriptor(); } catch (WikiManagerException e) { error(e); } return descriptor; } /** * @return the Id of the main wiki */ public String getMainWikiId() { return wikiDescriptorManager.getMainWikiId(); } /** * @return the id of the current wiki */ public String getCurrentWikiId() { return wikiDescriptorManager.getCurrentWikiId(); } /** * @return the descriptor of the current wiki */ public WikiDescriptor getCurrentWikiDescriptor() { WikiDescriptor descriptor = null; try { descriptor = wikiDescriptorManager.getCurrentWikiDescriptor(); } catch (WikiManagerException e) { error(e); } return descriptor; } /** * Save the specified descriptor (if you have the right). * * @param descriptor descriptor to save * @return true if it succeed */ public boolean saveDescriptor(WikiDescriptor descriptor) { XWikiContext context = xcontextProvider.get(); boolean result = false; try { // Get the wiki owner WikiDescriptor oldDescriptor = wikiDescriptorManager.getById(descriptor.getId()); WikiReference wikiReference = descriptor.getReference(); if (oldDescriptor != null) { if (!result) { // Users that can edit the wiki's descriptor document are allowed to use this API as well. This // includes global admins. DocumentReference descriptorDocument = wikiDescriptorDocumentHelper.getDocumentReferenceFromId(oldDescriptor.getId()); result = authorizationManager.hasAccess(Right.EDIT, context.getUserReference(), descriptorDocument); } String currentOwner = oldDescriptor.getOwnerId(); if (!result) { // The current owner can edit anything. result = entityReferenceSerializer.serialize(context.getUserReference()).equals(currentOwner); } if (!result) { // Local admins can edit the descriptor, except for the "ownerId" field, which should be // editable only by the current owner or main wiki admins. String newOwner = descriptor.getOwnerId(); result = authorizationManager.hasAccess(Right.ADMIN, context.getUserReference(), wikiReference) && StringUtils.equals(newOwner, currentOwner); } } else { // Saving a descriptor that did not already exist should be reserved to global admins result = authorizationManager.hasAccess(Right.ADMIN, context.getUserReference(), new WikiReference( wikiDescriptorManager.getMainWikiId())); } if (!result) { // Exhausted all options. Deny access for the current user to edit the descriptor. throw new AccessDeniedException(context.getUserReference(), wikiReference); } else { // Execute the operation. wikiDescriptorManager.saveDescriptor(descriptor); } return result; } catch (Exception e) { error(e); return false; } } public boolean isPathMode() { return standardURLConfiguration.isPathBasedMultiWiki(); } /** * @return the default suffix to append to new wiki aliases. */ public String getAliasSuffix() { return wikiConfiguration.getAliasSuffix(); } /** * Log exception and store it in the context. * * @param e the caught exception */ private void error(Exception e) { error(null, e); } /** * Log exception and store it in the context. * * @param errorMessage error message * @param e the caught exception */ private void error(String errorMessage, Exception e) { String errorMessageToLog = errorMessage; if (errorMessageToLog == null) { errorMessageToLog = e.getMessage(); } // Log exception. logger.error(errorMessageToLog, e); // Store exception in context. setLastError(e); // Deprecated this.execution.getContext().setProperty(CONTEXT_LASTEXCEPTION, e); } /** * @return the last exception, or null if there is not * @deprecated since 5.4RC1 use {@link #getLastError()} ()} instead */ @Deprecated public Exception getLastException() { return (Exception) this.execution.getContext().getProperty(CONTEXT_LASTEXCEPTION); } }
package hex.ensemble; import hex.DistributionFactory; import hex.Model; import hex.ModelBuilder; import hex.ensemble.Metalearner.Algorithm; import hex.genmodel.utils.DistributionFamily; import hex.glm.GLM; import hex.glm.GLMModel; import hex.glm.GLMModel.GLMParameters; import water.exceptions.H2OIllegalArgumentException; import water.nbhm.NonBlockingHashMap; import water.util.ArrayUtils; import water.util.Log; import java.util.ServiceLoader; import java.util.function.Supplier; /** * Entry point class to load and access the supported metalearners. * Most of them are defined in this class, but some others can be loaded dynamically from the classpath, * this is for example the case with the XGBoostMetalearner. */ public class Metalearners { static final NonBlockingHashMap<String, MetalearnerProvider> providersByName = new NonBlockingHashMap<>(); static { LocalProvider[] localProviders = new LocalProvider[] { new LocalProvider<>(Algorithm.AUTO, AUTOMetalearner::new), new LocalProvider<>(Algorithm.deeplearning, DLMetalearner::new), new LocalProvider<>(Algorithm.drf, DRFMetalearner::new), new LocalProvider<>(Algorithm.gbm, GBMMetalearner::new), new LocalProvider<>(Algorithm.glm, GLMMetalearner::new), new LocalProvider<>(Algorithm.naivebayes, NaiveBayesMetalearner::new), }; for (MetalearnerProvider provider : localProviders) { providersByName.put(provider.getName(), provider); } ServiceLoader<MetalearnerProvider> extensionProviders = ServiceLoader.load(MetalearnerProvider.class); for (MetalearnerProvider provider : extensionProviders) { providersByName.put(provider.getName(), provider); } } static Algorithm getActualMetalearnerAlgo(Algorithm algo) { assertAvailable(algo.name()); return algo == Algorithm.AUTO ? Algorithm.glm : algo; } static Model.Parameters createParameters(String name) { assertAvailable(name); return createInstance(name).createBuilder()._parms; } static Metalearner createInstance(String name) { assertAvailable(name); return providersByName.get(name).newInstance(); } private static void assertAvailable(String algo) { if (!providersByName.containsKey(algo)) throw new H2OIllegalArgumentException("'"+algo+"' metalearner is not supported or available."); } /** * A local implementation of {@link MetalearnerProvider} to expose the {@link Metalearner}s defined in this class. */ static class LocalProvider<M extends Metalearner> implements MetalearnerProvider<M> { private Algorithm _algorithm; private Supplier<M> _instanceFactory; public LocalProvider(Algorithm algorithm, Supplier<M> instanceFactory) { _algorithm = algorithm; _instanceFactory = instanceFactory; } @Override public String getName() { return _algorithm.name(); } @Override public M newInstance() { return _instanceFactory.get(); } } /** * A simple implementation of {@link Metalearner} suitable for any algo; it is just using the algo with its default parameters. */ public static class SimpleMetalearner extends Metalearner { private String _algo; protected SimpleMetalearner(String algo) { _algo = algo; } @Override ModelBuilder createBuilder() { return ModelBuilder.make(_algo, _metalearnerJob, _metalearnerKey); } protected String getAlgo() { return _algo; } } static class MetalearnerWithDistribution extends SimpleMetalearner { protected DistributionFamily[] _supportedDistributionFamilies; protected MetalearnerWithDistribution(String algo) { super(algo); } @Override protected void validateParams(Model.Parameters parms) { super.validateParams(parms); // Check if distribution family is supported and if not pick a basic one if (!ArrayUtils.contains(_supportedDistributionFamilies, parms._distribution)) { DistributionFamily distribution; if (_model._output.nclasses() == 1) { distribution = DistributionFamily.gaussian; } else if (_model._output.nclasses() == 2) { distribution = DistributionFamily.bernoulli; } else { distribution = DistributionFamily.multinomial; } Log.warn("Distribution \"" + parms._distribution + "\" is not supported by metalearner algorithm \"" + getAlgo() + "\". Using \"" + distribution + "\" instead."); parms._distribution = distribution; } } } static class DLMetalearner extends MetalearnerWithDistribution { public DLMetalearner() { super(Algorithm.deeplearning.name()); _supportedDistributionFamilies = new DistributionFamily[]{ DistributionFamily.AUTO, DistributionFamily.bernoulli, DistributionFamily.multinomial, DistributionFamily.gaussian, DistributionFamily.poisson, DistributionFamily.gamma, DistributionFamily.laplace, DistributionFamily.quantile, DistributionFamily.huber, DistributionFamily.tweedie, }; } } static class DRFMetalearner extends MetalearnerWithDistribution { public DRFMetalearner() { super(Algorithm.drf.name()); _supportedDistributionFamilies = new DistributionFamily[]{ DistributionFamily.AUTO, DistributionFamily.bernoulli, DistributionFamily.multinomial, DistributionFamily.gaussian, }; } } static class GBMMetalearner extends MetalearnerWithDistribution { public GBMMetalearner() { super(Algorithm.gbm.name()); _supportedDistributionFamilies = new DistributionFamily[]{ DistributionFamily.AUTO, DistributionFamily.bernoulli, DistributionFamily.quasibinomial, DistributionFamily.multinomial, DistributionFamily.gaussian, DistributionFamily.poisson, DistributionFamily.gamma, DistributionFamily.laplace, DistributionFamily.quantile, DistributionFamily.huber, DistributionFamily.tweedie, DistributionFamily.custom, }; } } static class GLMMetalearner extends Metalearner<GLM, GLMModel, GLMParameters> { @Override GLM createBuilder() { return ModelBuilder.make("GLM", _metalearnerJob, _metalearnerKey); } } static class NaiveBayesMetalearner extends SimpleMetalearner { public NaiveBayesMetalearner() { super(Algorithm.naivebayes.name()); } } static class AUTOMetalearner extends GLMMetalearner { @Override protected void setCustomParams(GLMParameters parms) { //add GLM custom params super.setCustomParams(parms); //specific to AUTO mode parms._non_negative = true; //parms._alpha = new double[] {0.0, 0.25, 0.5, 0.75, 1.0}; //parms._alpha = new double[] {0.5, 1.0}; parms._alpha = new double[] {1.0}; // feature columns are already homogeneous (probabilities); when standardization is enabled, // there can be information loss if some columns have very low probabilities compared with others for example (bad model) // giving more weight than it should to those columns. parms._standardize = false; // Enable lambda search if a validation frame is passed in to get a better GLM fit. // Since we are also using non_negative to true, we should also set early_stopping = false. if (parms._valid != null) { parms._lambda_search = true; parms._early_stopping = false; } } } }
package org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editpolicies.ReportContainerEditPolicy; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editpolicies.ReportFlowLayoutEditPolicy; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.figures.AreaFigure; import org.eclipse.birt.report.designer.internal.ui.layout.ReportFlowLayout; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DimensionHandle; import org.eclipse.birt.report.model.api.SimpleMasterPageHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.GraphicalEditPart; /** * Provides support for area edit part. */ public class AreaEditPart extends ReportElementEditPart { /** * Constructor * * @param model */ public AreaEditPart( Object model ) { super( model ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure() */ protected IFigure createFigure( ) { AreaFigure figure = new AreaFigure( ); figure.setLayoutManager( new ReportFlowLayout( ) ); return figure; } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#createEditPolicies() */ protected void createEditPolicies( ) { installEditPolicy( EditPolicy.COMPONENT_ROLE, null ); installEditPolicy( EditPolicy.LAYOUT_ROLE, new ReportFlowLayoutEditPolicy( ) ); installEditPolicy( EditPolicy.CONTAINER_ROLE, new ReportContainerEditPolicy( ) ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#getModelChildren() */ protected List getModelChildren( ) { List list = new ArrayList( ); insertIteratorToList( ( (SlotHandle) getModel( ) ) .iterator( ), list ); return list; } // TODO:move this code into util class? protected void insertIteratorToList( Iterator iterator, List list ) { for ( Iterator it = iterator; it.hasNext( ); ) { list.add( ( it.next( ) ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart#refreshFigure() */ public void refreshFigure( ) { ( (MasterPageEditPart) getParent( ) ).setLayoutConstraint( this, figure, getConstraint( ) ); } /** * Get the default constraint of area figure. * * @return */ private Rectangle getConstraint( ) { IFigure parent = ( (MasterPageEditPart) getParent( ) ).getFigure( ); Rectangle region = parent.getClientArea( ); Rectangle rect = new Rectangle( ); rect.height = -1; rect.width = region.width; // Define the default height value of header and footer SimpleMasterPageHandle mphandle = ( (SimpleMasterPageHandle) ( (MasterPageEditPart) getParent( ) ) .getModel( ) ); if ( ( (SlotHandle) getModel( ) ).getSlotID( ) == SimpleMasterPageHandle.PAGE_HEADER_SLOT ) { if ( mphandle.getPropertyHandle( SimpleMasterPageHandle.HEADER_HEIGHT_PROP ).isSet( ) || DEUtil.isFixLayout( getParent( ).getModel( ) )) { DimensionHandle handle = mphandle.getHeaderHeight( ); rect.height = getHeight( handle ); } } else { if ( mphandle.getPropertyHandle( SimpleMasterPageHandle.FOOTER_HEIGHT_PROP ).isSet( ) || DEUtil.isFixLayout( getParent( ).getModel( ) )) { DimensionHandle handle = mphandle.getFooterHeight( ); rect.height = getHeight( handle); } } if ( ( (SlotHandle) getModel( ) ).getSlotID( ) == SimpleMasterPageHandle.PAGE_HEADER_SLOT ) { rect.setLocation( 0, 0 ); } else { rect.setLocation( -1, -1 ); } return rect; } private int getHeight(DimensionHandle handle) { if ( DesignChoiceConstants.UNITS_PERCENTAGE.equals( handle.getUnits( ) ) ) { return (int)(((GraphicalEditPart)getParent( )).getFigure( ).getClientArea( ).height*handle.getMeasure( )/100); } return (int) DEUtil.convertoToPixel( handle ); } }
package com.fazend.web; import com.rexsl.page.HttpHeadersMocker; import com.rexsl.page.UriInfoMocker; import com.rexsl.test.JaxbConverter; import com.rexsl.test.XhtmlMatchers; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.mockito.Mockito; /** * Test case for {@link IndexRs}. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id: IndexRsTest.java 2344 2013-01-13 18:28:44Z guard $ */ public final class IndexRsTest { /** * IndexRs can render front page. * @throws Exception If some problem inside */ @Test public void rendersFrontPage() throws Exception { final IndexRs res = new IndexRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); res.setSecurityContext(Mockito.mock(SecurityContext.class)); final Response response = res.index(); MatcherAssert.assertThat( JaxbConverter.the(response.getEntity()), XhtmlMatchers.hasXPaths( "/page/message[.='Hello, world!']", "/page/version[name='1.0-SNAPSHOT']" ) ); } }
package hex; import water.*; import water.fvec.Vec; abstract public class SupervisedModelBuilder<M extends SupervisedModel<M,P,O>, P extends SupervisedModel.SupervisedParameters, O extends SupervisedModel.SupervisedOutput> extends ModelBuilder<M,P,O> { protected transient Vec _response; // Handy response column public Key _response_key; // Handy response column public Vec response() { return _response == null ? (_response = DKV.getGet(_response_key)) : _response; } protected transient Vec _vresponse; // Handy validation response column public Key _vresponse_key; // Handy response column public Vec vresponse() { return _vresponse == null ? (_vresponse = DKV.getGet(_vresponse_key)) : _vresponse; } public int _nclass; // Number of classes; 1 for regression; 2+ for classification public final boolean isClassifier() { return _nclass > 1; } public boolean isSupervised() { return true; } /** Constructor called from an http request; MUST override in subclasses. */ //public SupervisedModelBuilder(P parms) { super(parms); /*only call init in leaf classes*/ } public SupervisedModelBuilder(String desc, P parms) { super(desc,parms); /*only call init in leaf classes*/ } public SupervisedModelBuilder(Key dest, String desc, P parms) { super(dest,desc,parms); /*only call init in leaf classes*/ } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the response column; move it to the end; flip it to an Categorical if * requested. Validate the max_after_balance_size; compute the number of * classes. */ @Override public void init(boolean expensive) { super.init(expensive); if (! _parms._balance_classes) hide("_max_after_balance_size", "Balance classes is false, hide max_after_balance_size"); if( _parms._max_after_balance_size <= 0.0 ) error("_max_after_balance_size","Max size after balancing needs to be positive, suggest 1.0f"); if( _train == null ) return; // Nothing more to check if( _train.numCols() <= 1 ) error("_train", "Training data must have at least 2 features (incl. response)."); if (!isSupervised()) { hide("_response_column", "Ignored for unsupervised methods."); hide("_balance_classes", "Ignored for unsupervised methods."); hide("_class_sampling_factors", "Ignored for unsupervised methods."); hide("_max_after_balance_size", "Ignored for unsupervised methods."); hide("_max_confusion_matrix_size", "Ignored for unsupervised methods."); _response = null; _response_key = null; _vresponse = null; _nclass = 1; return; } else if (expensive && _parms._balance_classes && (long)(_train.numRows()*_parms._max_after_balance_size) <= _train.lastVec().domain().length ) error("_max_after_balance_size","Cannot end up with fewer rows than there are response levels. Increase max after balance size."); if( null == _parms._response_column) { error("_response_column", "Response column parameter not set."); return; } if( !_parms._balance_classes ) { hide("_max_after_balance_size", "Only used with balanced classes"); hide("_class_sampling_factors", "Class sampling factors is only applicable if balancing classes."); } // put response to the end (if not already) int ridx = _train.find(_parms._response_column); if( ridx == -1 ) { // Actually, think should not get here either (cutout at higher layer) error("_response_column", "Response column " + _parms._response_column + " not found in frame: " + _parms._train + "."); } else { _response = _train.remove(ridx); if( _valid != null && _valid.find(_parms._response_column)== -1 ) error("_response_column", "Response column is missing in the validation set!"); _vresponse = _valid == null ? null : _valid.remove(ridx); if (_response.isBad()) error("_response_column", "Response column is all NAs!"); if (_response.isConst()) error("_response_column", "Response column is constant!"); _train.add(_parms._response_column, _response); _response_key = _response._key; if (_valid != null) { _valid.add(_parms._response_column, _vresponse); _vresponse_key = _vresponse._key; } // #Classes: 1 for regression, domain-length for enum columns _nclass = _response.isEnum() ? _response.domain().length : 1; if( !isClassifier() ) { hide("_balance_classes", "Balance classes is only applicable to classification problems."); hide("_class_sampling_factors", "Class sampling factors is only applicable to classification problems."); hide("_max_after_balance_size", "Max after balance size is only applicable to classification problems."); hide("_max_confusion_matrix_size", "Max confusion matrix size is only applicable to classification problems."); } if (_nclass <= 2) hide("_max_hit_ratio_k", "Max K-value for hit ratio is only applicable to multi-class classification problems."); if (_nclass <= 2) hide("_max_confusion_matrix_size", "Only for multi-class classification problems."); } } }
package net.bootsfaces.listeners; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.application.Application; import javax.faces.application.ProjectStage; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.component.html.HtmlBody; import javax.faces.component.html.HtmlHead; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; import net.bootsfaces.C; /** * This class adds the resource needed by BootsFaces and ensures that they are * loaded in the correct order. It replaces the former HeadListener. * * @author Stephan Rauh */ public class AddResourcesListener implements SystemEventListener { private static final Logger LOGGER = Logger.getLogger("net.bootsfaces.listeners.AddResourcesListener"); /** * Components can request resources by registering them in the ViewMap, * using the RESOURCE_KEY. */ private static final String RESOURCE_KEY = "net.bootsfaces.listeners.AddResourcesListener.ResourceFiles"; static { LOGGER.info("net.bootsfaces.listeners.AddResourcesListener ready for use."); } /** * Trigger adding the resources if and only if the event has been fired by * UIViewRoot. */ public void processEvent(SystemEvent event) throws AbortProcessingException { Object source = event.getSource(); if (source instanceof UIViewRoot) { final FacesContext context = FacesContext.getCurrentInstance(); boolean isProduction = context.isProjectStage(ProjectStage.Production); addJavascript((UIViewRoot) source, context, isProduction); } } /** * Add the required Javascript files and the FontAwesome CDN link. * * @param root * The UIViewRoot of the JSF tree. * @param context * The current FacesContext * @param isProduction * This flag can be used to deliver different version of the JS * library, optimized for debugging or production. */ private void addJavascript(UIViewRoot root, FacesContext context, boolean isProduction) { Application app = context.getApplication(); ResourceHandler rh = app.getResourceHandler(); // If the BootsFaces_USETHEME parameter is true, render Theme CSS link String theme = null; theme = context.getExternalContext().getInitParameter(C.P_USETHEME); if (isFontAwesomeComponentUsedAndRemoveIt() || (theme != null && theme.equals(C.TRUE))) { Resource themeResource = rh.createResource(C.BSF_CSS_TBSTHEME, C.BSF_LIBRARY); if (themeResource == null) { throw new FacesException("Error loading theme, cannot find \"" + C.BSF_CSS_TBSTHEME + "\" resource of \"" + C.BSF_LIBRARY + "\" library"); } else { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Stylesheet"); output.getAttributes().put("name", C.BSF_CSS_TBSTHEME); output.getAttributes().put("library", C.BSF_LIBRARY); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } // deactive FontAwesome support if the no-fa facet is found in the // h:head tag UIComponent header = findHeader(root); boolean useCDNImportForFontAwesome = (null == header) || (null == header.getFacet("no-fa")); if (useCDNImportForFontAwesome) { String useCDN = FacesContext.getCurrentInstance().getExternalContext() .getInitParameter("net.bootsfaces.get_fontawesome_from_cdn"); if (null != useCDN) if (useCDN.equalsIgnoreCase("false") || useCDN.equals("no")) useCDNImportForFontAwesome = false; } // Do we have to add font-awesome and jQuery, or are the resources // already there? boolean loadJQuery = true; List<UIComponent> availableResources = root.getComponentResources(context, "head"); for (UIComponent ava : availableResources) { String name = (String) ava.getAttributes().get("name"); if (null != name) { name = name.toLowerCase(); if ((name.contains("font-awesome") || name.contains("fontawesome")) && name.endsWith("css")) useCDNImportForFontAwesome = false; if (name.contains("jquery-ui") && name.endsWith(".js")) { // do nothing - the if is needed to avoid confusion between // jQuery and jQueryUI } else if (name.contains("jquery") && name.endsWith(".js")) { loadJQuery = false; } } } // Font Awesome if (useCDNImportForFontAwesome) { // !=null && usefa.equals(C.TRUE)) { InternalFALink output = new InternalFALink(); output.getAttributes().put("src", C.FONTAWESOME_CDN_URL); addResourceIfNecessary(root, context, output); } Map<String, Object> viewMap = root.getViewMap(); @SuppressWarnings("unchecked") Map<String, String> resourceMap = (Map<String, String>) viewMap.get(RESOURCE_KEY); if (null != resourceMap) { if (loadJQuery) { boolean needsJQuery = false; for (Entry<String, String> entry : resourceMap.entrySet()) { String file = entry.getValue(); if ("jq/jquery.js".equals(file)) { needsJQuery = true; } } if (needsJQuery) { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Script"); output.getAttributes().put("name", "jq/jquery.js"); output.getAttributes().put("library", C.BSF_LIBRARY); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } for (Entry<String, String> entry : resourceMap.entrySet()) { String file = entry.getValue(); String library = entry.getKey().substring(0, entry.getKey().length() - file.length() - 1); if (!"jq/jquery.js".equals(file)) { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Script"); output.getAttributes().put("name", file); output.getAttributes().put("library", library); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } } enforceCorrectLoadOrder(root, context); { InternalIE8CompatiblityLinks output = new InternalIE8CompatiblityLinks(); addResourceIfNecessary(root, context, output); } } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, InternalIE8CompatiblityLinks output) { for (UIComponent c : root.getComponentResources(context, "head")) { if (c instanceof InternalIE8CompatiblityLinks) return; } root.addComponentResource(context, output, "head"); } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, InternalFALink output) { for (UIComponent c : root.getComponentResources(context, "head")) { if (c instanceof InternalFALink) return; } root.addComponentResource(context, output, "head"); } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, UIOutput output) { for (UIComponent c : root.getComponentResources(context, "head")) { String library = (String) c.getAttributes().get("library"); String name = (String) c.getAttributes().get("name"); if (library != null && library.equals(output.getAttributes().get("library"))) { if (name != null && library.equals(output.getAttributes().get("name"))) { return; } } } root.addComponentResource(context, output, "head"); } /** * Make sure jQuery is loaded before jQueryUI, and that every other * Javascript is loaded later. Also make sure that the BootsFaces resource * files are loaded prior to other resource files, giving the developer the * opportunity to overwrite a CSS or JS file. * * @param root * The current UIViewRoot * @param context * The current FacesContext */ private void enforceCorrectLoadOrder(UIViewRoot root, FacesContext context) { List<UIComponent> resources = new ArrayList<UIComponent>(root.getComponentResources(context, "head")); Collections.sort(resources, new Comparator<UIComponent>() { @Override public int compare(UIComponent o1, UIComponent o2) { String name1 = (String) o1.getAttributes().get("name"); // String lib1 = (String) o1.getAttributes().get("name"); String name2 = (String) o2.getAttributes().get("name"); // String lib2 = (String) o2.getAttributes().get("name"); if (name1 == null) return 1; if (name2 == null) return -1; if (name1.endsWith(".js") && (!(name2.endsWith(".js")))) return 1; if (name2.endsWith(".js") && (!(name1.endsWith(".js")))) return -1; if (name1.endsWith(".js")) { if (name1.contains("jquery-ui")) name1 = "2.js"; // make it the second JS file else if (name1.contains("jquery")) name1 = "1.js"; // make it the second JS file else if (name1.contains("bsf.js")) name1 = "zzz.js"; // make it the last JS file else name1="keep.js"; // don't move it } if (name2.endsWith(".js")) { if (name2.contains("jquery-ui")) name2 = "2.js"; // make it the second JS file else if (name2.contains("jquery")) name2 = "1.js"; // make it the second JS file else if (name2.contains("bsf.js")) name2 = "zzz.js"; // make it the last JS file else name2="keep.js"; // don't move it } int result = name1.compareTo(name2); return result; } }); for (UIComponent c : resources) { // System.out.println((String) c.getAttributes().get("name")); root.removeComponentResource(context, c); } for (UIComponent c : resources) { root.addComponentResource(context, c, "head"); } // resources = new ArrayList<UIComponent>(root.getComponentResources(context, "head")); // for (UIComponent c : resources) { // System.out.println((String) c.getAttributes().get("name")); } /** * Look whether a b:iconAwesome component is used. If so, the * font-awesome.css is removed from the resource list because it's loaded * from the CDN. * * @return true, if the font-awesome.css is found in the resource list. Note * the side effect of this method! */ private boolean isFontAwesomeComponentUsedAndRemoveIt() { FacesContext fc = FacesContext.getCurrentInstance(); UIViewRoot viewRoot = fc.getViewRoot(); ListIterator<UIComponent> resourceIterator = (viewRoot.getComponentResources(fc, "head")).listIterator(); UIComponent fontAwesomeResource = null; while (resourceIterator.hasNext()) { UIComponent resource = (UIComponent) resourceIterator.next(); String name = (String) resource.getAttributes().get("name"); // rw.write("\n<!-- res: '"+name+"' -->" ); if (name != null) { if (name.endsWith("font-awesome.css")) fontAwesomeResource = resource; } } if (null != fontAwesomeResource) { viewRoot.removeComponentResource(fc, fontAwesomeResource); return true; } return false; } /** * Looks for the header in the JSF tree. * * @param root * The root of the JSF tree. * @return null, if the head couldn't be found. */ private UIComponent findHeader(UIViewRoot root) { for (UIComponent c : root.getChildren()) { if (c instanceof HtmlHead) return c; } for (UIComponent c : root.getChildren()) { if (c instanceof HtmlBody) return null; if (c instanceof UIOutput) if (c.getFacets() != null) return c; } return null; } /** * Which JSF elements do we listen to? */ @Override public boolean isListenerForSource(Object source) { if (source instanceof UIComponent) { return true; } return false; } /** * Registers a JS file that needs to be include in the header of the HTML * file, but after jQuery and AngularJS. * * @param library * The name of the sub-folder of the resources folder. * @param resource * The name of the resource file within the library folder. */ public static void addResourceToHeadButAfterJQuery(String library, String resource) { FacesContext ctx = FacesContext.getCurrentInstance(); UIViewRoot v = ctx.getViewRoot(); Map<String, Object> viewMap = v.getViewMap(); @SuppressWarnings("unchecked") Map<String, String> resourceMap = (Map<String, String>) viewMap.get(RESOURCE_KEY); if (null == resourceMap) { resourceMap = new HashMap<String, String>(); viewMap.put(RESOURCE_KEY, resourceMap); } String key = library + "#" + resource; if (!resourceMap.containsKey(key)) { resourceMap.put(key, resource); } } }
package io.cattle.platform.agent.connection.delegate; import io.cattle.platform.agent.RemoteAgent; import io.cattle.platform.agent.server.connection.AgentConnection; import io.cattle.platform.async.utils.AsyncUtils; import io.cattle.platform.eventing.EventCallOptions; import io.cattle.platform.eventing.model.Event; import io.cattle.platform.eventing.model.EventVO; import io.cattle.platform.iaas.event.delegate.DelegateEvent; import io.cattle.platform.json.JsonMapper; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; public class AgentDelegateConnection implements AgentConnection { private static final Logger log = LoggerFactory.getLogger(AgentDelegateConnection.class); String uri; long agentId; boolean open = true; RemoteAgent remoteAgent; Map<String,Object> instanceData; JsonMapper jsonMapper; public AgentDelegateConnection(RemoteAgent remoteAgent, long agentId, String uri, Map<String,Object> instanceData, JsonMapper jsonMapper) { super(); this.remoteAgent = remoteAgent; this.agentId = agentId; this.uri = uri; this.jsonMapper = jsonMapper; this.instanceData = instanceData; } @Override public long getAgentId() { return agentId; } @Override public ListenableFuture<Event> execute(final Event event) { if ( ! open ) { return AsyncUtils.error(new IOException("Agent connection is closed")); } DelegateEvent delegateEvent = new DelegateEvent(instanceData, event); log.debug("Delegating [{}] [{}] inner [{}] [{}]", event.getName(), event.getId(), delegateEvent.getName(), delegateEvent.getId()); EventCallOptions options = new EventCallOptions(0, event.getTimeoutMillis()); return Futures.transform(remoteAgent.call(delegateEvent, options), new AsyncFunction<Event, Event>() { @Override public ListenableFuture<Event> apply(Event input) throws Exception { if ( input == null ) { return AsyncUtils.done(null); } Object data = input.getData(); if ( data == null ) { throw new IllegalStateException("No response for delegated input event [" + event.getName() + "] [" + event.getId() + "]"); } return AsyncUtils.done((Event)jsonMapper.convertValue(data, EventVO.class)); } }); } @Override public void close() { open = false; } @Override public String getUri() { return uri; } @Override public boolean isOpen() { return open; } }
package bisq.network.p2p.network; import bisq.common.UserThread; import bisq.common.proto.network.NetworkEnvelope; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.LongProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleLongProperty; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import lombok.extern.slf4j.Slf4j; /** * Network statistics per connection. As we are also interested in total network statistics * we use static properties to get traffic of all connections combined. */ @Slf4j public class Statistic { // Static private final static long startTime = System.currentTimeMillis(); private final static LongProperty totalSentBytes = new SimpleLongProperty(0); private final static LongProperty totalReceivedBytes = new SimpleLongProperty(0); private final static Map<String, Integer> totalReceivedMessages = new ConcurrentHashMap<>(); private final static Map<String, Integer> totalSentMessages = new ConcurrentHashMap<>(); private final static Map<String, Integer> totalReceivedMessagesLastSec = new ConcurrentHashMap<>(); private final static Map<String, Integer> totalSentMessagesLastSec = new ConcurrentHashMap<>(); private final static LongProperty numTotalSentMessages = new SimpleLongProperty(0); private final static LongProperty numTotalSentMessagesLastSec = new SimpleLongProperty(0); private final static DoubleProperty numTotalSentMessagesPerSec = new SimpleDoubleProperty(0); private final static LongProperty numTotalReceivedMessages = new SimpleLongProperty(0); private final static LongProperty numTotalReceivedMessagesLastSec = new SimpleLongProperty(0); private final static DoubleProperty numTotalReceivedMessagesPerSec = new SimpleDoubleProperty(0); private static String totalSentMessagesLastSecString; private static String totalReceivedMessagesLastSecString; static { UserThread.runPeriodically(() -> { numTotalSentMessages.set(totalSentMessages.values().stream().mapToInt(Integer::intValue).sum()); numTotalSentMessagesLastSec.set(totalSentMessagesLastSec.values().stream().mapToInt(Integer::intValue).sum()); numTotalReceivedMessages.set(totalReceivedMessages.values().stream().mapToInt(Integer::intValue).sum()); numTotalReceivedMessagesLastSec.set(totalReceivedMessagesLastSec.values().stream().mapToInt(Integer::intValue).sum()); long passed = (System.currentTimeMillis() - startTime) / 1000; numTotalSentMessagesPerSec.set(((double) numTotalSentMessages.get()) / passed); numTotalReceivedMessagesPerSec.set(((double) numTotalReceivedMessages.get()) / passed); // We keep totalSentMessagesPerSec in a string so it is available at logging (totalSentMessagesPerSec is reset) totalSentMessagesLastSecString = totalSentMessagesLastSec.toString(); totalReceivedMessagesLastSecString = totalReceivedMessagesLastSec.toString(); // We do not clear the map as the totalSentMessagesPerSec is not thread safe and clearing could lead to null pointers totalSentMessagesLastSec.entrySet().forEach(e -> e.setValue(0)); totalReceivedMessagesLastSec.entrySet().forEach(e -> e.setValue(0)); }, 1); // We log statistics every minute UserThread.runPeriodically(() -> { log.info("Network statistics:\n" + "Bytes sent: {} kb;\n" + "Number of sent messages/Sent messages: {} / {};\n" + "Number of sent messages of last sec/Sent messages of last sec: {} / {};\n" + "Bytes received: {} kb\n" + "Number of received messages/Received messages: {} / {};\n" + "Number of received messages of last sec/Received messages of last sec: {} / {};", totalSentBytes.get() / 1024d, numTotalSentMessages.get(), totalSentMessages, numTotalSentMessagesLastSec.get(), totalSentMessagesLastSecString, totalReceivedBytes.get() / 1024d, numTotalReceivedMessages.get(), totalReceivedMessages, numTotalReceivedMessagesLastSec.get(), totalReceivedMessagesLastSecString); }, 60); } public static LongProperty totalSentBytesProperty() { return totalSentBytes; } public static LongProperty totalReceivedBytesProperty() { return totalReceivedBytes; } public static LongProperty numTotalSentMessagesProperty() { return numTotalSentMessages; } public static LongProperty numTotalSentMessagesLastSecProperty() { return numTotalSentMessagesLastSec; } public static DoubleProperty numTotalSentMessagesPerSecProperty() { return numTotalSentMessagesPerSec; } public static LongProperty numTotalReceivedMessagesProperty() { return numTotalReceivedMessages; } public static LongProperty numTotalReceivedMessagesLastSecProperty() { return numTotalReceivedMessagesLastSec; } public static DoubleProperty numTotalReceivedMessagesPerSecProperty() { return numTotalReceivedMessagesPerSec; } // Instance fields private final Date creationDate; private long lastActivityTimestamp = System.currentTimeMillis(); private final LongProperty sentBytes = new SimpleLongProperty(0); private final LongProperty receivedBytes = new SimpleLongProperty(0); private final Map<String, Integer> receivedMessages = new ConcurrentHashMap<>(); private final Map<String, Integer> sentMessages = new ConcurrentHashMap<>(); private final IntegerProperty roundTripTime = new SimpleIntegerProperty(0); // Constructor Statistic() { creationDate = new Date(); } // Update, increment void updateLastActivityTimestamp() { UserThread.execute(() -> lastActivityTimestamp = System.currentTimeMillis()); } void addSentBytes(int value) { UserThread.execute(() -> { sentBytes.set(sentBytes.get() + value); totalSentBytes.set(totalSentBytes.get() + value); }); } void addReceivedBytes(int value) { UserThread.execute(() -> { receivedBytes.set(receivedBytes.get() + value); totalReceivedBytes.set(totalReceivedBytes.get() + value); }); } // TODO would need msg inspection to get useful information... void addReceivedMessage(NetworkEnvelope networkEnvelope) { String messageClassName = networkEnvelope.getClass().getSimpleName(); int counter = 1; if (receivedMessages.containsKey(messageClassName)) { counter = receivedMessages.get(messageClassName) + 1; } receivedMessages.put(messageClassName, counter); counter = 1; if (totalReceivedMessages.containsKey(messageClassName)) { counter = totalReceivedMessages.get(messageClassName) + 1; } totalReceivedMessages.put(messageClassName, counter); counter = 1; if (totalReceivedMessagesLastSec.containsKey(messageClassName)) { counter = totalReceivedMessagesLastSec.get(messageClassName) + 1; } totalReceivedMessagesLastSec.put(messageClassName, counter); } void addSentMessage(NetworkEnvelope networkEnvelope) { String messageClassName = networkEnvelope.getClass().getSimpleName(); int counter = 1; if (sentMessages.containsKey(messageClassName)) { counter = sentMessages.get(messageClassName) + 1; } sentMessages.put(messageClassName, counter); counter = 1; if (totalSentMessages.containsKey(messageClassName)) { counter = totalSentMessages.get(messageClassName) + 1; } totalSentMessages.put(messageClassName, counter); counter = 1; if (totalSentMessagesLastSec.containsKey(messageClassName)) { counter = totalSentMessagesLastSec.get(messageClassName) + 1; } totalSentMessagesLastSec.put(messageClassName, counter); } public void setRoundTripTime(int roundTripTime) { this.roundTripTime.set(roundTripTime); } // Getters public long getLastActivityTimestamp() { return lastActivityTimestamp; } public long getLastActivityAge() { return System.currentTimeMillis() - lastActivityTimestamp; } public long getSentBytes() { return sentBytes.get(); } public LongProperty sentBytesProperty() { return sentBytes; } public long getReceivedBytes() { return receivedBytes.get(); } public LongProperty receivedBytesProperty() { return receivedBytes; } public Date getCreationDate() { return creationDate; } public IntegerProperty roundTripTimeProperty() { return roundTripTime; } @Override public String toString() { return "Statistic{" + "\n creationDate=" + creationDate + ",\n lastActivityTimestamp=" + lastActivityTimestamp + ",\n sentBytes=" + sentBytes + ",\n receivedBytes=" + receivedBytes + ",\n receivedMessages=" + receivedMessages + ",\n sentMessages=" + sentMessages + ",\n roundTripTime=" + roundTripTime + "\n}"; } }
package ro.isdc.wro.http; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.WroRuntimeException; import ro.isdc.wro.config.ConfigurationContext; import ro.isdc.wro.config.Context; import ro.isdc.wro.config.WroConfigurationChangeListener; import ro.isdc.wro.config.jmx.WroConfiguration; import ro.isdc.wro.manager.CacheChangeCallbackAware; import ro.isdc.wro.manager.WroManagerFactory; import ro.isdc.wro.manager.factory.ServletContextAwareWroManagerFactory; import ro.isdc.wro.util.WroUtil; public class WroFilter implements Filter { /** * Logger. */ private static final Logger LOG = LoggerFactory.getLogger(WroFilter.class); /** * The parameter used to specify headers to put into the response, used mostly for caching. */ static final String PARAM_HEADER = "header"; /** * The name of the context parameter that specifies wroManager factory class */ static final String PARAM_MANAGER_FACTORY = "managerFactoryClassName"; /** * Configuration Mode (DEVELOPMENT or DEPLOYMENT) By default DEVELOPMENT mode is used. */ static final String PARAM_CONFIGURATION = "configuration"; /** * Deployment configuration option. If false, the DEVELOPMENT (or DEBUG) is assumed. */ static final String PARAM_VALUE_DEPLOYMENT = "DEPLOYMENT"; /** * Gzip resources configuration option. */ static final String PARAM_GZIP_RESOURCES = "gzipResources"; /** * Parameter containing an integer value for specifying how often (in seconds) the cache should be refreshed. */ static final String PARAM_CACHE_UPDATE_PERIOD = "cacheUpdatePeriod"; /** * Parameter containing an integer value for specifying how often (in seconds) the model should be refreshed. */ static final String PARAM_MODEL_UPDATE_PERIOD = "modelUpdatePeriod"; /** * Parameter allowing to turn jmx on or off. */ static final String PARAM_JMX_ENABLED = "jmxEnabled"; /** * Filter config. */ private FilterConfig filterConfig; /** * WroManagerFactory. The brain of the optimizer. */ private WroManagerFactory wroManagerFactory; private WroConfiguration configuration; /** * Flag for enable/disable jmx. By default this value is true. */ private boolean jmxEnabled = true; /** * Map containing header values used to control caching. The keys from this values are trimmed and lower-cased when * put, in order to avoid duplicate keys. This is done, because according to RFC 2616 Message Headers field names are * case-insensitive. */ @SuppressWarnings("serial") private final Map<String, String> headersMap = new LinkedHashMap<String, String>() { @Override public String put(final String key, final String value) { return super.put(key.trim().toLowerCase(), value); } public String get(final Object key) { return super.get(((String) key).toLowerCase()); } }; /** * {@inheritDoc} */ public final void init(final FilterConfig config) throws ServletException { this.filterConfig = config; initWroManagerFactory(); initHeaderValues(); doInit(config); initJMX(); } /** * Initialize {@link WroManagerFactory}. */ private void initWroManagerFactory() { this.wroManagerFactory = getWroManagerFactory(); if (wroManagerFactory instanceof CacheChangeCallbackAware) { ((CacheChangeCallbackAware)wroManagerFactory).registerCallback(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { //update header values initHeaderValues(); } }); } } /** * Expose MBean to tell JMX infrastructure about our MBean. */ private void initJMX() throws ServletException { try { // treat null as true //TODO do not use BooleanUtils -> create your utility method jmxEnabled = BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBooleanObject(filterConfig.getInitParameter(PARAM_JMX_ENABLED)), true); configuration = newConfiguration(); ConfigurationContext.get().setConfig(configuration); LOG.debug("jmxEnabled: " + jmxEnabled); LOG.debug("wro4j configuration: " + configuration); if (jmxEnabled) { registerChangeListeners(); final MBeanServer mbeanServer = getMBeanServer(); final ObjectName name = new ObjectName(WroConfiguration.getObjectName()); if (!mbeanServer.isRegistered(name)) { mbeanServer.registerMBean(configuration, name); } } } catch (final JMException e) { LOG.error("Exception occured while registering MBean", e); } } /** * Override this method if you want to provide a different MBeanServer. * * @return {@link MBeanServer} to use for JMX. */ protected MBeanServer getMBeanServer() { return ManagementFactory.getPlatformMBeanServer(); } /** * Register property change listeners. */ private void registerChangeListeners() { configuration.registerCacheUpdatePeriodChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent event) { // reset cache headers when any property is changed in order to avoid browser caching (using ETAG header) initHeaderValues(); if (wroManagerFactory instanceof WroConfigurationChangeListener) { ((WroConfigurationChangeListener)wroManagerFactory).onCachePeriodChanged(); } } }); configuration.registerModelUpdatePeriodChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent event) { initHeaderValues(); if (wroManagerFactory instanceof WroConfigurationChangeListener) { ((WroConfigurationChangeListener)wroManagerFactory).onModelPeriodChanged(); } } }); } /** * Extracts long value from provided init param name configuration. */ private long getUpdatePeriodByName(final String paramName) { final String valueAsString = filterConfig.getInitParameter(paramName); if (valueAsString == null) { return 0; } try { return Long.valueOf(valueAsString); } catch (final NumberFormatException e) { throw new WroRuntimeException(paramName + " init-param must be a number, but was: " + valueAsString); } } /** * @return {@link WroConfiguration} configured object with default values set. */ private WroConfiguration newConfiguration() { final WroConfiguration config = new WroConfiguration(); final String gzipParam = filterConfig.getInitParameter(PARAM_GZIP_RESOURCES); final boolean gzipResources = gzipParam == null ? true : Boolean.valueOf(gzipParam); config.setGzipEnabled(gzipResources); boolean debug = true; final String configParam = filterConfig.getInitParameter(PARAM_CONFIGURATION); if (configParam != null) { if (PARAM_VALUE_DEPLOYMENT.equalsIgnoreCase(configParam)) { debug = false; } } config.setDebug(debug); config.setCacheUpdatePeriod(getUpdatePeriodByName(PARAM_CACHE_UPDATE_PERIOD)); config.setModelUpdatePeriod(getUpdatePeriodByName(PARAM_MODEL_UPDATE_PERIOD)); return config; } /** * Initialize header values. */ private void initHeaderValues() { // put defaults final Long timestamp = new Date().getTime(); final Calendar cal = Calendar.getInstance(); cal.roll(Calendar.YEAR, 10); headersMap.put(HttpHeader.CACHE_CONTROL.toString(), "public, max-age=315360000, post-check=315360000, pre-check=315360000"); headersMap.put(HttpHeader.ETAG.toString(), Long.toHexString(timestamp)); headersMap.put(HttpHeader.LAST_MODIFIED.toString(), WroUtil.toDateAsString(timestamp)); headersMap.put(HttpHeader.EXPIRES.toString(), WroUtil.toDateAsString(cal.getTimeInMillis())); final String headerParam = filterConfig.getInitParameter(PARAM_HEADER); if (headerParam != null) { try { if (headerParam.contains("|")) { final String[] headers = headerParam.split("[|]"); for (final String header : headers) { parseHeader(header); } } else { parseHeader(headerParam); } } catch (final Exception e) { throw new WroRuntimeException("Invalid header init-param value: " + headerParam + ". A correct value should have the following format: " + "<HEADER_NAME1>: <VALUE1> | <HEADER_NAME2>: <VALUE2>. " + "Ex: <look like this: " + "Expires: Thu, 15 Apr 2010 20:00:00 GMT | ETag: 123456789", e); } } LOG.info("Header Values :" + headersMap); } /** * Parse header value & puts the found values in headersMap field. * * @param header value to parse. */ private void parseHeader(final String header) { final String headerName = header.substring(0, header.indexOf(":")); if (!headersMap.containsKey(headerName)) { headersMap.put(headerName, header.substring(header.indexOf(":") + 1)); } } /** * Custom filter initialization - can be used for extended classes. * * @see Filter#init(FilterConfig). */ protected void doInit(final FilterConfig config) throws ServletException {} /** * {@inheritDoc} */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest)req; final HttpServletResponse response = (HttpServletResponse)res; try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig)); if (!ConfigurationContext.get().getConfig().isDebug()) { final String ifNoneMatch = request.getHeader(HttpHeader.IF_NONE_MATCH.toString()); final String etagValue = headersMap.get(HttpHeader.ETAG.toString()); LOG.info("Request ETag: " + ifNoneMatch); LOG.info("Resource ETag: " + etagValue); if (etagValue != null && etagValue.equals(ifNoneMatch)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } setResponseHeaders(response); // process the uri using manager wroManagerFactory.getInstance().process(request, response); // remove context from the current thread local. Context.unset(); } catch (final RuntimeException e) { onRuntimeException(e, response); } } /** * Invoked when a {@link RuntimeException} is thrown. Allows custom exception handling. By default the exception is thrown further. * * @param e {@link RuntimeException}. */ protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response) { throw e; } /** * Method called for each request and responsible for setting response headers, used mostly for cache control. * Override this method if you want to change the way headers are set.<br> * * @param response {@link HttpServletResponse} object. */ protected void setResponseHeaders(final HttpServletResponse response) { if (!ConfigurationContext.get().getConfig().isDebug()) { // Force resource caching as best as possible for (final Map.Entry<String, String> entry : headersMap.entrySet()) { response.setHeader(entry.getKey(), entry.getValue()); } } } /** * Factory method for {@link WroManagerFactory}. Override this method, in order to change the way filter use factory. * * @return {@link WroManagerFactory} object. */ protected WroManagerFactory getWroManagerFactory() { final String appFactoryClassName = filterConfig.getInitParameter(PARAM_MANAGER_FACTORY); if (appFactoryClassName == null) { // If no context param was specified we return the default factory return new ServletContextAwareWroManagerFactory(); } else { // Try to find the specified factory class Class<?> factoryClass; try { factoryClass = Thread.currentThread().getContextClassLoader().loadClass(appFactoryClassName); // Instantiate the factory return (WroManagerFactory)factoryClass.newInstance(); } catch (final Exception e) { throw new WroRuntimeException("Exception while loading WroManagerFactory class", e); } } } /** * This exists only for testing purposes. * * @return the applicationSettings */ protected final WroConfiguration getConfiguration() { return this.configuration; } /** * {@inheritDoc} */ public void destroy() { wroManagerFactory.destroy(); } }
package com.heroku.api.json; import java.util.Iterator; import java.util.ServiceLoader; public class Json { private static volatile boolean initialized = false; private static JsonParser parser; private static Object lock = new Object(); public static JsonParser getJsonParser() { if (parser != null) return parser; if (!initialized) { synchronized (lock) { if (!initialized) { ServiceLoader<JsonParser> loader = ServiceLoader.load(JsonParser.class); Iterator<JsonParser> iterator = loader.iterator(); if (iterator.hasNext()) { parser = iterator.next(); } else { throw new IllegalStateException("Unable to load a JSONProvider, please make sure you have a com.heroku.api.json.JSONParser implementation" + "on your classpath that can be discovered and loaded via java.util.ServiceLoader"); } } } } return parser; } }
package net.xisberto.work_schedule; import java.util.Calendar; import net.xisberto.work_schedule.Settings.Period; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.widget.TimePicker; import com.actionbarsherlock.app.SherlockDialogFragment; public class TimePickerFragment extends SherlockDialogFragment implements OnClickListener { private TimePicker timePicker; private Dialog dialog; private OnTimePickerSetListener listener; public static TimePickerFragment newInstance(int callerId) { TimePickerFragment dialog_fragment = new TimePickerFragment(); Bundle args = new Bundle(); args.putInt("callerId", callerId); dialog_fragment.setArguments(args); return dialog_fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (!(getActivity() instanceof OnTimePickerSetListener)) { throw new ClassCastException( "Activity must implement OnTimePickerSetListener"); } else { listener = (OnTimePickerSetListener)getActivity(); } final Calendar c = Calendar.getInstance(); int hourOfDay = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); LayoutInflater inflater = (LayoutInflater) getActivity() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.time_picker_dialog, null); timePicker = (TimePicker) view.findViewById(R.id.timePicker); timePicker.setIs24HourView(DateFormat.is24HourFormat(getActivity())); timePicker.setCurrentHour(hourOfDay); timePicker.setCurrentMinute(minute); int callerId = getArguments().getInt("callerId"); Period period = Period.getFromPrefId(callerId); // Create a new instance of TimePickerDialog and return it AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setView(view) .setTitle(getResources().getString(period.label_id)) .setPositiveButton(android.R.string.ok, this) .setNegativeButton(android.R.string.cancel, this); dialog = builder.create(); return dialog; } @Override public void onClick(DialogInterface dialog, int which) { timePicker.clearFocus(); switch (which) { case AlertDialog.BUTTON_POSITIVE: int callerId = getArguments().getInt("callerId"); listener.onTimeSet( timePicker.getCurrentHour(), timePicker.getCurrentMinute(), callerId); break; case AlertDialog.BUTTON_NEGATIVE: default: break; } } public interface OnTimePickerSetListener { public void onTimeSet(int hour, int minute, int callerId); } }
package odontosoft.controller; import java.io.IOException; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import odontosoft.model.dao.FuncionarioDAO; import odontosoft.model.database.ConexaoBanco; import odontosoft.model.domain.Funcionario; import odontosoft.model.domain.Usuario; /** * FXML Controller class * * @author eduardo */ public class TelaPrincipalController implements Initializable { @FXML private Label lblNome,lblHorario; @FXML private ImageView imgViewSair; @FXML private BorderPane borderPane; @FXML private HBox btnMenuLateralFuncionarios; //0-Recepcionista 1-Dentista 2-Gerente private Funcionario funcionario; private Usuario user; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { btnMenuLateralPaginaInicialClicked(); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Platform.runLater(() -> lblHorario.setText(getHora())); } }, 0, 1000); } public Usuario getUser() { return user; } public void setUser(Usuario user) { this.user = user; ConexaoBanco conexao = new ConexaoBanco(); Funcionario f = new FuncionarioDAO(conexao).buscaPorId(user.getIdFuncionario()); if(f == null) System.out.println("deu null"); lblNome.setText(f.getNome()); this.funcionario = f; if(!f.isGerente()){ btnMenuLateralFuncionarios.setVisible(false); } } @FXML public void imgViewSairMouseEntered(){ Image image = new Image(getClass().getResourceAsStream("/odontosoft/view/img/iconSairHover.png")); imgViewSair.setImage(image); } @FXML public void imgViewSairMouseExited(){ Image image = new Image(getClass().getResourceAsStream("/odontosoft/view/img/iconSairPadrao.png")); imgViewSair.setImage(image); } @FXML public void imgViewSairMouseClicked(){ System.exit(0); } @FXML public void btnMenuLateralPaginaInicialClicked(){ try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLPaginaInicial.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML public void btnMenuLateralPacientesClicked(){ try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLPacientes.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML public void btnMenuLateralAgendaClicked(){ try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLTelaAgenda.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML public void btnMenuLateralFuncionariosClicked(){ try{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLFuncionarios.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML public void btnMenuLateralProcedimentosClicked(){ try{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLTelaProcedimentos.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML public void btnMenuLateralEstatisticasClicked(){ try{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/odontosoft/view/FXMLTelaEstatisticas.fxml")); borderPane.setCenter(fxmlLoader.load()); } catch (IOException ex) { Logger.getLogger(TelaPrincipalController.class.getName()).log(Level.SEVERE, null, ex); } } public String getHora(){ Calendar cal = new GregorianCalendar(); int hora = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); if (hora < 10) return "0" + hora + ":" + min; if (min < 10) return hora + ":" + "0" + min; if (hora < 10 && min < 10) return "0" + hora + ":" + "0" + min; return hora + ":" + min; } }
package edu.umd.cs.daveho.ba.bcp; import java.util.regex.*; import org.apache.bcel.Repository; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import edu.umd.cs.daveho.ba.*; /** * A PatternElement to match a method invocation. * Currently, we don't allow variables in this element (for arguments * and return value). This would be a good thing to add. * We also don't distinguish between invokevirtual, invokeinterface, * and invokespecial. * * <p> Invoke objects match by class name, method name, method signature, * and <em>mode</em>. * * <p> Names and signatures may be matched in several ways: * <ol> * <li> By an exact match. This is the default behavior. * <li> By a regular expression. If the string provided to the Invoke * constructor begins with a "/" character, the rest of the string * is treated as a regular expression. * <li> As a subclass match. This only applies to class name matches. * If the first character of a class name string is "+", then the * rest of the string is treated as the name of a base class. * Any subclass or subinterface of the named type will be accepted. * </ol> * * <p> The <em>mode</em> specifies what kind of invocations in the Invoke * element matches. It is specified as the bitwise combination of the * following values: * <ol> * <li> <code>INSTANCE</code>, which matches ordinary instance method invocations * <li> <code>STATIC</code>, which matches static method invocations * <li> <code>CONSTRUCTOR</code>, which matches object constructor invocations * </ol> * The special mode <code>ORDINARY_METHOD</code> is equivalent to <code>INSTANCE|STATIC</code>. * The special mode <code>ANY</code> is equivalent to <code>INSTANCE|STATIC|CONSTRUCTOR</code>. * * @see PatternElement * @author David Hovemeyer */ public class Invoke extends PatternElement { /** Match ordinary (non-constructor) instance invocations. */ public static final int INSTANCE = 1; /** Match static invocations. */ public static final int STATIC = 2; /** Match object constructor invocations. */ public static final int CONSTRUCTOR = 4; /** Match ordinary methods (everything except constructors). */ public static final int ORDINARY_METHOD = INSTANCE | STATIC; /** Match both static and instance invocations. */ public static final int ANY = INSTANCE | STATIC | CONSTRUCTOR; private interface StringMatcher { public boolean match(String s); } private static class ExactStringMatcher implements StringMatcher { private String value; public ExactStringMatcher(String value) { this.value = value; } public boolean match(String s) { return s.equals(value); } } private static class RegexpStringMatcher implements StringMatcher { private Pattern pattern; public RegexpStringMatcher(String re) { pattern = Pattern.compile(re); } public boolean match(String s) { return pattern.matcher(s).matches(); } } private class SubclassMatcher implements StringMatcher { private String className; public SubclassMatcher(String className) { this.className = className; } public boolean match(String s) { try { return Repository.instanceOf(s, className); } catch (ClassNotFoundException e) { lookupFailureCallback.lookupFailure(e); return false; } } } private final StringMatcher classNameMatcher; private final StringMatcher methodNameMatcher; private final StringMatcher methodSigMatcher; private final int mode; private final RepositoryLookupFailureCallback lookupFailureCallback; /** * Constructor. * @param className the class name of the method; may be specified exactly, * as a regexp, or as a subtype match * @param methodName the name of the method; may be specified exactly or as a regexp * @param methodSig the signature of the method; may be specified exactly or as a regexp * @param mode the mode of invocation */ public Invoke(String className, String methodName, String methodSig, int mode, RepositoryLookupFailureCallback lookupFailureCallback) { this.classNameMatcher = createClassMatcher(className); this.methodNameMatcher = createMatcher(methodName); this.methodSigMatcher = createMatcher(methodSig); this.mode = mode; this.lookupFailureCallback = lookupFailureCallback; } private StringMatcher createClassMatcher(String s) { return s.startsWith("+") ? new SubclassMatcher(s.substring(1)) : createMatcher(s); } private StringMatcher createMatcher(String s) { return s.startsWith("/") ? (StringMatcher) new RegexpStringMatcher(s.substring(1)) : (StringMatcher) new ExactStringMatcher(s); } public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException { // See if the instruction is an InvokeInstruction Instruction ins = handle.getInstruction(); if (!(ins instanceof InvokeInstruction)) return null; InvokeInstruction inv = (InvokeInstruction) ins; String methodName = inv.getMethodName(cpg); boolean isStatic = inv.getOpcode() == Constants.INVOKESTATIC; boolean isCtor = methodName.equals("<init>"); int actualMode = 0; if (isStatic) actualMode |= STATIC; if (isCtor) actualMode |= CONSTRUCTOR; if (!isStatic && !isCtor) actualMode |= INSTANCE; // Intersection of actual and desired modes must be nonempty. if ((actualMode & mode) == 0) return null; // Check class name, method name, and method signature. if (!classNameMatcher.match(inv.getClassName(cpg)) || !methodNameMatcher.match(methodName) || !methodSigMatcher.match(inv.getSignature(cpg))) return null; // It's a match! return new MatchResult(this, bindingSet); } public boolean acceptBranch(Edge edge, InstructionHandle source) { return true; } public int minOccur() { return 1; } public int maxOccur() { return 1; } } // vim:ts=4
package org.innovateuk.ifs.application.terms.controller; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.service.ApplicationRestService; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/application/{applicationId}/terms-and-conditions") @PreAuthorize("hasAuthority('applicant')") @SecuredBySpring(value="Controller", description = "Only applicants are allowed to view the application terms", securedType = ApplicationTermsController.class) public class ApplicationTermsController { private ApplicationRestService applicationRestService; private CompetitionRestService competitionRestService; public ApplicationTermsController(ApplicationRestService applicationRestService, CompetitionRestService competitionRestService) { this.applicationRestService = applicationRestService; this.competitionRestService = competitionRestService; } @GetMapping public String getTerms(@PathVariable long applicationId, Model model) { ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess(); model.addAttribute("template", competition.getTermsAndConditions().getTemplate()); model.addAttribute("collaborative", application.isCollaborativeProject()); return "application/terms-and-conditions"; } }
package opendap.semantics.IRISail; import opendap.wcs.v1_1_2.*; import org.jdom.Element; import org.jdom.filter.ElementFilter; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; import org.openrdf.query.*; import org.slf4j.Logger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.ConcurrentHashMap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Vector; import org.openrdf.model.Value; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import com.ontotext.trree.owlim_ext.SailImpl; /** * A colon of LocalFileCatalog */ public class NewStaticRDFCatalog implements WcsCatalog, Runnable { private Logger log; // = LoggerFactory.getLogger(StaticRDFCatalog.class); private AtomicBoolean repositoryUpdateActive; private ReentrantReadWriteLock _repositoryLock; private XMLfromRDF buildDoc; private long _catalogLastModifiedTime; private ConcurrentHashMap<String, CoverageDescription> coverages; private ReentrantReadWriteLock _catalogLock; private Thread catalogUpdateThread; private long firstUpdateDelay; private long catalogUpdateInterval; private long timeOfLastUpdate; private boolean stopWorking = false; private Element _config; private String catalogCacheDirectory; private String owlim_storage_folder; private String resourcePath; private boolean backgroundUpdates; private boolean overrideBackgroundUpdates; private HashMap<String, Vector<String>> coverageIDServer; private boolean initialized; public NewStaticRDFCatalog() { log = org.slf4j.LoggerFactory.getLogger(this.getClass()); catalogUpdateInterval = 20 * 60 * 1000; // 20 minutes worth of milliseconds firstUpdateDelay = 5 * 1000; // 5 seconds worth of milliseconds timeOfLastUpdate = 0; stopWorking = false; _catalogLock = new ReentrantReadWriteLock(); coverages = new ConcurrentHashMap<String, CoverageDescription>(); _repositoryLock = new ReentrantReadWriteLock(); repositoryUpdateActive = new AtomicBoolean(); repositoryUpdateActive.set(false); backgroundUpdates = false; overrideBackgroundUpdates = false; buildDoc = null; _catalogLastModifiedTime = -1; _config = null; catalogCacheDirectory = "."; owlim_storage_folder = "owlim-storage"; resourcePath = "."; initialized = false; } /** * @param args Command line arguments */ public static void main(String[] args) { long startTime, endTime; double elapsedTime; NewStaticRDFCatalog catalog = new NewStaticRDFCatalog(); try { if (args.length > 0) System.out.println("arg[0]= " + args[0]); catalog.resourcePath = "."; catalog.catalogCacheDirectory = "."; String configFileName; configFileName = "file:///data/haibo/workspace/ioos/wcs_service.xml"; if (args.length > 0) configFileName = args[0]; catalog.log.debug("main() using config file: " + configFileName); Element olfsConfig = opendap.xml.Util.getDocumentRoot(configFileName); catalog._config = (Element) olfsConfig.getDescendants(new ElementFilter("WcsCatalog")).next(); catalog.overrideBackgroundUpdates = true; startTime = new Date().getTime(); catalog.init(catalog._config, catalog.catalogCacheDirectory, catalog.resourcePath); endTime = new Date().getTime(); elapsedTime = (endTime - startTime) / 1000.0; catalog.log.debug("Completed catalog update in " + elapsedTime + " seconds."); catalog.log.debug(" catalog.log.debug(" catalog.log.debug(" } catch (Exception e) { catalog.log.error("Caught " + e.getClass().getName() + " in main(): " + e.getMessage()); e.printStackTrace(); } } public void init(Element config, String defaultCacheDirectory, String defaultResourcePath) throws Exception { if (initialized) return; backgroundUpdates = false; _config = config; processConfig(_config, defaultCacheDirectory, defaultResourcePath); loadWcsCatalogFromRepository(); if (backgroundUpdates && !overrideBackgroundUpdates) { catalogUpdateThread = new Thread(this); catalogUpdateThread.start(); } else { updateCatalog(); } initialized = true; } public void updateCatalog() throws RepositoryException, InterruptedException { IRISailRepository repository = setupRepository(); try { log.debug("updateRepository(): Getting starting points (RDF imports)."); Vector<String> startingPoints = getRdfImports(_config); log.info("updateCatalog(): Updating Repository..."); if (updateRepository(repository, startingPoints)) { log.info("updateCatalog(): Extracting CoverageDescriptions from the Repository..."); extractCoverageDescrptionsFromRepository(repository); String filename = catalogCacheDirectory + "coverageXMLfromRDF.xml"; log.info("updateCatalog(): Dumping CoverageDescriptions Document to: " + filename); dumpCoverageDescriptionsDocument(filename); log.info("updateCatalog(): Updating catalog cache...."); updateCatalogCache(repository); } else { log.info("updateCatalog(): The repository was unchanged, nothing else to do."); } } finally { shutdownRepository(repository); } } public boolean updateRepository(IRISailRepository repository, Vector<String> startingPoints) throws RepositoryException, InterruptedException { boolean repositoryChanged = RdfPersistence.updateSemanticRepository(repository, startingPoints); String filename = catalogCacheDirectory + "owlimHorstRepository.nt"; log.debug("updateRepository(): Dumping Semantic Repository to: " + filename); RepositoryUtility.dumpRepository(repository, filename); filename = catalogCacheDirectory + "owlimHorstRepository.trig"; log.debug("updateRepository(): Dumping Semantic Repository to: " + filename); RepositoryUtility.dumpRepository(repository, filename); return repositoryChanged; } public void loadWcsCatalogFromRepository() throws InterruptedException, RepositoryException { long startTime, endTime; double elapsedTime; log.info(" log.info(" log.info("Loading WCS Catalog from Semantic Repository."); startTime = new Date().getTime(); IRISailRepository repository = setupRepository(); try { extractCoverageDescrptionsFromRepository(repository); updateCatalogCache(repository); } finally { shutdownRepository(repository); } endTime = new Date().getTime(); elapsedTime = (endTime - startTime) / 1000.0; log.info("WCS Catalog loaded from the Semantic Repository. Loaded in " + elapsedTime + " seconds."); log.info(" log.info(" } public String getDataAccessUrl(String coverageID) { return coverageIDServer.get(coverageID).firstElement(); } private void processConfig(Element config, String defaultCacheDirectory, String defaultResourcePath) { Element e; File file; catalogCacheDirectory = defaultCacheDirectory; e = config.getChild("CacheDirectory"); if (e != null) catalogCacheDirectory = e.getTextTrim(); if (catalogCacheDirectory != null && catalogCacheDirectory.length() > 0 && !catalogCacheDirectory.endsWith("/")) catalogCacheDirectory += "/"; file = new File(catalogCacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + catalogCacheDirectory); if (!catalogCacheDirectory.equals(defaultCacheDirectory)) { file = new File(defaultCacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + defaultCacheDirectory); log.error("Process probably doomed..."); } } } else { log.error("Process probably doomed..."); } } } log.info("Using catalogCacheDirectory: " + catalogCacheDirectory); resourcePath = defaultResourcePath; e = config.getChild("ResourcePath"); if (e != null) resourcePath = e.getTextTrim(); if (resourcePath != null && resourcePath.length() > 0 && !resourcePath.endsWith("/")) resourcePath += "/"; file = new File(this.resourcePath); if (!file.exists()) { log.error("Unable to locate resource directory: " + resourcePath); file = new File(defaultResourcePath); if (!file.exists()) { log.error("Unable to locate default resource directory: " + defaultResourcePath); log.error("Process probably doomed..."); } } log.info("Using resourcePath: " + resourcePath); e = config.getChild("useUpdateCatalogThread"); if (e != null) { backgroundUpdates = true; String s = e.getAttributeValue("updateInterval"); if (s != null) { catalogUpdateInterval = Long.parseLong(s) * 1000; } s = e.getAttributeValue("firstUpdateDelay"); if (s != null) { firstUpdateDelay = Long.parseLong(s) * 1000; } } log.info("backgroundUpdates: " + backgroundUpdates); log.info("Catalog update interval: " + catalogUpdateInterval + "ms"); log.info("First update delay: " + firstUpdateDelay + "ms"); } private void shutdownRepository(IRISailRepository repository) throws RepositoryException { log.debug("shutdownRepository)(): Shutting down Repository..."); repository.shutDown(); log.debug("shutdownRepository(): Repository shutdown complete."); } private IRISailRepository setupRepository() throws RepositoryException, InterruptedException { log.info("Setting up Semantic Repository."); //OWLIM Sail Repository (inferencing makes this somewhat slow) SailImpl owlimSail = new com.ontotext.trree.owlim_ext.SailImpl(); IRISailRepository repository = new IRISailRepository(owlimSail, resourcePath, catalogCacheDirectory); //owlim inferencing log.info("Configuring Semantic Repository."); File storageDir = new File(catalogCacheDirectory); //define local copy of repository owlimSail.setDataDir(storageDir); log.debug("Semantic Repository Data directory set to: " + catalogCacheDirectory); // prepare config owlimSail.setParameter("storage-folder", owlim_storage_folder); log.debug("Semantic Repository 'storage-folder' set to: " + owlim_storage_folder); // Choose the operational ruleset String ruleset; ruleset = "owl-horst"; //ruleset = "owl-max"; owlimSail.setParameter("ruleset", ruleset); //owlimSail.setParameter("ruleset", "owl-max"); //owlimSail.setParameter("partialRDFs", "false"); log.debug("Semantic Repository 'ruleset' set to: " + ruleset); log.info("Intializing Semantic Repository."); // Initialize repository repository.startup(); //needed log.info("Adding InternalStartingPoint to repository."); RepositoryUtility.addInternalStartingPoint(repository); log.info("Semantic Repository Ready."); if (Thread.currentThread().isInterrupted()) throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); return repository; } private void extractCoverageDescrptionsFromRepository(IRISailRepository repository) throws RepositoryException { RepositoryConnection con = repository.getConnection(); log.info("Repository connection has been opened."); extractCoverageDescrptionsFromRepository(con); log.info("Closing repository connection."); con.close(); //close connection first } private void extractCoverageDescrptionsFromRepository(RepositoryConnection con) { //retrieve XML from the RDF store. log.info("extractCoverageDescrptionsFromRepository() - Extracting CoverageDescriptions from repository."); log.info("extractCoverageDescrptionsFromRepository() - Building CoverageDescription XML from repository."); buildDoc = new XMLfromRDF(con, "CoverageDescriptions", "http://www.opengis.net/wcs/1.1#CoverageDescription"); buildDoc.getXMLfromRDF("http://www.opengis.net/wcs/1.1#CoverageDescription"); //build a JDOM doc by querying against the RDF store // Next we update the cached maps of datasetUrl/serverIDs and datasetUrl/wcsID // held in the CoverageIDGenerator so that subsequent calls to the CoverageIdGenerator // create new IDs correctly. try { log.info("extractCoverageDescrptionsFromRepository() - Updating CoverageIdGenerator Id Caches."); HashMap<String, Vector<String>> coverageIdToServerMap = getCoverageIDServerURL(con); CoverageIdGenerator.updateIdCaches(coverageIdToServerMap); } catch (RepositoryException e) { log.error("extractCoverageDescrptionsFromRepository(): Caught RepositoryException. msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("extractCoverageDescrptionsFromRepository(): Caught MalformedQueryException. msg: " + e.getMessage()); } catch (QueryEvaluationException e) { log.error("extractCoverageDescrptionsFromRepository(): Caught QueryEvaluationException. msg: " + e.getMessage()); } } private void dumpCoverageDescriptionsDocument(String filename) { //print out the XML XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); try { FileOutputStream fos = new FileOutputStream(filename); outputter.output(buildDoc.getDoc(), fos); } catch (IOException e1) { e1.printStackTrace(); } } public void destroy() { log.debug("destroy(): Attempting to aquire WriteLock from _catalogLock and _repositoryLock."); ReentrantReadWriteLock.WriteLock catLock = _catalogLock.writeLock(); ReentrantReadWriteLock.WriteLock reposLock = _repositoryLock.writeLock(); try { catLock.lock(); reposLock.lock(); log.debug("destroy(): WriteLocks Aquired."); setStopFlag(true); if (catalogUpdateThread != null) { log.debug("destroy() Current thread '" + Thread.currentThread().getName() + "' Interrupting catalogUpdateThread '" + catalogUpdateThread + "'"); catalogUpdateThread.interrupt(); log.debug("destroy(): catalogUpdateThread '" + catalogUpdateThread + "' interrupt() called."); } } finally { catLock.unlock(); reposLock.unlock(); log.debug("destroy(): Released WriteLock for _catalogLock and _repositoryLock."); log.debug("destroy(): Complete."); } } private Vector<String> getRdfImports(Element config) { Vector<String> rdfImports = new Vector<String>(); Element e; String s; /** * Load individual dataset references */ Iterator i = config.getChildren("dataset").iterator(); String datasetURL; while (i.hasNext()) { e = (Element) i.next(); datasetURL = e.getTextNormalize(); if (!datasetURL.endsWith(".rdf")) { if (datasetURL.endsWith(".ddx") | datasetURL.endsWith(".dds") | datasetURL.endsWith(".das") ) { datasetURL = datasetURL.substring(0, datasetURL.lastIndexOf(".")); } datasetURL += ".rdf"; } rdfImports.add(datasetURL); log.info("Added dataset reference " + datasetURL + " to RDF imports list."); log.debug("<wcs:Identifier>" + CoverageIdGenerator.getWcsIdString(datasetURL) + "</wcs:Identifier>"); } /** * Load THREDDS Catalog references. */ i = config.getChildren("ThreddsCatalog").iterator(); String catalogURL; boolean recurse; while (i.hasNext()) { e = (Element) i.next(); catalogURL = e.getTextNormalize(); recurse = false; s = e.getAttributeValue("recurse"); if (s != null && s.equalsIgnoreCase("true")) recurse = true; ThreddsCatalogUtil tcu = null; try { // Passing false means no caching but also no exception. // Maybe there's a better way to code the TCU ctor? tcu = new ThreddsCatalogUtil(); } catch (Exception e1) { log.debug("ThreddsCatalogUtil exception: " + e1.getMessage()); } Vector<String> datasetURLs = tcu.getDataAccessURLs(catalogURL, ThreddsCatalogUtil.SERVICE.OPeNDAP, recurse); for (String dataset : datasetURLs) { dataset += ".rdf"; rdfImports.add(dataset); log.info("Added dataset reference " + dataset + " to RDF imports list."); } } /** * Load RDF Imports */ i = config.getChildren("RdfImport").iterator(); while (i.hasNext()) { e = (Element) i.next(); s = e.getTextNormalize(); rdfImports.add(s); log.info("Added reference " + s + " to RDF imports list."); } return rdfImports; } private void ingestCatalog(IRISailRepository repository) throws Exception { log.info("Ingesting catalog from CoverageDescriptions Document built by the XMLFromRDF object..."); HashMap<String, String> lmtfc; String contextLMT; String coverageID; Element idElement; DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); long lastModifiedTime; String dapVariableID; RepositoryConnection con = null; List<Element> coverageDescriptions = buildDoc.getDoc().getRootElement().getChildren(); try { con = repository.getConnection(); lmtfc = RepositoryUtility.getLastModifiedTimesForContexts(con); for (Element cde : coverageDescriptions) { idElement = cde.getChild("Identifier", WCS.WCS_NS); if (idElement != null) { coverageID = idElement.getTextTrim(); contextLMT = lmtfc.get(coverageID); String dateTime = contextLMT.substring(0, 10) + " " + contextLMT.substring(11, 19) + " +0000"; log.debug("CoverageDescription '" + coverageID + "' has a last modified time of " + dateTime); lastModifiedTime = sdf.parse(dateTime).getTime(); CoverageDescription coverageDescription = ingestCoverageDescription(cde, lastModifiedTime); if (_catalogLastModifiedTime < lastModifiedTime) _catalogLastModifiedTime = lastModifiedTime; if (coverageDescription != null) { for (String fieldID : coverageDescription.getFieldIDs()) { log.debug("Getting DAP Coordinate IDs for FieldID: " + fieldID); dapVariableID = getLatitudeCoordinateDapId(con, coverageID, fieldID); coverageDescription.setLatitudeCoordinateDapId(fieldID, dapVariableID); dapVariableID = getLongitudeCoordinateDapId(con, coverageID, fieldID); coverageDescription.setLongitudeCoordinateDapId(fieldID, dapVariableID); dapVariableID = getElevationCoordinateDapId(con, coverageID, fieldID); coverageDescription.setElevationCoordinateDapId(fieldID, dapVariableID); dapVariableID = getTimeCoordinateDapId(con, coverageID, fieldID); coverageDescription.setTimeCoordinateDapId(fieldID, dapVariableID); } } log.debug("Ingested CoverageDescription '" + coverageID + "'"); } } } finally { if (con != null) con.close(); } } private CoverageDescription ingestCoverageDescription(Element cde, long lastModified) { CoverageDescription cd = null; try { cd = new CoverageDescription(cde, lastModified); coverages.put(cd.getIdentifier(), cd); log.info("Ingested CoverageDescription: " + cd.getIdentifier()); } catch (WcsException e) { XMLOutputter xmlo = new XMLOutputter(Format.getCompactFormat()); String wcseElem = xmlo.outputString(e.getExceptionElement()); String cvgDesc = xmlo.outputString(cde); log.error("ingestCoverageDescription(): Failed to ingest CoverageDescription!"); log.error("ingestCoverageDescription(): WcsException: " + wcseElem + ""); log.error("ingestCoverageDescription(): Here is the XML element that failed to ingest: " + cvgDesc); } return cd; } public boolean hasCoverage(String id) { log.debug("Looking for a coverage with ID: " + id); ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.containsKey(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageDescriptionElement(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); CoverageDescription cd = coverages.get(id); if (cd == null) return null; return cd.getElement(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageDescriptionElements() throws WcsException { throw new WcsException("getCoverageDescriptionElements() method Not Implemented", WcsException.NO_APPLICABLE_CODE); } public CoverageDescription getCoverageDescription(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageSummaryElement(String id) throws WcsException { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id).getCoverageSummary(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageSummaryElements() throws WcsException { ArrayList<Element> coverageSummaries = new ArrayList<Element>(); Enumeration e; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. e = coverages.elements(); while (e.hasMoreElements()) { cd = (CoverageDescription) e.nextElement(); coverageSummaries.add(cd.getCoverageSummary()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return coverageSummaries; } public List<Element> getSupportedFormatElements() { ArrayList<Element> supportedFormats = new ArrayList<Element>(); HashMap<String, Element> uniqueFormats = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedFormatElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueFormats.put(e.getTextTrim(), e); } } i = uniqueFormats.values().iterator(); while (i.hasNext()) { supportedFormats.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedFormats; } public List<Element> getSupportedCrsElements() { ArrayList<Element> supportedCRSs = new ArrayList<Element>(); HashMap<String, Element> uniqueCRSs = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedCrsElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueCRSs.put(e.getTextTrim(), e); } } i = uniqueCRSs.values().iterator(); while (i.hasNext()) { supportedCRSs.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedCRSs; } private String getLatitudeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) { log.debug("getLatitudeCoordinateDapId(): Getting the DAP variable ID that represents the latitude coordinate for FieldID: " + fieldId); String qString = createCoordinateIdQuery("A_1D_latitude", coverageId, fieldId); String coordinateDapId = runQuery(con, qString); log.debug("getLatitudeCoordinateDapId(): '" + coordinateDapId + "' is the DAP variable ID that represents the latitude coordinate for FieldID: " + fieldId); return coordinateDapId; } private String getLongitudeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) { log.debug("getLongitudeCoordinateDapId(): Getting the DAP variable ID that represents the longitude coordinate for FieldID: " + fieldId); String qString = createCoordinateIdQuery("A_1D_longitude", coverageId, fieldId); String coordinateDapId = runQuery(con, qString); log.debug("getLongitudeCoordinateDapId(): '" + coordinateDapId + "' is the DAP variable ID that represents the longitude coordinate for FieldID: " + fieldId); return coordinateDapId; } private String getElevationCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) { log.debug("getElevationCoordinateDapId(): Getting the DAP variable ID that represents the elevation coordinate for FieldID: " + fieldId); String qString = createCoordinateIdQuery("A_elevation", coverageId, fieldId); String coordinateDapId = runQuery(con, qString); log.debug("getElevationCoordinateDapId(): '" + coordinateDapId + "' is the DAP variable ID that represents the elevation coordinate for FieldID: " + fieldId); return coordinateDapId; } private String getTimeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) { log.debug("getTimeCoordinateDapId(): Getting the DAP variable ID that represents the time coordinate for FieldID: " + fieldId); String qString = createCoordinateIdQuery("A_time", fieldId, coverageId); String coordinateDapId = runQuery(con, qString); log.debug("getTimeCoordinateDapId(): '" + coordinateDapId + "' is the DAP variable ID that represents the time coordinate for FieldID: " + fieldId); return coordinateDapId; } private String runQuery(RepositoryConnection con, String qString) { String coordinateDapId = null; try { TupleQueryResult result = null; TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, qString); result = tupleQuery.evaluate(); if (result != null && result.hasNext()) { while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("cid"); coordinateDapId = firstValue.stringValue(); } } else { log.error("No query result!"); } } catch (Exception e) { log.error("runQuery(): Query FAILED. Caught "+ e.getClass().getName()+ " Message: " + e.getMessage()); } return coordinateDapId; } private String createCoordinateIdQuery(String coordinateName, String coverageStr, String fieldStr) { String qString = "select cid,cidid " + "FROM {cover} wcs:Identifier {covid} ; wcs:Range {} wcs:Field " + "{field} wcs:Identifier {fieldid}, " + "{field} ncobj:hasCoordinate {cid} rdf:type {cfobj:A_time}; dap:localId {cidid} " + "WHERE covid= \"" + coverageStr + "\" AND fieldid=\"" + fieldStr + "\"" + " USING NAMESPACE " + "wcs=<http://www.opengis.net/wcs/1.1 "ncobj=<http://iridl.ldeo.columbia.edu/ontologies/netcdf-obj.owl "cfobj=<http://iridl.ldeo.columbia.edu/ontologies/cf-obj.owl "dap=<http://xml.opendap.org/ontologies/opendap-dap-3.2.owl log.debug("createCoordinateIdQuery: Built query string: '" + qString + "'"); return qString; } public long getLastModified() { return _catalogLastModifiedTime; } public void setStopFlag(boolean flag) { stopWorking = flag; } public void updateCatalogCache(IRISailRepository repository) throws InterruptedException { Thread thread = Thread.currentThread(); int biffCount = 0; if (!stopWorking && !thread.isInterrupted()) { ReentrantReadWriteLock.WriteLock catlock = _catalogLock.writeLock(); ReentrantReadWriteLock.ReadLock repLock = _repositoryLock.readLock(); try { repLock.lock(); catlock.lock(); log.debug("_catalogLock WriteLock Acquired."); if (!stopWorking && !thread.isInterrupted()) { coverageIDServer = getCoverageIDServerURL(repository); addSupportedFormats(buildDoc.getRootElement()); ingestCatalog(repository); timeOfLastUpdate = new Date().getTime(); log.debug("Catalog Cache updated at " + new Date(timeOfLastUpdate)); } } catch (Exception e) { log.error("updateCatalogCache() has a problem: " + e.getMessage() + " biffCount: " + (++biffCount)); e.printStackTrace(); } finally { catlock.unlock(); repLock.unlock(); log.debug("_catalogLock WriteLock Released."); } } if (thread.isInterrupted()) { log.warn("updateCatalog(): WARNING! Thread " + thread.getName() + " was interrupted!"); throw new InterruptedException(); } } public HashMap<String, Vector<String>> getCoverageIDServerURL(IRISailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException { RepositoryConnection con = null; HashMap<String, Vector<String>> coverageIDServer; try { con = repo.getConnection(); coverageIDServer = getCoverageIDServerURL(con); return coverageIDServer; } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error(e.getClass().getName() + ": Failed to close repository connection. Msg: " + e.getMessage()); } } } } /** * @param con * @return * @throws RepositoryException * @throws MalformedQueryException * @throws QueryEvaluationException */ public HashMap<String, Vector<String>> getCoverageIDServerURL(RepositoryConnection con) throws RepositoryException, MalformedQueryException, QueryEvaluationException { TupleQueryResult result; HashMap<String, Vector<String>> coverageIDServer = new HashMap<String, Vector<String>>(); String queryString = "SELECT coverageurl,coverageid " + "FROM " + "{} wcs:CoverageDescription {coverageurl} wcs:Identifier {coverageid} " + "USING NAMESPACE " + "wcs = <http://www.opengis.net/wcs/1.1 log.debug("getCoverageIDServerURL() - QueryString (coverage ID and server URL): \n" + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); log.debug("getCoverageIDServerURL() - Qresult: " + result.hasNext()); while (result.hasNext()) { BindingSet bindingSet = result.next(); Vector<String> coverageURL = new Vector<String>(); if (bindingSet.getValue("coverageid") != null && bindingSet.getValue("coverageurl") != null) { Value valueOfcoverageid = bindingSet.getValue("coverageid"); Value valueOfcoverageurl = bindingSet.getValue("coverageurl"); coverageURL.addElement(valueOfcoverageurl.stringValue()); log.debug("getCoverageIDServerURL() - coverageid: " + valueOfcoverageid.stringValue()); log.debug("getCoverageIDServerURL() - coverageurl: " + valueOfcoverageurl.stringValue()); if (coverageIDServer.containsKey(valueOfcoverageid.stringValue())) coverageIDServer.get(valueOfcoverageid.stringValue()).addElement(valueOfcoverageurl.stringValue()); else coverageIDServer.put(valueOfcoverageid.stringValue(), coverageURL); } } return coverageIDServer; } public void run() { try { log.info("************* STARTING CATALOG UPDATE THREAD."); try { log.info("************* CATALOG UPDATE THREAD sleeping for " + firstUpdateDelay / 1000.0 + " seconds."); Thread.sleep(firstUpdateDelay); } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } int updateCounter = 0; long startTime, endTime; long elapsedTime, sleepTime; stopWorking = false; Thread thread = Thread.currentThread(); while (!stopWorking) { try { startTime = new Date().getTime(); try { updateCatalog(); } catch (RepositoryException e) { log.error("Problem using Repository! msg: " + e.getMessage()); } endTime = new Date().getTime(); elapsedTime = (endTime - startTime); updateCounter++; log.debug("Completed catalog update " + updateCounter + " in " + elapsedTime / 1000.0 + " seconds."); sleepTime = catalogUpdateInterval - elapsedTime; stopWorking = thread.isInterrupted(); if (!stopWorking && sleepTime > 0) { log.debug("Catalog Update thread sleeping for " + sleepTime / 1000.0 + " seconds."); Thread.sleep(sleepTime); } } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } } } finally { destroy(); } log.info("************* EXITING CATALOG UPDATE THREAD."); } private void addSupportedFormats(Element coverages) throws MalformedURLException { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); Element coverageDescription; Element identifierElem; Iterator i; String coverageID; String msg; Vector<String> servers; i = coverages.getChildren().iterator(); while (i.hasNext()) { coverageDescription = (Element) i.next(); identifierElem = coverageDescription.getChild("Identifier", WCS.WCS_NS); if (identifierElem != null) { coverageID = identifierElem.getTextTrim(); servers = coverageIDServer.get(coverageID); Vector<Element> supportedFormats = getWcsSupportedFormatElements(new URL(servers.get(0))); coverageDescription.addContent(supportedFormats); msg = "Adding supported formats to coverage " + coverageID + "\n" + "CoverageDescription Element: \n " + xmlo.outputString(coverageDescription) + "\n" + "Coverage " + coverageID + " held at: \n"; for (String s : servers) { msg += " " + s + "\n"; } log.debug(msg); } else { log.error("addSupportedFormats() - Failed to locate wcs:Identifier element for Coverage!"); //@todo Throw an exception (what kind??) here!! } } } private Vector<Element> getWcsSupportedFormatElements(URL dapServerUrl) { Vector<Element> sfEs = new Vector<Element>(); String[] formats = ServerCapabilities.getSupportedFormatStrings(dapServerUrl); Element sf; for (String format : formats) { sf = new Element("SupportedFormat", WCS.WCS_NS); sf.setText(format); sfEs.add(sf); } return sfEs; } private void checkExecutionState() throws InterruptedException { Thread thread = Thread.currentThread(); boolean isInterrupted = thread.isInterrupted(); if (isInterrupted || stopWorking) { log.warn("updateRepository2(): WARNING! Thread " + thread.getName() + " was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned '" + isInterrupted + "'. stopWorking='" + stopWorking + "'"); } } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.ResourceCreationPoint; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.RepositoryLookupFailureCallback; import edu.umd.cs.findbugs.ba.ResourceValue; import edu.umd.cs.findbugs.ba.ResourceValueFrame; import org.apache.bcel.Constants; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKEVIRTUAL; import org.apache.bcel.generic.INVOKEINTERFACE; /** * A Stream object marks the location in the code where a * stream is created. It also is responsible for determining * some aspects of how the stream state is tracked * by the ResourceValueAnalysis, such as when the stream * is opened or closed, and whether implicit exception * edges are significant. * * <p> TODO: change streamClass and streamBase to ObjectType * * <p> TODO: isStreamOpen() and isStreamClose() should * probably be abstract, so we can customize how they work * for different kinds of streams */ public class Stream extends ResourceCreationPoint { private String streamBase; private boolean isUninteresting; private boolean isOpenOnCreation; private InstructionHandle ctorHandle; private boolean ignoreImplicitExceptions; private String bugType; /** * Constructor. * By default, Stream objects are marked as uninteresting. * setInteresting("BUG_TYPE") must be called explicitly to mark * the Stream as interesting. * @param location where the stream is created * @param streamClass type of Stream * @param baseClass highest class in the class hierarchy through which * stream's close() method could be called */ public Stream(Location location, String streamClass, String streamBase) { super(location, streamClass); this.streamBase = streamBase; isUninteresting = true; } /** * Mark this Stream as interesting. * @param bugType the bug type that should be reported if * the stream is not closed on all paths out of the method */ public Stream setInteresting(String bugType) { this.isUninteresting = false; this.bugType = bugType; return this; } /** * Mark whether or not implicit exception edges should be * ignored by ResourceValueAnalysis when determining whether or * not stream is closed on all paths out of method. */ public Stream setIgnoreImplicitExceptions(boolean enable) { ignoreImplicitExceptions = enable; return this; } /** * Mark whether or not Stream is open as soon as it is created, * or whether a later method or constructor must explicitly * open it. */ public Stream setIsOpenOnCreation(boolean enable) { isOpenOnCreation = enable; return this; } public String getStreamBase() { return streamBase; } public boolean isUninteresting() { return isUninteresting; } public boolean isOpenOnCreation() { return isOpenOnCreation; } public void setConstructorHandle(InstructionHandle handle) { this.ctorHandle = handle; } public InstructionHandle getConstructorHandle() { return ctorHandle; } public boolean ignoreImplicitExceptions() { return ignoreImplicitExceptions; } public String getBugType() { return bugType; } public boolean isStreamOpen(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame) { if (isOpenOnCreation) return false; Instruction ins = handle.getInstruction(); if (!(ins instanceof INVOKESPECIAL)) return false; // Does this instruction open the stream? INVOKESPECIAL inv = (INVOKESPECIAL) ins; return frame.isValid() && getInstanceValue(frame, inv, cpg).isInstance() && matchMethod(inv, cpg, this.getResourceClass(), "<init>"); } public boolean isStreamClose(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame, RepositoryLookupFailureCallback lookupFailureCallback) { Instruction ins = handle.getInstruction(); if ((ins instanceof INVOKEVIRTUAL) || (ins instanceof INVOKEINTERFACE)) { // Does this instruction close the stream? InvokeInstruction inv = (InvokeInstruction) ins; if (!frame.isValid() || !getInstanceValue(frame, inv, cpg).isInstance()) return false; // It's a close if the invoked class is any subtype of the stream base class. // (Basically, we may not see the exact original stream class, // even though it's the same instance.) try { return inv.getName(cpg).equals("close") && inv.getSignature(cpg).equals("()V") && Hierarchy.isSubtype(inv.getClassName(cpg), streamBase); } catch (ClassNotFoundException e) { lookupFailureCallback.reportMissingClass(e); return false; } } return false; } private ResourceValue getInstanceValue(ResourceValueFrame frame, InvokeInstruction inv, ConstantPoolGen cpg) { int numConsumed = inv.consumeStack(cpg); if (numConsumed == Constants.UNPREDICTABLE) throw new IllegalStateException(); return frame.getValue(frame.getNumSlots() - numConsumed); } private boolean matchMethod(InvokeInstruction inv, ConstantPoolGen cpg, String className, String methodName) { return inv.getClassName(cpg).equals(className) && inv.getName(cpg).equals(methodName); } } // vim:ts=3
package edu.kit.iti.formal.pse.worthwhile.interpreter; import static org.junit.Assert.*; import java.math.BigInteger; import org.junit.Test; import edu.kit.iti.formal.pse.worthwhile.common.tests.TestASTProvider; /** * @author matthias and stefan */ public class InterpreterASTNodeVisitorTest { @Test public void test() { InterpreterASTNodeVisitor v = new InterpreterASTNodeVisitor(); assertNotNull(v); } @Test public void testInterpreterContextAssignment() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Integer a := 42\n")); assertNotNull(interpreter); interpreter.execute(); Value value = new Value(new BigInteger("42")); assertEquals(interpreter.getSymbol("a"), value); } @Test public void testInterpreterContexAddition() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Integer a := 21 + 21\n")); assertNotNull(interpreter); interpreter.execute(); Value value = new Value(new BigInteger("42")); assertEquals(interpreter.getSymbol("a"), value); } @Test public void testInterpreterContexMultiplication() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Integer a := 2 * 21\n")); assertNotNull(interpreter); interpreter.execute(); Value value = new Value(new BigInteger("42")); assertEquals(interpreter.getSymbol("a"), value); } @Test public void testInterpreterContexDivision() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Integer a := 84 / 2\n")); assertNotNull(interpreter); interpreter.execute(); Value value = new Value(new BigInteger("42")); assertEquals(interpreter.getSymbol("a"), value); } @Test public void testInterpreterContexModulus() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Integer a := 85 % 43\n")); assertNotNull(interpreter); interpreter.execute(); Value value = new Value(new BigInteger("42")); assertEquals(interpreter.getSymbol("a"), value); } @Test public void testInterpreterContexAnd() { Interpreter interpreter = new Interpreter( TestASTProvider.getRootASTNode("Boolean a := true && false\n")); assertNotNull(interpreter); interpreter.execute(); assertFalse(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexOr() { Interpreter interpreter = new Interpreter( TestASTProvider.getRootASTNode("Boolean a := true || false\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexLess() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 < 45\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexGreater() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 > 41\n")); assertNotNull(interpreter); interpreter.execute(); assertFalse(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexLessEqual() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 <= 52\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexGreaterEqual() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 >= 52\n")); assertNotNull(interpreter); interpreter.execute(); assertFalse(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexEqual() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 == 42\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexNotEqual() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := 42 != 52\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } @Test public void testInterpreterContexNot() { Interpreter interpreter = new Interpreter(TestASTProvider.getRootASTNode("Boolean a := !false\n")); assertNotNull(interpreter); interpreter.execute(); assertTrue(interpreter.getSymbol("a").getBooleanValue()); } }
package org.TexasTorque.TorqueLib.util; import com.sun.squawk.io.BufferedWriter; import com.sun.squawk.microedition.io.FileConnection; import java.io.IOException; import java.io.OutputStreamWriter; import javax.microedition.io.Connector; public class TorqueLogging2 { private static TorqueLogging2 instance; private FileConnection fileConnection = null; private BufferedWriter fileIO = null; private String fileName = "TorqueLog.csv"; private String filePath = "file:///ni-rt/startup/"; private String keyNames; private String logString; public static TorqueLogging2 getInstance() { return (instance == null) ? instance = new TorqueLogging2() : instance; } private TorqueLogging2() { try { fileConnection = (FileConnection) Connector.open(filePath + fileName); if(!fileConnection.exists()) { fileConnection.create(); } fileIO = new BufferedWriter(new OutputStreamWriter(fileConnection.openOutputStream())); } catch(IOException e) { System.err.println("Error creating file in TorqueLogging."); } keyNames = null; logString = null; } public void logKeyNames(String names) { keyNames = names; log(keyNames); } public void logData(String data) { logString = data; log(logString); } private void log(String str) { try { fileIO.write(str); fileIO.newLine(); fileIO.flush(); } catch(IOException e) { System.err.println("Error logging some data."); } } }
package com.thinkbiganalytics.util; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class ColumnSpecTest { /** Verify the DDL for creating the column. */ @Test public void toCreateSQL() { final ColumnSpec[] specs = ColumnSpec.createFromString("col1|string"); Assert.assertNotNull(specs); Assert.assertEquals("`col1` string", specs[0].toCreateSQL()); } /** Verify the DDL for creating the partition. */ @Test public void toPartitionSQL() { final ColumnSpec[] specs = ColumnSpec.createFromString("col1|string"); Assert.assertNotNull(specs); Assert.assertEquals("`col1` string", specs[0].toPartitionSQL()); } /** Verify the join query. */ @Test public void toPrimaryKeyJoinSQL() { final ColumnSpec[] specs = ColumnSpec.createFromString("col1|string|pk1|1|0|0\ncol2|int\ncol3|int|pk2|1|0|0"); Assert.assertNotNull(specs); Assert.assertEquals("`a`.`col1` = `b`.`col1` AND `a`.`col3` = `b`.`col3`", ColumnSpec.toPrimaryKeyJoinSQL(specs, "a", "b")); } /** Verify the primary key identifiers. */ @Test public void toPrimaryKeys() { final ColumnSpec[] specs = ColumnSpec.createFromString("col1|string|pk1|1|0|0\ncol2|int\ncol3|int|pk2|1|0|0"); Assert.assertNotNull(specs); Assert.assertArrayEquals(new String[] {"`col1`", "`col3`"}, ColumnSpec.toPrimaryKeys(specs)); } @Test public void testFromString() throws IOException { ColumnSpec[] specs = ColumnSpec.createFromString("col1|string|my comment\ncol2|int\ncol3|string|foo description\ncol4|string"); assertTrue("Expecting 4 parts", specs.length==4); assertTrue(specs[0].getComment().equals("my comment")); ColumnSpec[] specs2 = ColumnSpec.createFromString("col1|string|my comment|1|0|0\ncol2|int\ncol3|string|foo description\ncol4|string||BAD|1|1"); assertTrue("Expecting 4 parts", specs.length==4); assertTrue(specs2[0].isPk()); assertFalse(specs2[0].isCreateDt()); assertFalse(specs2[0].isModifiedDt()); assertFalse(specs2[1].isPk()); assertFalse(specs2[1].isCreateDt()); assertFalse(specs2[1].isModifiedDt()); assertFalse(specs2[2].isPk()); assertFalse(specs2[2].isCreateDt()); assertFalse(specs2[2].isModifiedDt()); assertFalse(specs2[3].isPk()); assertTrue(specs2[3].isCreateDt()); assertTrue(specs2[3].isModifiedDt()); } @Test public void testSpecs() throws IOException { ColumnSpec[] specs = ColumnSpec.createFromString("col1|string|my comment\ncol2|int\ncol3|string|foo description\ncol4|string"); StringBuffer sb = new StringBuffer(); int i = specs.length; for (ColumnSpec spec : specs) { sb.append(spec.toCreateSQL()); if (i sb.append(", "); } } System.out.println(sb.toString()); assertNotNull(sb.toString()); } @Test public void testPartitionKeyAndQuery() { PartitionKey key1 = new PartitionKey("country", "string", "country"); PartitionKey key2 = new PartitionKey("year", "int", "year(hired_date)"); PartitionKey key3 = new PartitionKey("reg date month", "int", "month(reg date)"); PartitionKey key4 = new PartitionKey("reg date day", "int", "day(`reg date`)"); PartitionSpec spec = new PartitionSpec(key1, key2, key3, key4); String sql = spec.toDistinctSelectSQL("sourceSchema", "sourceTable", "11111111"); System.out.println(sql); String expected = "select `country`, year(`hired_date`), month(`reg date`), day(`reg date`), count(0) as `tb_cnt` from `sourceSchema`.`sourceTable` where `processing_dttm` = \"11111111\" " + "group by `country`, year(`hired_date`), month(`reg date`), day(`reg date`)"; assertEquals(expected, sql); assertEquals("`country`", key1.getKeyForSql()); assertEquals("`year`", key2.getKeyForSql()); assertEquals("`reg date month`", key3.getKeyForSql()); assertEquals("`reg date day`", key4.getKeyForSql()); } }