answer
stringlengths
17
10.2M
// $Id:Giniiosp.java 63 2006-07-12 21:50:51Z edavis $ package ucar.nc2.iosp.gini; import ucar.ma2.*; import ucar.nc2.Variable; import java.io.*; import java.awt.image.*; import java.util.*; import java.util.zip.Inflater; import java.util.zip.DataFormatException; //import java.awt.image.BufferedImage; /** * IOServiceProvider implementation abstract base class to read/write "version 3" netcdf files. * AKA "file format version 1" files. * * see concrete class */ public class Giniiosp implements ucar.nc2.IOServiceProvider { protected boolean readonly; private ucar.nc2.NetcdfFile ncfile; private ucar.unidata.io.RandomAccessFile myRaf; protected Giniheader headerParser; final static int Z_DEFLATED = 8; final static int DEF_WBITS = 15; // used for writing protected int fileUsed = 0; // how much of the file is written to ? protected int recStart = 0; // where the record data starts protected boolean debug = false, debugSize = false, debugSPIO = false; protected boolean showHeaderBytes = false; public void setSpecial( Object special) {} public ucar.ma2.Array readNestedData(ucar.nc2.Variable v2, java.util.List section) throws java.io.IOException, ucar.ma2.InvalidRangeException { throw new UnsupportedOperationException("Gini IOSP does not support nested variables"); } public boolean isValidFile( ucar.unidata.io.RandomAccessFile raf ) { Giniheader localHeader = new Giniheader(); return( localHeader.isValidFile( raf )); } // reading public void open(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile file, ucar.nc2.util.CancelTask cancelTask) throws IOException { ncfile = file; myRaf = raf; headerParser = new Giniheader(); headerParser.read(myRaf, ncfile, null); ncfile.finish(); } public Array readData(ucar.nc2.Variable v2, java.util.List sectionList) throws IOException, InvalidRangeException { // subset Range[] section = Range.toArray( sectionList); int[] origin = new int[v2.getRank()]; int[] shape = v2.getShape(); int[] stride = new int[v2.getRank()]; if (section != null) { for (int i=0; i<section.length; i++ ) { origin[i] = section[i].first(); shape[i] = section[i].length(); stride[i] = section[i].stride(); //if (section[i].stride() != 1) // throw new UnsupportedOperationException("Giniiosp doesnt yet support strides"); } } Giniheader.Vinfo vinfo = (Giniheader.Vinfo) v2.getSPobject(); if( headerParser.gini_GetCompressType() == 0) return readData( v2, vinfo.begin, origin, shape, stride); else if(headerParser.gini_GetCompressType() == 2 ) return readCompressedData( v2, vinfo.begin, origin, shape, stride ); else if(headerParser.gini_GetCompressType() == 1 ) return readCompressedZlib( v2, vinfo.begin, vinfo.nx, vinfo.ny, origin, shape, stride ); else return null; } // all the work is here, so can be called recursively public Array readData(ucar.nc2.Variable v2, long dataPos, int [] origin, int [] shape, int [] stride) throws IOException, InvalidRangeException { long length = myRaf.length(); myRaf.seek(dataPos); int data_size = (int) (length - dataPos); byte[] data = new byte[data_size]; myRaf.read(data); Array array = Array.factory( DataType.BYTE.getPrimitiveClassType(), v2.getShape(), data); return array.sectionNoReduce(origin, shape, stride); } public Array readDataOld(ucar.nc2.Variable v2, long dataPos, int [] origin, int [] shape, int [] stride) throws IOException, InvalidRangeException { int start_l, stride_l, stop_l; int start_p, stride_p, stop_p; if (origin == null) origin = new int[ v2.getRank()]; if (shape == null) shape = v2.getShape(); Giniheader.Vinfo vinfo = (Giniheader.Vinfo) v2.getSPobject(); ucar.ma2.DataType dataType = v2.getDataType(); int nx = vinfo.nx ; int ny = vinfo.ny ; start_l = origin[0]; stride_l = stride[0]; stop_l = origin[0] + shape[0] - 1; // Get data values from GINI // Loop over number of lines (slower dimension) for actual data Array start_p = origin[1] ; stride_p = stride[1]; stop_p = origin[1] + shape[1] -1; if(start_l+stop_l+stride_l == 0){ //default lines start_l = 0; stride_l = 1; stop_l = ny -1 ; } if(start_p+stop_p+stride_p == 0){ //default pixels start_p = 0; stride_p = 1; stop_p = nx - 1; } int Len = shape[1]; // length of pixels read each line ucar.ma2.DataType ConvertFrom = ucar.ma2.DataType.BYTE; ArrayByte adata = new ArrayByte(new int[] {shape[0], shape[1]}); Index indx = adata.getIndex(); long doff = dataPos + start_p; // initially no data conversion is needed. if(ConvertFrom == ucar.ma2.DataType.BYTE) { for (int iline = start_l; iline <= stop_l; iline+=stride_l) { /* read 1D byte[] */ byte[] buf = getGiniLine(nx, ny, doff, iline, Len, stride_p); /* write into 2D array */ for(int i = 0; i < Len; i++ ){ adata.setByte(indx.set(iline - start_l, i), buf[i] ); } } } return adata; } // for the compressed data read all out into a array and then parse into requested // for the compressed data read all out into a array and then parse into requested public Array readCompressedData(ucar.nc2.Variable v2, long dataPos, int [] origin, int [] shape, int [] stride) throws IOException, InvalidRangeException { long length = myRaf.length(); myRaf.seek(dataPos); int data_size = (int) (length - dataPos); byte[] data = new byte[data_size]; myRaf.read(data); ByteArrayInputStream ios = new ByteArrayInputStream(data); BufferedImage image = javax.imageio.ImageIO.read(ios); Raster raster = image.getData(); DataBuffer db = raster.getDataBuffer(); if (db instanceof DataBufferByte) { DataBufferByte dbb = (DataBufferByte) db; int t = dbb.getNumBanks(); byte[] udata = dbb.getData(); Array array = Array.factory( DataType.BYTE.getPrimitiveClassType(), v2.getShape(), udata); v2.setCachedData(array, false); return array.sectionNoReduce(origin, shape, stride); } return null; } public Array readCompressedZlib(ucar.nc2.Variable v2, long dataPos, int nx, int ny, int [] origin, int [] shape, int [] stride) throws IOException, InvalidRangeException { long length = myRaf.length(); myRaf.seek(dataPos); int data_size = (int) (length - dataPos); // or 5120 as read buffer size byte[] data = new byte[data_size]; myRaf.read(data); // decompress the bytes int resultLength = 0; int result = 0; byte[] inflateData = new byte[nx*(ny)]; byte[] tmp; int uncompLen ; /* length of decompress space */ byte[] uncomp = new byte[nx*(ny+1) + 4000]; Inflater inflater = new Inflater( false); inflater.setInput(data, 0, data_size); int offset = 0; int limit = nx*ny + nx; while ( inflater.getRemaining() > 0 ) { try { resultLength = inflater.inflate(uncomp, offset, 4000); } catch (DataFormatException ex) { System.out.println("ERROR on inflation "+ex.getMessage()); ex.printStackTrace(); throw new IOException( ex.getMessage()); } offset = offset + resultLength; result = result + resultLength; if( (result) > limit ) { // when uncomp data larger then limit, the uncomp need to increase size tmp = new byte[ result]; System.arraycopy(uncomp, 0, tmp, 0, result); uncompLen = result + 4000; uncomp = new byte[uncompLen]; System.arraycopy(tmp, 0, uncomp, 0, result); } if( resultLength == 0 ) { int tt = inflater.getRemaining(); byte [] b2 = new byte[2]; System.arraycopy(data,(int)data_size-tt, b2, 0, 2); if( isZlibHed( b2 ) == 0 ) { System.arraycopy(data, (int)data_size-tt, uncomp, result, tt); result = result + tt; break; } inflater.reset(); inflater.setInput(data, (int)data_size-tt, tt); } } inflater.end(); System.arraycopy(uncomp, 0, inflateData, 0, nx*ny ); if ( data != null) { Array array = Array.factory( DataType.BYTE.getPrimitiveClassType(), v2.getShape(), uncomp); if (array.getSize() < Variable.defaultSizeToCache) v2.setCachedData(array, false); return array.sectionNoReduce(origin, shape, stride); } return null; } /* ** Name: GetGiniLine ** ** Purpose: Extract a line of data from a GINI image ** ** Parameters: ** buf - buffer containing image data ** ** Returns: ** SUCCESS == 1 ** FAILURE == 0 ** ** */ private byte[] getGiniLine( int nx, int ny, long doff, int lineNumber, int len, int stride ) throws IOException{ byte[] data = new byte[len]; /* ** checking image file and set location of first line in file */ myRaf.seek ( doff ); if ( lineNumber >= ny ) throw new IOException("Try to access the file at line number= "+lineNumber+" larger then last line number = "+ny); /* ** Read in the requested line */ int offset = lineNumber * nx + (int)doff; //myRaf.seek ( offset ); for( int i = 0; i< len; i++ ) { myRaf.seek ( offset ); data[i] = myRaf.readByte(); offset = offset + stride ; //myRaf.seek(offset); } //myRaf.read( data, 0, len); return data; } // convert byte array to char array static protected char[] convertByteToChar( byte[] byteArray) { int size = byteArray.length; char[] cbuff = new char[size]; for (int i=0; i<size; i++) cbuff[i] = (char) byteArray[i]; return cbuff; } // convert char array to byte array static protected byte[] convertCharToByte( char[] from) { int size = from.length; byte[] to = new byte[size]; for (int i=0; i<size; i++) to[i] = (byte) from[i]; return to; } /* ** Name: IsZlibed ** ** Purpose: Check a two-byte sequence to see if it indicates the start of ** a zlib-compressed buffer ** ** Parameters: ** buf - buffer containing at least two bytes ** ** Returns: ** SUCCESS 1 ** FAILURE 0 ** */ int issZlibed( byte[] buf ) { if ( (buf[0] & 0xf) == Z_DEFLATED ) { if ( (buf[0] >> 4) + 8 <= DEF_WBITS ) { if ( (((buf[0] << 8) + (buf[1])) % 31) == 0 ) { return 1; } } } return 0; } protected boolean fill; protected HashMap dimHash = new HashMap(50); public void flush() throws java.io.IOException { myRaf.flush(); } public void close() throws java.io.IOException { myRaf.close(); } public boolean syncExtend() { return false; } public boolean sync() { return false; } public short convertunsignedByte2Short(byte b) { return (short) ((b < 0) ? (short) b + 256 : (short) b); } int isZlibHed( byte[] buf ){ short b0 = convertunsignedByte2Short(buf[0]); short b1 = convertunsignedByte2Short(buf[1]); if ( (b0 & 0xf) == Z_DEFLATED ) { if ( (b0 >> 4) + 8 <= DEF_WBITS ) { if ( (((b0 << 8) + b1) % 31)==0 ) { return 1; } } } return 0; } /** Debug info for this object. */ public String toStringDebug(Object o) { return null; } public String getDetailInfo() { return ""; } public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException { //String fileIn = "/home/yuanho/dev/netcdf-java-2.2/src/ucar/nc2/n0r_20040823_2215"; // uncompressed String fileIn = "c:/data/image/gini/n0r_20041013_1852"; ucar.nc2.NetcdfFile.registerIOProvider( ucar.nc2.iosp.gini.Giniiosp.class); ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn); List alist = ncf.getGlobalAttributes(); ucar.nc2.Variable v = ncf.findVariable("BaseReflectivity"); int[] origin = {0, 0}; int[] shape = {3000, 4736}; ArrayByte data = (ArrayByte)v.read(origin,shape); ncf.close(); } }
package annotations.el; import checkers.nullness.quals.Nullable; import checkers.javari.quals.ReadOnly; import java.io.File; import java.util.*; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.lang.reflect.Method; import annotations.el.AElement; import annotations.AnnotationBuilder; import annotations.field.*; import annotations.util.coll.*; import annotations.Annotation; import annotations.Annotations; /** * An annotation type definition, consisting of the annotation name, * its meta-annotations, and its field names and * types. <code>AnnotationDef</code>s are immutable. An AnnotationDef with * a non-null retention policy is called a "top-level annotation definition". */ public final /*@ReadOnly*/ class AnnotationDef extends AElement { /** * The fully qualified name of the annotation type, such as * "foo.Bar$Baz". */ public final String name; /** * A map of the names of this annotation type's fields to their types. Since * {@link AnnotationDef}s are immutable, attempting to modify this * map will result in an exception. */ public /*@ReadOnly*/ Map<String, AnnotationFieldType> fieldTypes; /** * Constructs an annotation definition with the given name. * You MUST call setFieldTypes afterward, even if with an empty map. (Yuck.) */ public AnnotationDef(String name) { super("annotation: " + name); assert name != null; this.name = name; } // Problem: I am not sure how to handle circularities (annotations meta-annotated with themselves /** Use scene to look up (or insert into it) missing AnnotationDefs. */ public static AnnotationDef fromClass(Class<? extends java.lang.annotation.Annotation> annoType, Map<String,AnnotationDef> adefs) { String name = annoType.getCanonicalName(); assert name != null; if (adefs.containsKey(name)) { return adefs.get(name); } Map<String,AnnotationFieldType> fieldTypes = new LinkedHashMap<String,AnnotationFieldType>(); for (Method m : annoType.getDeclaredMethods()) { AnnotationFieldType aft = AnnotationFieldType.fromClass(m.getReturnType(), adefs); fieldTypes.put(m.getName(), aft); } AnnotationDef result = new AnnotationDef(name, Annotations.noAnnotations, fieldTypes); adefs.put(name, result); // An annotation can be meta-annotated with itself, so add // meta-annotations after putting the annotation in the map. java.lang.annotation.Annotation[] jannos; try { jannos = annoType.getDeclaredAnnotations(); } catch (Exception e) { printClasspath(); throw new Error("Exception in getDeclaredAnnotations for " + annoType, e); } for (java.lang.annotation.Annotation ja : jannos) { result.tlAnnotationsHere.add(new Annotation(ja, adefs)); } return result; } public AnnotationDef(String name, Set<Annotation> tlAnnotationsHere) { super("annotation: " + name); assert name != null; this.name = name; if (tlAnnotationsHere != null) { this.tlAnnotationsHere.addAll(tlAnnotationsHere); } } public AnnotationDef(String name, Set<Annotation> tlAnnotationsHere, /*@ReadOnly*/ Map<String, ? extends AnnotationFieldType> fieldTypes) { this(name, tlAnnotationsHere); setFieldTypes(fieldTypes); } /** * Constructs an annotation definition with the given name and field types. * The field type map is copied and then wrapped in an * {@linkplain Collections#unmodifiableMap unmodifiable map} to protect the * immutability of the annotation definition. * You MUST call setFieldTypes afterward, even if with an empty map. (Yuck.) */ public void setFieldTypes(/*@ReadOnly*/ Map<String, ? extends AnnotationFieldType> fieldTypes) { this.fieldTypes = Collections.unmodifiableMap( new LinkedHashMap<String, AnnotationFieldType>(fieldTypes) ); } /** * The retention policy for annotations of this type. * If non-null, this is called a "top-level" annotation definition. * It may be null for annotations that are used only as a field of other * annotations. */ public /*@Nullable*/ RetentionPolicy retention() { if (tlAnnotationsHere.contains(Annotations.aRetentionClass)) { return RetentionPolicy.CLASS; } else if (tlAnnotationsHere.contains(Annotations.aRetentionRuntime)) { return RetentionPolicy.RUNTIME; } else if (tlAnnotationsHere.contains(Annotations.aRetentionSource)) { return RetentionPolicy.SOURCE; } else { return null; } } /** * True if this is a type annotation (was meta-annotated * with @Target(ElementType.TYPE_USE) or @TypeQualifier). */ public boolean isTypeAnnotation() { return (tlAnnotationsHere.contains(Annotations.aTargetTypeUse) || tlAnnotationsHere.contains(Annotations.aTypeQualifier)); } /** * This {@link AnnotationDef} equals <code>o</code> if and only if * <code>o</code> is another nonnull {@link AnnotationDef} and * <code>this</code> and <code>o</code> define annotation types of the same * name with the same field names and types. */ @Override public boolean equals(/*@ReadOnly*/ Object o) /*@ReadOnly*/ { return o instanceof AnnotationDef && equals((AnnotationDef) o); } /** * Returns whether this {@link AnnotationDef} equals <code>o</code>; a * slightly faster variant of {@link #equals(Object)} for when the argument * is statically known to be another nonnull {@link AnnotationDef}. */ public boolean equals(AnnotationDef o) /*@ReadOnly*/ { boolean sameName = name.equals(o.name); boolean sameMetaAnnotations = equalsElement(o); boolean sameFieldTypes = fieldTypes.equals(o.fieldTypes); // Can be useful for debugging if (false && sameName && (! (sameMetaAnnotations && sameFieldTypes))) { String message = String.format("Warning: incompatible definitions of annotation %s%n %s%n %s%n", name, this, o); new Exception(message).printStackTrace(System.out); } return sameName && sameMetaAnnotations && sameFieldTypes; } /** * {@inheritDoc} */ @Override public int hashCode() /*@ReadOnly*/ { return name.hashCode() // Omit tlAnnotationsHere, becase it should be unique and, more // importantly, including it causes an infinite loop. // + tlAnnotationsHere.hashCode() + fieldTypes.hashCode(); } /** * Returns an <code>AnnotationDef</code> containing all the information * from both arguments, or <code>null</code> if the two arguments * contradict each other. Currently this just * {@linkplain AnnotationFieldType#unify unifies the field types} * to handle arrays of unknown element type, which can arise via * {@link AnnotationBuilder#addEmptyArrayField}. */ public static AnnotationDef unify(AnnotationDef def1, AnnotationDef def2) { // if (def1.name.equals(def2.name) // && def1.fieldTypes.keySet().equals(def2.fieldTypes.keySet()) // && ! def1.equalsElement(def2)) { // throw new Error(String.format("Unifiable except for meta-annotations:%n %s%n %s%n", // def1, def2)); if (def1.equals(def2)) { return def1; } else if (def1.name.equals(def2.name) && def1.equalsElement(def2) && def1.fieldTypes.keySet().equals(def2.fieldTypes.keySet())) { Map<String, AnnotationFieldType> newFieldTypes = new LinkedHashMap<String, AnnotationFieldType>(); for (String fieldName : def1.fieldTypes.keySet()) { AnnotationFieldType aft1 = def1.fieldTypes.get(fieldName); AnnotationFieldType aft2 = def2.fieldTypes.get(fieldName); AnnotationFieldType uaft = AnnotationFieldType.unify(aft1, aft2); if (uaft == null) { return null; } else newFieldTypes.put(fieldName, uaft); } return new AnnotationDef(def1.name, def1.tlAnnotationsHere, newFieldTypes); } else { return null; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); // Not: sb.append(((AElement) this).toString()); // because it causes an infinite loop. boolean first; first = true; for (Annotation a : tlAnnotationsHere) { if (!first) { sb.append(" "); } else { first=false; } sb.append(a); } sb.append("] "); sb.append("@"); sb.append(name); sb.append("("); first = true; for (Map.Entry<String, AnnotationFieldType> entry : fieldTypes.entrySet()) { if (!first) { sb.append(","); } else { first = false; } sb.append(entry.getValue().toString()); sb.append(" "); sb.append(entry.getKey()); } sb.append(")"); return sb.toString(); } public static void printClasspath() { System.out.println("\nClasspath:"); StringTokenizer tokenizer = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); } } }
package com.phoenix.eteacher.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MathUtils { private static int count = 0; private static class Node{ private String value = null; private Node left = null; private Node right = null; private boolean isOpt; private boolean isTree = false; private boolean noSwitch = false; private boolean noChildSwitch = false; private boolean noGrandchildSwitch = false; public Node(String value){ this.value = value; setType(value); } private void setType(String value) { if(isOperator(value)){ this.isOpt = true; } else if(isNum(value)){ this.isOpt = false; } else{ throw new RuntimeException("Node value must be either operator or a number!"); } } public Node(String value, Node left, Node right){ this.value = value; this.left = left; this.right = right; setType(value); } public boolean isOpt() { return isOpt; } public void setOpt(boolean isOpt) { this.isOpt = isOpt; } public boolean isTree() { return isTree; } public void setTree(boolean isTree) { this.isTree = isTree; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } private static boolean isOperator(String s){ return "+-*/".indexOf(s) != -1; } private static boolean isNum(String s){ try{ Integer.parseInt(s); return true; } catch(Exception ex){ return false; } } public void print(boolean printValue){ if(printValue){ System.out.println(this.value); } if(this.left != null){ System.out.print(" left: " + this.left.getValue()); this.left.print(false); } else{ System.out.print(" "); } if(this.right != null){ System.out.println(" right: " + this.right.getValue()); this.right.print(false); } } public int nodeCount(){ int i = 1; if(this.left != null){ i += this.left.nodeCount(); } if(this.right != null){ i += this.right.nodeCount(); } return i; } @Override public boolean equals(Object obj){ if(obj instanceof Node){ Node other = (Node)obj; if(!this.value.equals(other.value)){ return false; } if(this.left != null){ if(!left.equals(other.left)){ return false; } } else if(other.left != null){ return false; } if(this.right != null){ if (!right.equals(other.right)){ return false; } } else if(other.right != null){ return false; } return true; } else{ return false; } } @Override public int hashCode(){ return this.value.hashCode(); } private Set<Node> getIdenticalTrees(){ System.err.println("entering getIdenticalTrees " + count++); Set<Node> trees = new HashSet<Node>(); Set<Node> leftTrees = null; Set<Node> rightTrees = null; trees.add(this); if(this.left == null && this.right == null){ return trees; } if(this.left != null){ leftTrees = this.left.getIdenticalTrees(); for(Node tree : leftTrees){ trees.add(new Node(this.value, tree, this.right)); } } if(this.right != null){ rightTrees = this.right.getIdenticalTrees(); for(Node tree : rightTrees){ trees.add(new Node(this.value, this.left, tree)); } } if(leftTrees != null && rightTrees != null){ for(Node ltree : leftTrees){ for(Node rtree : rightTrees){ trees.add(new Node(this.value, ltree, rtree)); } } } if (!noSwitch && (this.value.equals("+") || this.value.equals("*"))){ Node tree = new Node(this.value, this.right, this.left); //set this to avoid infinite loop tree.noSwitch = true; trees.addAll(tree.getIdenticalTrees()); } if ((this.value.equals("+") && this.left.value.equals("+")) || (this.value.equals("*") && this.left.value.equals("*"))){ if(!noChildSwitch){ Node lNode = new Node(this.left.value, this.right, this.left.right); Node tree = new Node(this.value, lNode, this.left.left); //set this to avoid infinite loop tree.noChildSwitch = true; trees.addAll(tree.getIdenticalTrees()); lNode = new Node(this.left.value, this.left.left, this.right); tree = new Node(this.value, lNode, this.left.right); //set this to avoid infinite loop tree.noChildSwitch = true; trees.addAll(tree.getIdenticalTrees()); } } // if ((this.value.equals("+") && this.left.value.equals("+") && this.right.value.equals("+")) || (this.value.equals("*") && this.left.value.equals("*") && this.right.value.equals("*"))){ // if(!noGrandchildSwitch){ // Node lNode = new Node(this.left.value, this.right.left, this.left.right); // Node rNode = new Node(this.right.value, this.left.left, this.right.right); // Node tree = new Node(this.value, lNode, rNode); // //set this to avoid infinite loop // tree.noGrandchildSwitch = true; // trees.addAll(tree.getIdenticalTrees()); if (this.value.equals("*") && (this.left.value.equals("+") || this.left.value.equals("-"))){ Node lNode = new Node(this.value, this.left.left, this.right); Node rNode = new Node(this.value, this.left.right, this.right); Node newNode = new Node(this.left.value, lNode, rNode); // newNode.noChildSwitch = true; // newNode.noGrandchildSwitch = true; // newNode.noSwitch = true; trees.addAll(newNode.getIdenticalTrees()); } System.err.println("exiting getIdenticalTrees " + count); return trees; } } public static Node getExpressionTree(String exp){ List<Node> nodes = getPostfixExp(exp); while(!isTreeCompleted(nodes)){ for(int i = 0; i < nodes.size(); i++){ if(nodes.get(i).isOpt() && !nodes.get(i-1).isOpt() && !nodes.get(i-2).isOpt()){ Node newNode = new Node(nodes.get(i).getValue()); newNode.setLeft(nodes.get(i-2)); newNode.setRight(nodes.get(i-1)); newNode.setOpt(false); newNode.setTree(true); nodes.remove(i-2); nodes.remove(i-2); nodes.remove(i-2); nodes.add(i-2,newNode); i = i-2; continue; } } } return nodes.get(0); } private static boolean isTreeCompleted(List<Node> nodes) { for(Node node : nodes){ if(node.isOpt() && !node.isTree()){ return false; } } return true; } public static List<Node> getPostfixExp(String exp){ List<Node> sb = new ArrayList<Node>(); Stack<String> st = new Stack<String>(); List<String> eval = new ArrayList<String>(); String popUp; for(int i = 0; i < exp.length(); i++){ char op = exp.charAt(i); if(isOpt(op)){ if(st.isEmpty() || st.peek().equals("(") || isHigher(op,st.peek())){ st.push(op+""); } else{ popUp = st.pop(); sb.add(new Node(popUp)); eval.add(popUp); st.push(op+""); } } else if(op == '('){ st.push(op+""); } else if(op == ')'){ while(!st.peek().equals("(")){ popUp = st.pop(); sb.add(new Node(popUp)); eval.add(popUp); } st.pop(); } else{ int j = 0; while(i+j<exp.length() && isNum(exp.charAt(i+j))){ j++; } sb.add(new Node(exp.substring(i, i+j))); eval.add(exp.substring(i, i+j)); i = i + j - 1; } } while(!st.isEmpty()){ popUp = st.pop(); sb.add(new Node(popUp)); eval.add(popUp); } for(int i = 0; i < eval.size(); i++){ if (isOpt(eval.get(i))){ float b = Float.parseFloat(st.pop()); float a = Float.parseFloat(st.pop()); st.push(String.valueOf(compute(eval.get(i).charAt(0),a,b))); } else{ st.push(eval.get(i)); } } while(!st.isEmpty()){ st.pop(); // System.err.println("eval2: " + st.pop()); } return sb; } public static boolean isEquivalentExp(String correctExp, String exp){ Node correntTree = getExpressionTree(preprocess(correctExp)); Node tree = getExpressionTree(preprocess(exp)); Set<Node> sameTrees = correntTree.getIdenticalTrees(); return sameTrees.contains(tree); } private static String preprocess(String exp) { return exp.replaceAll("×", "*"); } private static boolean isNum(char s){ try{ Integer.parseInt(s+""); return true; } catch(Exception ex){ return false; } } private static float compute(char op, float a, float b){ float r; switch(op){ case '+': r = a + b; break; case '-': r = a - b; break; case '*': r = a * b; break; case '/': r = a / b; break; default: r = 0; break; } return r; } private static boolean isOpt(char s){ return "+-*/".indexOf(s) != -1; } private static boolean isOpt(String s){ return "+-*/".indexOf(s) != -1; } private static boolean isHigher(char o, String op){ return "*/".indexOf(o) != -1 && "+-".indexOf(op) != -1; } public static boolean isTheSame(String exp1, String exp2){ ExpressionTree et1 = new ExpressionTree(exp1); ExpressionTree et2 = new ExpressionTree(exp2); return (et1.isTheSame(et2)); } /** * @param args */ public static void main(String[] args) { String exp = "(1+3)*2"; // Node tree4 = getExpressionTree(exp); // Set<Node> same = tree4.getIdenticalTrees(); // System.out.println("identical: " + same.size()); // Set<Node> uniq = new HashSet<Node>(); // uniq.addAll(same); // System.out.println("identical: " + uniq.size()); // String answer = "2*(3+1)"; // System.err.println("Equivalent: " + isEquivalentExp(answer, exp)); // System.err.println("Equivalent: " + isEquivalentExp(answer, "2*3+1")); // answer = "1+2+3"; // List<Node> ansNode = getPostfixExp(answer); // for(Node aNode : ansNode){ // System.out.print(aNode.getValue()); // System.out.println(); // exp = "3+1+2"; // List<Node> expNode = getPostfixExp(exp); // for(Node aNode : expNode){ // System.out.print(aNode.getValue()); // System.out.println(); // exp = "(1+2)*((3+4)*5+6)"; // List<Node> nodes = MathUtils.getPostfixExp(exp); // Node root = MathUtils.getExpressionTree(exp); // for(Node node : nodes){ // System.out.print(node.value); System.out.println(); exp = "(1+2)*(3+4)*5"; isEquivalentExp(exp,exp); System.err.println("snow: " + "1+2=3".split("=")[0]); } public static ArrayList<String> appendResToStr(Matcher content){ ArrayList<String> res = new ArrayList<String>(); while(content.find()){ res.add(content.group()); } return res; } public static ArrayList<String> returnExpressionForEachLine(String line){ Pattern p = Pattern.compile("([\\d\\+\\-\\*\\/\\(\\)\\.]+)"); Matcher matcherAns = p.matcher( line ); ArrayList<String> ansExpression = MathUtils.appendResToStr(matcherAns); return ansExpression; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.sound; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.commons.io.IOUtils; import com.samskivert.util.Config; import com.samskivert.util.Interval; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.samskivert.util.RuntimeAdjust; import com.samskivert.util.StringUtil; import com.threerings.resource.ResourceManager; import com.threerings.util.RandomUtil; import com.threerings.media.Log; import com.threerings.media.MediaPrefs; /** * Manages the playing of audio files. */ public class SoundManager { /** * Create instances of this for your application to differentiate * between different types of sounds. */ public static class SoundType { /** * Construct a new SoundType. * Which should be a static variable stashed somewhere for the * entire application to share. * * @param strname a short string identifier, preferably without spaces. */ public SoundType (String strname) { _strname = strname; } public String toString () { return _strname; } protected String _strname; } /** * A control for sounds. */ public static interface Frob { /** * Stop playing or looping the sound. * At present, the granularity of this command is limited to the * buffer size of the line spooler, or about 8k of data. Thus, * if playing an 11khz sample, it could take 8/11ths of a second * for the sound to actually stop playing. */ public void stop (); /** * Set the volume of the sound. */ public void setVolume (float vol); /** * Get the volume of this sound. */ public float getVolume (); } /** The default sound type. */ public static final SoundType DEFAULT = new SoundType("default"); /** * Constructs a sound manager. */ public SoundManager (ResourceManager rmgr) { this(rmgr, null, null); } /** * Constructs a sound manager. * * @param defaultClipBundle * @param defaultClipPath The pathname of a sound clip to use as a * fallback if another sound clip cannot be located. */ public SoundManager ( ResourceManager rmgr, String defaultClipBundle, String defaultClipPath) { // save things off _rmgr = rmgr; _defaultClipBundle = defaultClipBundle; _defaultClipPath = defaultClipPath; } /** * Shut the damn thing off. */ public void shutdown () { synchronized (_queue) { _queue.clear(); if (_spoolerCount > 0) { _queue.append(new SoundKey(DIE)); // signal death } } synchronized (_clipCache) { _lockedClips.clear(); } } /** * Returns a string summarizing our volume settings and disabled sound * types. */ public String summarizeState () { StringBuffer buf = new StringBuffer(); buf.append(", clipVol=").append(_clipVol); buf.append(", disabled=["); int ii = 0; for (Iterator iter = _disabledTypes.iterator(); iter.hasNext(); ) { if (ii++ > 0) { buf.append(", "); } buf.append(iter.next()); } return buf.append("]").toString(); } /** * Is the specified soundtype enabled? */ public boolean isEnabled (SoundType type) { // by default, types are enabled.. return (!_disabledTypes.contains(type)); } /** * Turns on or off the specified sound type. */ public void setEnabled (SoundType type, boolean enabled) { if (enabled) { _disabledTypes.remove(type); } else { _disabledTypes.add(type); } } /** * Sets the volume for all sound clips. * * @param vol a volume parameter between 0f and 1f, inclusive. */ public void setClipVolume (float vol) { _clipVol = Math.max(0f, Math.min(1f, vol)); } /** * Get the volume for all sound clips. */ public float getClipVolume () { return _clipVol; } /** * Optionally lock the sound data prior to playing, to guarantee * that it will be quickly available for playing. */ public void lock (String pkgPath, String key) { enqueue(new SoundKey(LOCK, pkgPath, key), true); } /** * Unlock the specified sound so that its resources can be freed. */ public void unlock (String pkgPath, String key) { enqueue(new SoundKey(UNLOCK, pkgPath, key), true); } /** * Batch lock a list of sounds. */ public void lock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(LOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Batch unlock a list of sounds. */ public void unlock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(UNLOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Play the specified sound of as the specified type of sound, immediately. * Note that a sound need not be locked prior to playing. */ public void play (SoundType type, String pkgPath, String key) { play(type, pkgPath, key, 0); } /** * Play the specified sound after the specified delay. * @param delay the delay in milliseconds. */ public void play (SoundType type, String pkgPath, String key, int delay) { if (type == null) { type = DEFAULT; // let the lazy kids play too } if ((_clipVol != 0f) && isEnabled(type)) { final SoundKey skey = new SoundKey(PLAY, pkgPath, key, delay, _clipVol); if (delay > 0) { new Interval() { public void expired () { addToPlayQueue(skey); } }.schedule(delay); } else { addToPlayQueue(skey); } } } /** * Loop the specified sound. */ public Frob loop (SoundType type, String pkgPath, String key) { SoundKey skey = new SoundKey(LOOP, pkgPath, key, 0, _clipVol); addToPlayQueue(skey); return skey; // it is a frob } /** * Add the sound clip key to the queue to be played. */ protected void addToPlayQueue (SoundKey skey) { boolean queued = enqueue(skey, true); if (queued) { if (_verbose.getValue()) { Log.info("Sound request [key=" + skey.key + "]."); } } else /* if (_verbose.getValue()) */ { Log.warning("SoundManager not playing sound because " + "too many sounds in queue [key=" + skey + "]."); } } /** * Enqueue a new SoundKey. */ protected boolean enqueue (SoundKey key, boolean okToStartNew) { boolean add; boolean queued; synchronized (_queue) { if (key.cmd == PLAY && _queue.size() > MAX_QUEUE_SIZE) { queued = add = false; } else { _queue.appendLoud(key); queued = true; add = okToStartNew && (_freeSpoolers == 0) && (_spoolerCount < MAX_SPOOLERS); if (add) { _spoolerCount++; } } } // and if we need a new thread, add it if (add) { Thread spooler = new Thread("narya SoundManager line spooler") { public void run () { spoolerRun(); } }; spooler.setDaemon(true); spooler.start(); } return queued; } /** * This is the primary run method of the sound-playing threads. */ protected void spoolerRun () { while (true) { try { SoundKey key; synchronized (_queue) { _freeSpoolers++; key = (SoundKey) _queue.get(MAX_WAIT_TIME); _freeSpoolers if (key == null || key.cmd == DIE) { _spoolerCount // if dieing and there are others to kill, do so if (key != null && _spoolerCount > 0) { _queue.appendLoud(key); } return; } } // process the command processKey(key); } catch (Exception e) { Log.logStackTrace(e); } } } /** * Process the requested command in the specified SoundKey. */ protected void processKey (SoundKey key) throws Exception { switch (key.cmd) { case PLAY: case LOOP: playSound(key); break; case LOCK: if (!isTesting()) { synchronized (_clipCache) { try { getClipData(key); // preload // copy cached to lock map _lockedClips.put(key, _clipCache.get(key)); } catch (Exception e) { // don't whine about LOCK failures unless // we are verbosely logging if (_verbose.getValue()) { throw e; } } } } break; case UNLOCK: synchronized (_clipCache) { _lockedClips.remove(key); } break; } } /** * On a spooling thread, */ protected void playSound (SoundKey key) { if (!key.running) { return; } key.thread = Thread.currentThread(); SourceDataLine line = null; try { // get the sound data from our LRU cache byte[] data = getClipData(key); if (data == null) { return; // borked! } else if (key.isExpired()) { if (_verbose.getValue()) { Log.info("Sound expired [key=" + key.key + "]."); } return; } AudioInputStream stream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(data)); AudioFormat format = stream.getFormat(); // open the sound line line = (SourceDataLine) AudioSystem.getLine( new DataLine.Info(SourceDataLine.class, format)); line.open(format, LINEBUF_SIZE); float setVolume = 1; line.start(); _soundSeemsToWork = true; do { // play the sound byte[] buffer = new byte[LINEBUF_SIZE]; int count = 0; while (key.running && count != -1) { float vol = key.volume; if (vol != setVolume) { adjustVolume(line, vol); setVolume = vol; } try { count = stream.read(buffer, 0, buffer.length); } catch (IOException e) { // this shouldn't ever ever happen because the stream // we're given is from a reliable source Log.warning("Error reading clip data! [e=" + e + "]."); return; } if (count >= 0) { line.write(buffer, 0, count); } } // if we're going to loop, reset the stream to the beginning if (key.cmd == LOOP) { stream.reset(); } } while (key.cmd == LOOP && key.running); // sleep the drain time. We never trust line.drain() because // it is buggy and locks up on natively multithreaded systems // (linux, winXP with HT). float sampleRate = format.getSampleRate(); if (sampleRate == AudioSystem.NOT_SPECIFIED) { sampleRate = 11025; // most of our sounds are } int sampleSize = format.getSampleSizeInBits(); if (sampleSize == AudioSystem.NOT_SPECIFIED) { sampleSize = 16; } int drainTime = (int) Math.ceil( (LINEBUF_SIZE * 8 * 1000) / (sampleRate * sampleSize)); // add in a fudge factor of half a second drainTime += 500; try { Thread.sleep(drainTime); } catch (InterruptedException ie) { } } catch (IOException ioe) { Log.warning("Error loading sound file [key=" + key + ", e=" + ioe + "]."); } catch (UnsupportedAudioFileException uafe) { Log.warning("Unsupported sound format [key=" + key + ", e=" + uafe + "]."); } catch (LineUnavailableException lue) { String err = "Line not available to play sound [key=" + key.key + ", e=" + lue + "]."; if (_soundSeemsToWork) { Log.warning(err); } else { // this error comes every goddamned time we play a sound on // someone with a misconfigured sound card, so let's just keep // it to ourselves Log.debug(err); } } finally { if (line != null) { line.close(); } key.thread = null; } } /** * @return true if we're using a test sound directory. */ protected boolean isTesting () { return !StringUtil.blank(_testDir.getValue()); } /** * Called by spooling threads, loads clip data from the resource * manager or the cache. */ protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { byte[][] data; boolean verbose = _verbose.getValue(); synchronized (_clipCache) { // if we're testing, clear all non-locked sounds every time if (isTesting()) { _clipCache.clear(); } data = (byte[][]) _clipCache.get(key); // see if it's in the locked cache (we first look in the regular // clip cache so that locked clips that are still cached continue // to be moved to the head of the LRU queue) if (data == null) { data = (byte[][]) _lockedClips.get(key); } if (data == null) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip(key); if (stream != null) { data = new byte[1][]; data[0] = IOUtils.toByteArray(stream); } else { // otherwise, randomize between all available sounds Config c = getConfig(key); String[] names = c.getValue(key.key, (String[])null); if (names == null) { Log.warning("No such sound [key=" + key + "]."); return null; } data = new byte[names.length][]; String bundle = c.getValue("bundle", (String)null); for (int ii=0; ii < names.length; ii++) { data[ii] = loadClipData(bundle, names[ii]); } } _clipCache.put(key, data); } } return (data.length > 0) ? data[RandomUtil.getInt(data.length)] : null; } protected InputStream getTestClip (SoundKey key) { String testDirectory = _testDir.getValue(); if (StringUtil.blank(testDirectory)) { return null; } final String namePrefix = key.key; File f = new File(testDirectory); File[] list = f.listFiles(new FilenameFilter() { public boolean accept (File f, String name) { if (name.startsWith(namePrefix)) { String backhalf = name.substring(namePrefix.length()); int dot = backhalf.indexOf('.'); if (dot == -1) { dot = backhalf.length(); } // allow the file if the portion of the name // after the prefix but before the extension is blank // or a parsable integer String extra = backhalf.substring(0, dot); if ("".equals(extra)) { return true; } else { try { Integer.parseInt(extra); // success! return true; } catch (NumberFormatException nfe) { // not a number, we fall through... } } // else fall through } return false; } }); int size = (list == null) ? 0 : list.length; if (size > 0) { File pick = list[RandomUtil.getInt(size)]; try { return new FileInputStream(pick); } catch (Exception e) { Log.warning("Error reading test sound [e=" + e + ", file=" + pick + "]."); } } return null; } /** * Read the data from the resource manager. */ protected byte[] loadClipData (String bundle, String path) throws IOException { InputStream clipin = null; try { clipin = _rmgr.getResource(bundle, path); } catch (FileNotFoundException fnfe) { // try from the classpath try { clipin = _rmgr.getResource(path); } catch (FileNotFoundException fnfe2) { // only play the default sound if we have verbose sound // debuggin turned on. if (_verbose.getValue()) { Log.warning("Could not locate sound data [bundle=" + bundle + ", path=" + path + "]."); if (_defaultClipPath != null) { try { clipin = _rmgr.getResource( _defaultClipBundle, _defaultClipPath); } catch (FileNotFoundException fnfe3) { try { clipin = _rmgr.getResource(_defaultClipPath); } catch (FileNotFoundException fnfe4) { Log.warning("Additionally, the default " + "fallback sound could not be located " + "[bundle=" + _defaultClipBundle + ", path=" + _defaultClipPath + "]."); } } } else { Log.warning("No fallback default sound specified!"); } } // if we couldn't load the default, rethrow if (clipin == null) { throw fnfe2; } } } return IOUtils.toByteArray(clipin); } /** * Get the cached Config. */ protected Config getConfig (SoundKey key) { Config c = (Config) _configs.get(key.pkgPath); if (c == null) { String propPath = key.pkgPath + Sounds.PROP_NAME; Properties props = new Properties(); try { props.load(_rmgr.getResource(propPath + ".properties")); } catch (IOException ioe) { Log.warning("Failed to load sound properties " + "[path=" + propPath + ", error=" + ioe + "]."); } c = new Config(propPath, props); _configs.put(key.pkgPath, c); } return c; } // /** // * Adjust the volume of this clip. // */ // protected static void adjustVolumeIdeally (Line line, float volume) // if (line.isControlSupported(FloatControl.Type.VOLUME)) { // FloatControl vol = (FloatControl) // line.getControl(FloatControl.Type.VOLUME); // float min = vol.getMinimum(); // float max = vol.getMaximum(); // float ourval = (volume * (max - min)) + min; // Log.debug("adjust vol: [min=" + min + ", ourval=" + ourval + // ", max=" + max + "]."); // vol.setValue(ourval); // } else { // // fall back // adjustVolume(line, volume); /** * Use the gain control to implement volume. */ protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, // which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain; if (vol == 0f) { gain = control.getMinimum(); } else { gain = (float) ((Math.log(vol) / Math.log(10.0)) * 20.0); } control.setValue(gain); //Log.info("Set gain: " + gain); } /** * A key for tracking sounds. */ protected static class SoundKey implements Frob { public byte cmd; public String pkgPath; public String key; public long stamp; /** Should we still be running? */ public volatile boolean running = true; public volatile float volume; /** The player thread, if it's playing us. */ public Thread thread; /** * Create a SoundKey that just contains the specified command. * DIE. */ public SoundKey (byte cmd) { this.cmd = cmd; } /** * Quicky constructor for music keys and lock operations. */ public SoundKey (byte cmd, String pkgPath, String key) { this(cmd); this.pkgPath = pkgPath; this.key = key; } /** * Constructor for a sound effect soundkey. */ public SoundKey (byte cmd, String pkgPath, String key, int delay, float volume) { this(cmd, pkgPath, key); stamp = System.currentTimeMillis() + delay; this.volume = volume; } // documentation inherited from interface Frob public void stop () { running = false; Thread t = thread; if (t != null) { // doesn't actually ever seem to do much t.interrupt(); } } // documentation inherited from interface Frob public void setVolume (float vol) { volume = Math.max(0f, Math.min(1f, vol)); } // documentation inherited from interface Frob public float getVolume () { return volume; } /** * Has this sound key expired. */ public boolean isExpired () { return (stamp + MAX_SOUND_DELAY < System.currentTimeMillis()); } // documentation inherited public String toString () { return "SoundKey{cmd=" + cmd + ", pkgPath=" + pkgPath + ", key=" + key + "}"; } // documentation inherited public int hashCode () { return pkgPath.hashCode() ^ key.hashCode(); } // documentation inherited public boolean equals (Object o) { if (o instanceof SoundKey) { SoundKey that = (SoundKey) o; return this.pkgPath.equals(that.pkgPath) && this.key.equals(that.key); } return false; } } /** The path of the default sound to use for missing sounds. */ protected String _defaultClipBundle, _defaultClipPath; /** The resource manager from which we obtain audio files. */ protected ResourceManager _rmgr; /** The queue of sound clips to be played. */ protected Queue _queue = new Queue(); /** The number of currently active LineSpoolers. */ protected int _spoolerCount, _freeSpoolers; /** If we every play a sound successfully, this is set to true. */ protected boolean _soundSeemsToWork = false; /** Volume level for sound clips. */ protected float _clipVol = 1f; /** The cache of recent audio clips . */ protected LRUHashMap _clipCache = new LRUHashMap(10); /** The set of locked audio clips; this is separate from the LRU so * that locking clips doesn't booch up an otherwise normal caching * agenda. */ protected HashMap _lockedClips = new HashMap(); /** A set of soundTypes for which sound is enabled. */ protected HashSet _disabledTypes = new HashSet(); /** A cache of config objects we've created. */ protected HashMap _configs = new HashMap(); /** Soundkey command constants. */ protected static final byte PLAY = 0; protected static final byte LOCK = 1; protected static final byte UNLOCK = 2; protected static final byte DIE = 3; protected static final byte LOOP = 4; /** A pref that specifies a directory for us to get test sounds from. */ protected static RuntimeAdjust.FileAdjust _testDir = new RuntimeAdjust.FileAdjust( "Test sound directory", "narya.media.sound.test_dir", MediaPrefs.config, true, ""); protected static RuntimeAdjust.BooleanAdjust _verbose = new RuntimeAdjust.BooleanAdjust( "Verbose sound event logging", "narya.media.sound.verbose", MediaPrefs.config, false); /** The queue size at which we start to ignore requests to play sounds. */ protected static final int MAX_QUEUE_SIZE = 25; /** The maximum time after which we throw away a sound rather * than play it. */ protected static final long MAX_SOUND_DELAY = 400L; /** The size of the line's buffer. */ protected static final int LINEBUF_SIZE = 8 * 1024; /** The maximum time a spooler will wait for a stream before * deciding to shut down. */ protected static final long MAX_WAIT_TIME = 30000L; /** The maximum number of spoolers we'll allow. This is a lot. */ protected static final int MAX_SPOOLERS = 12; }
// $Id: DownloadManager.java,v 1.10 2003/08/05 23:34:01 mdb Exp $ package com.threerings.resource; import java.awt.EventQueue; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import com.samskivert.util.Queue; import com.samskivert.util.StringUtil; /** * Manages the asynchronous downloading of files that are usually located * on an HTTP server but that may also be located on the local filesystem. */ public class DownloadManager { /** * Provides facilities for notifying an observer of file download * progress. */ public interface DownloadObserver { /** * If this method returns true the download observer callbacks * will be called on the AWT thread, allowing the observer to do * things like safely update user interfaces, etc. If false, it * will be called on the download thread. */ public boolean notifyOnAWTThread (); /** * Called when the download manager is about to check all * downloads to see whether they are in need of an update. */ public void resolvingDownloads (); /** * Called to inform the observer of ongoing progress toward * completion of the overall downloading task. The caller is * guaranteed to get at least one call reporting 100% completion. * * @param percent the percent completion, in terms of total file * size, of the download request. * @param remaining the estimated download time remaining in * seconds, or <code>-1</code> if the time can not yet be * determined. */ public void downloadProgress (int percent, long remaining); /** * Called on the download thread during the patching of jar files. */ public void patchingProgress (int percent); /** * Called after the download and patching has completed on the * download manager thread. */ public void postDownloadHook (); /** * Called on the preferred notification thread after the download * is complete and the post-download hook has run to completion. */ public void downloadComplete (); /** * Called if a failure occurs while checking for an update or * downloading a file. * * @param desc the file that was being downloaded when the error * occurred, or <code>null</code> if the failure occurred while * resolving downloads. * @param e the exception detailing the failure. */ public void downloadFailed (DownloadDescriptor desc, Exception e); } /** * Describes a single file to be downloaded. */ public static class DownloadDescriptor { /** The URL from which the file is to be downloaded. */ public URL sourceURL; /** The destination file to which the file is to be written. */ public File destFile; /** The version of the file to be downloaded. */ public String version; /** The last-modified timestamp of the source. */ public long lastModified; /** The last-modified timestamp of the destination file. */ public long destLastModified; /** The size in bytes of the destination file. */ public long destFileSize; /** * Constructs a download descriptor to retrieve the specified * version of the given file from the given URL. */ public DownloadDescriptor (URL url, File file, String version) { this.sourceURL = url; this.destFile = file; this.version = version; } /** * Creates the appropriate type of downloader for this descriptor. */ public Downloader createDownloader () throws IOException { String protocol = sourceURL.getProtocol(); if (protocol.equals("file")) { return new FileDownloader(); } else if (protocol.equals("http")) { return new JNLPDownloader(); } else { throw new IOException( "Unknown source file protocol " + "[protocol=" + protocol + ", desc=" + this + "]."); } } /** Returns a string representation of this instance. */ public String toString () { return StringUtil.fieldsToString(this); } } /** * Downloads the supplied list of descriptors, notifying the given * download observer of download progress and status. * * @param descriptors the list of files to be downloaded. * @param fragile if true, reports failure and ceases any further * downloading if an error occurs; else will continue attempting to * download the remainder of the descriptors. * @param downloadObs the observer to notify of progress, success and * failure. */ public void download ( List descriptors, boolean fragile, DownloadObserver downloadObs) { // add the download request to the download queue DownloadRecord dlrec = new DownloadRecord(); dlrec.descriptors = descriptors; dlrec.obs = downloadObs; dlrec.fragile = fragile; _dlqueue.append(dlrec); synchronized (this) { // if we've not yet got our downloading thread... if (_dlthread == null) { // create the thread _dlthread = new Thread() { public void run () { processDownloads(); } }; _dlthread.setDaemon(true); // and start it going _dlthread.start(); } } } /** * Called by the download thread to process all download requests in * the download queue. */ protected void processDownloads () { // create the data buffer to be used when reading files _buffer = new byte[BUFFER_SIZE]; DownloadRecord dlrec; while (true) { synchronized (this) { // kill the download thread if we have no remaining // download requests if (_dlqueue.size() == 0) { _dlthread = null; // free up the data buffer _buffer = null; return; } // pop download off the queue dlrec = (DownloadRecord)_dlqueue.getNonBlocking(); } // handle the download request processDownloadRequest(dlrec.descriptors, dlrec.obs, dlrec.fragile); } } /** * Processes a single download request. */ protected void processDownloadRequest ( List descriptors, final DownloadObserver obs, boolean fragile) { // let the observer know that we're about to resolve all files to // be downloaded if (obs.notifyOnAWTThread()) { EventQueue.invokeLater(new Runnable() { public void run () { obs.resolvingDownloads(); } }); } else { obs.resolvingDownloads(); } // check the size and last-modified information for each file to // ascertain whether our local copy needs to be refreshed ArrayList fetch = new ArrayList(); ProgressInfo pinfo = new ProgressInfo(); int size = descriptors.size(); for (int ii = 0; ii < size; ii++) { DownloadDescriptor desc = (DownloadDescriptor)descriptors.get(ii); try { Downloader loader = desc.createDownloader(); loader.init(desc); if (loader.checkUpdate(pinfo)) { fetch.add(loader); } } catch (final IOException ioe) { notifyFailed(obs, null, ioe); if (fragile) { return; } } } if (pinfo.totalSize > 0) { Log.info("Initiating download of " + pinfo.totalSize + " bytes."); } // download all stale files size = fetch.size(); pinfo.start = System.currentTimeMillis(); for (int ii = 0; ii < size; ii++) { Downloader loader = (Downloader)fetch.get(ii); try { loader.processDownload(this, obs, pinfo, _buffer); } catch (IOException ioe) { notifyFailed(obs, loader.getDescriptor(), ioe); if (fragile) { return; } } } // now go through and do the post-download phase for (int ii = 0; ii < size; ii++) { Downloader loader = (Downloader)fetch.get(ii); try { loader.postDownload(this, obs, pinfo); } catch (IOException ioe) { notifyFailed(obs, loader.getDescriptor(), ioe); if (fragile) { return; } } } // make sure to always let the observer know that we've wrapped up // by reporting 100% completion notifyProgress(obs, 100, 0L); } /** Helper function. */ protected void notifyProgress (final DownloadObserver obs, final int progress, final long remaining) { if (obs.notifyOnAWTThread()) { EventQueue.invokeLater(new Runnable() { public void run () { obs.downloadProgress(progress, remaining); } }); } else { obs.downloadProgress(progress, remaining); } if (progress == 100) { // if we're at 100%, run the post-download hook try { obs.postDownloadHook(); } catch (Exception e) { Log.warning("Observer choked in post-download hook."); Log.logStackTrace(e); } // notify of total and final download completion if (obs.notifyOnAWTThread()) { EventQueue.invokeLater(new Runnable() { public void run () { obs.downloadComplete(); } }); } else { obs.downloadComplete(); } } } /** Helper function. */ protected void notifyFailed (final DownloadObserver obs, final DownloadDescriptor desc, final Exception e) { if (obs.notifyOnAWTThread()) { EventQueue.invokeLater(new Runnable() { public void run () { obs.downloadFailed(desc, e); } }); } else { obs.downloadFailed(desc, e); } } /** * A record describing a single download request. */ protected static class DownloadRecord { /** The list of download descriptors to be downloaded. */ public List descriptors; /** The download observer to notify of download progress. */ public DownloadObserver obs; /** Whether to abort downloading if an error occurs. */ public boolean fragile; } /** The downloading thread. */ protected Thread _dlthread; /** The queue of download requests. */ protected Queue _dlqueue = new Queue(); /** The data buffer used when reading file data. */ protected byte[] _buffer; /** The data buffer size for reading file data. */ protected static final int BUFFER_SIZE = 2048; /** Indicates whether or not we're using versioned resources. */ protected static boolean VERSIONING = false; static { try { VERSIONING = "true".equalsIgnoreCase( System.getProperty("versioned_rsrcs")); } catch (Throwable t) { // no versioning, no problem } } }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.resource; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.security.AccessController; import java.security.PrivilegedAction; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import com.google.common.collect.Maps; import com.samskivert.io.StreamUtil; import com.samskivert.net.PathUtil; import com.samskivert.util.ObserverList; import com.samskivert.util.ResultListener; import com.samskivert.util.StringUtil; import com.samskivert.util.WeakObserverList; import static com.threerings.resource.Log.log; /** * The resource manager is responsible for maintaining a repository of resources that are * synchronized with a remote source. This is accomplished in the form of sets of jar files * (resource bundles) that contain resources and that are updated from a remote resource repository * via HTTP. These resource bundles are organized into resource sets. A resource set contains one * or more resource bundles and is defined much like a classpath. * * <p> The resource manager can load resources from the default resource set, and can make * available named resource sets to entities that wish to do their own resource loading. If the * resource manager fails to locate a resource in the default resource set, it falls back to * loading the resource via the classloader (which will search the classpath). * * <p> Applications that wish to make use of resource sets and their associated bundles must call * {@link #initBundles} after constructing the resource manager, providing the path to a resource * definition file which describes these resource sets. The definition file will be loaded and the * resource bundles defined within will be loaded relative to the resource directory. The bundles * will be cached in the user's home directory and only reloaded when the source resources have * been updated. The resource definition file looks something like the following: * * <pre> * resource.set.default = sets/misc/config.jar: \ * sets/misc/icons.jar * resource.set.tiles = sets/tiles/ground.jar: \ * sets/tiles/objects.jar: \ * /global/resources/tiles/ground.jar: \ * /global/resources/tiles/objects.jar * resource.set.sounds = sets/sounds/sfx.jar: \ * sets/sounds/music.jar: \ * /global/resources/sounds/sfx.jar: \ * /global/resources/sounds/music.jar * </pre> * * <p> All resource set definitions are prefixed with <code>resource.set.</code> and all text * following that string is considered to be the name of the resource set. The resource set named * <code>default</code> is the default resource set and is the one that is searched for resources * is a call to {@link #getResource}. * * <p> When a resource is loaded from a resource set, the set is searched in the order that entries * are specified in the definition. */ public class ResourceManager { /** * Provides facilities for notifying an observer of the resource unpacking process. */ public interface InitObserver { /** * Indicates a percent completion along with an estimated time remaining in seconds. */ public void progress (int percent, long remaining); /** * Indicates that there was a failure unpacking our resource bundles. */ public void initializationFailed (Exception e); } /** * An adapter that wraps an {@link InitObserver} and routes all method invocations to the AWT * thread. */ public static class AWTInitObserver implements InitObserver { public AWTInitObserver (InitObserver obs) { _obs = obs; } public void progress (final int percent, final long remaining) { EventQueue.invokeLater(new Runnable() { public void run () { _obs.progress(percent, remaining); } }); } public void initializationFailed (final Exception e) { EventQueue.invokeLater(new Runnable() { public void run () { _obs.initializationFailed(e); } }); } protected InitObserver _obs; } /** * Notifies observers of modifications to resources (as indicated by a change to their * {@link File#lastModified} property). */ public interface ModificationObserver { /** * Notes that a resource has been modified. * * @param path the path of the resource. * @param lastModified the resource's new timestamp. */ public void resourceModified (String path, long lastModified); } /** * Constructs a resource manager which will load resources via the classloader, prepending * <code>resourceRoot</code> to their path. * * @param resourceRoot the path to prepend to resource paths prior to attempting to load them * via the classloader. When resources are bundled into the default resource bundle, they don't * need this prefix, but if they're to be loaded from the classpath, it's likely that they'll * live in some sort of <code>resources</code> directory to isolate them from the rest of the * files in the classpath. This is not a platform dependent path (forward slash is always used * to separate path elements). */ public ResourceManager (String resourceRoot) { this(resourceRoot, ResourceManager.class.getClassLoader()); } /** * Creates a resource manager with the specified class loader via which to load classes. See * {@link #ResourceManager(String)} for further documentation. */ public ResourceManager (String resourceRoot, ClassLoader loader) { this(resourceRoot, null, loader); } /** * Creates a resource manager with a root path to resources over the network. See * {@link #ResourceManager(String)} for further documentation. */ public ResourceManager (String resourceRoot, String networkResourceRoot) { this(resourceRoot, networkResourceRoot, ResourceManager.class.getClassLoader()); } /** * Creates a resource manager with a root path to resources over the network and the specified * class loader via which to load classes. See {@link #ResourceManager(String)} for further * documentation. */ public ResourceManager (String fileResourceRoot, String networkResourceRoot, ClassLoader loader) { _rootPath = fileResourceRoot; _networkRootPath = networkResourceRoot; _loader = loader; // check a system property to determine if we should unpack our bundles, but don't freak // out if we fail to read it try { _unpack = !Boolean.getBoolean("no_unpack_resources"); } catch (SecurityException se) { // no problem, we're in a sandbox so we definitely won't be unpacking } // get our resource directory from resource_dir if possible initResourceDir(null); } /** * Registers a protocol handler with URL to handle <code>resource:</code> URLs. The URLs take * the form: <pre>resource://bundle_name/resource_path</pre> Resources from the default bundle * can be loaded via: <pre>resource:///resource_path</pre> */ public void activateResourceProtocol () { // set up a URL handler so that things can be loaded via urls with the 'resource' protocol try { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run () { Handler.registerHandler(ResourceManager.this); return null; } }); } catch (SecurityException se) { log.info("Running in sandbox. Unable to bind rsrc:// handler."); } } /** * Returns where we're currently looking for locale-specific resources. */ public String getLocalePrefix () { return _localePrefix; } /** * Set where we should look for locale-specific resources. */ public void setLocalePrefix (String prefix) { _localePrefix = prefix; } /** * Configures whether we unpack our resource bundles or not. This must be called before {@link * #initBundles}. One can also pass the <code>-Dno_unpack_resources=true</code> system property * to disable resource unpacking. */ public void setUnpackResources (boolean unpackResources) { _unpack = unpackResources; } /** * Initializes the bundle sets to be made available by this resource manager. Applications * that wish to make use of resource bundles should call this method after constructing the * resource manager. * * @param resourceDir the base directory to which the paths in the supplied configuration file * are relative. If this is null, the system property <code>resource_dir</code> will be used, * if available. * @param configPath the path (relative to the resource dir) of the resource definition file. * @param initObs a bundle initialization observer to notify of unpacking progress and success * or failure, or <code>null</code> if the caller doesn't care to be informed; note that in the * latter case, the calling thread will block until bundle unpacking is complete. * * @exception IOException thrown if we are unable to read our resource manager configuration. */ public void initBundles (String resourceDir, String configPath, InitObserver initObs) throws IOException { // reinitialize our resource dir if it was specified if (resourceDir != null) { initResourceDir(resourceDir); } // load up our configuration Properties config = loadConfig(configPath); // resolve the configured resource sets List<ResourceBundle> dlist = new ArrayList<ResourceBundle>(); Enumeration<?> names = config.propertyNames(); while (names.hasMoreElements()) { String key = (String)names.nextElement(); if (!key.startsWith(RESOURCE_SET_PREFIX)) { continue; } String setName = key.substring(RESOURCE_SET_PREFIX.length()); String resourceSetType = config.getProperty(RESOURCE_SET_TYPE_PREFIX + setName, FILE_SET_TYPE); resolveResourceSet(setName, config.getProperty(key), resourceSetType, dlist); } // if an observer was passed in, then we do not need to block the caller final boolean[] shouldWait = new boolean[] { false }; if (initObs == null) { // if there's no observer, we'll need to block the caller shouldWait[0] = true; initObs = new InitObserver() { public void progress (int percent, long remaining) { if (percent >= 100) { synchronized (this) { // turn off shouldWait, in case we reached 100% progress before the // calling thread even gets a chance to get to the blocking code, below shouldWait[0] = false; notify(); } } } public void initializationFailed (Exception e) { synchronized (this) { shouldWait[0] = false; notify(); } } }; } // start a thread to unpack our bundles Unpacker unpack = new Unpacker(dlist, initObs); unpack.start(); if (shouldWait[0]) { synchronized (initObs) { if (shouldWait[0]) { try { initObs.wait(); } catch (InterruptedException ie) { log.warning("Interrupted while waiting for bundles to unpack."); } } } } } /** * (Re)initializes the directory to search for resource files. * * @param resourceDir the directory path, or <code>null</code> to set the resource dir to * the value of the <code>resource_dir</code> system property. */ public void initResourceDir (String resourceDir) { // if none was specified, check the resource_dir system property if (resourceDir == null) { try { resourceDir = System.getProperty("resource_dir"); } catch (SecurityException se) { // no problem } } // if we found no resource directory, don't use one if (resourceDir == null) { return; } // make sure there's a trailing slash if (!resourceDir.endsWith(File.separator)) { resourceDir += File.separator; } _rdir = new File(resourceDir); } /** * Given a path relative to the resource directory, the path is properly jimmied (assuming we * always use /) and combined with the resource directory to yield a {@link File} object that * can be used to access the resource. * * @return a file referencing the specified resource or null if the resource manager was never * configured with a resource directory. */ public File getResourceFile (String path) { if (_rdir == null) { return null; } if (!"/".equals(File.separator)) { path = StringUtil.replace(path, "/", File.separator); } return new File(_rdir, path); } /** * Given a file within the resource directory, returns a resource path that can be passed to * {@link #getResourceFile} to locate the resource. * * @return a path referencing the specified resource or null if either the resource manager * was never configured with a resource directory or the file is not contained within the * resource directory. */ public String getResourcePath (File file) { if (_rdir == null) { return null; } try { String parent = _rdir.getCanonicalPath(); if (!parent.endsWith(File.separator)) { parent += File.separator; } String child = file.getCanonicalPath(); if (!child.startsWith(parent)) { return null; } String path = child.substring(parent.length()); return (File.separatorChar == '/') ? path : path.replace(File.separatorChar, '/'); } catch (IOException e) { log.warning("Failed to determine resource path [file=" + file + "].", e); return null; } } /** * Checks to see if the specified bundle exists, is unpacked and is ready to be used. */ public boolean checkBundle (String path) { File bfile = getResourceFile(path); return (bfile == null) ? false : new FileResourceBundle(bfile, true, _unpack).isUnpacked(); } /** * Resolve the specified bundle (the bundle file must already exist in the appropriate place on * the file system) and return it on the specified result listener. Note that the result * listener may be notified before this method returns on the caller's thread if the bundle is * already resolved, or it may be notified on a brand new thread if the bundle requires * unpacking. */ public void resolveBundle (String path, final ResultListener<FileResourceBundle> listener) { File bfile = getResourceFile(path); if (bfile == null) { String errmsg = "ResourceManager not configured with resource directory."; listener.requestFailed(new IOException(errmsg)); return; } final FileResourceBundle bundle = new FileResourceBundle(bfile, true, _unpack); if (bundle.isUnpacked()) { if (bundle.sourceIsReady()) { listener.requestCompleted(bundle); } else { String errmsg = "Bundle initialization failed."; listener.requestFailed(new IOException(errmsg)); } return; } // start a thread to unpack our bundles ArrayList<ResourceBundle> list = new ArrayList<ResourceBundle>(); list.add(bundle); Unpacker unpack = new Unpacker(list, new InitObserver() { public void progress (int percent, long remaining) { if (percent == 100) { listener.requestCompleted(bundle); } } public void initializationFailed (Exception e) { listener.requestFailed(e); } }); unpack.start(); } /** * Returns the class loader being used to load resources if/when there are no resource bundles * from which to load them. */ public ClassLoader getClassLoader () { return _loader; } /** * Configures the class loader this manager should use to load resources if/when there are no * bundles from which to load them. */ public void setClassLoader (ClassLoader loader) { _loader = loader; } /** * Fetches a resource from the local repository. * * @param path the path to the resource (ie. "config/miso.properties"). This should not begin * with a slash. * * @exception IOException thrown if a problem occurs locating or reading the resource. */ public InputStream getResource (String path) throws IOException { InputStream in = null; // first look for this resource in our default resource bundle for (ResourceBundle bundle : _default) { // Try a localized version first. if (_localePrefix != null) { in = bundle.getResource(PathUtil.appendPath(_localePrefix, path)); } // If that didn't work, try generic. if (in == null) { in = bundle.getResource(path); } if (in != null) { return in; } } // fallback next to an unpacked resource file File file = getResourceFile(path); if (file != null && file.exists()) { return new FileInputStream(file); } // if we still didn't find anything, try the classloader; first try a locale-specific file if (_localePrefix != null) { final String rpath = PathUtil.appendPath( _rootPath, PathUtil.appendPath(_localePrefix, path)); in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return in; } } // if we didn't find that, try locale-neutral final String rpath = PathUtil.appendPath(_rootPath, path); in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return in; } // if we still haven't found it, we throw an exception String errmsg = "Unable to locate resource [path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Fetches and decodes the specified resource into a {@link BufferedImage}. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public BufferedImage getImageResource (String path) throws IOException { // first look for this resource in our default resource bundle for (ResourceBundle bundle : _default) { // try a localized version first BufferedImage image = null; if (_localePrefix != null) { image = bundle.getImageResource(PathUtil.appendPath(_localePrefix, path), false); } // if we didn't find that, try generic if (image == null) { image = bundle.getImageResource(path, false); } if (image != null) { return image; } } // fallback next to an unpacked resource file File file = getResourceFile(path); if (file != null && file.exists()) { return loadImage(file, path.endsWith(FastImageIO.FILE_SUFFIX)); } // first try a locale-specific file if (_localePrefix != null) { final String rpath = PathUtil.appendPath( _rootPath, PathUtil.appendPath(_localePrefix, path)); InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return loadImage(in); } } // if we still didn't find anything, try the classloader final String rpath = PathUtil.appendPath(_rootPath, path); InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return loadImage(in); } // if we still haven't found it, we throw an exception String errmsg = "Unable to locate image resource [path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Returns an input stream from which the requested resource can be loaded. <em>Note:</em> this * performs a linear search of all of the bundles in the set and returns the first resource * found with the specified path, thus it is not extremely efficient and will behave * unexpectedly if you use the same paths in different resource bundles. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public InputStream getResource (String rset, String path) throws IOException { // grab the resource bundles in the specified resource set ResourceBundle[] bundles = getResourceSet(rset); if (bundles == null) { throw new FileNotFoundException( "Unable to locate resource [set=" + rset + ", path=" + path + "]"); } // look for the resource in any of the bundles int size = bundles.length; for (int ii = 0; ii < size; ii++) { InputStream instr = null; // Try a localized version first. if (_localePrefix != null) { instr = bundles[ii].getResource(PathUtil.appendPath(_localePrefix, path)); } // If we didn't find that, try a generic. if (instr == null) { instr = bundles[ii].getResource(path); } if (instr != null) { // Log.info("Found resource [rset=" + rset + // ", bundle=" + bundles[ii].getSource().getPath() + // ", path=" + path + ", in=" + instr + "]."); return instr; } } throw new FileNotFoundException( "Unable to locate resource [set=" + rset + ", path=" + path + "]"); } /** * Fetches and decodes the specified resource into a {@link BufferedImage}. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public BufferedImage getImageResource (String rset, String path) throws IOException { // grab the resource bundles in the specified resource set ResourceBundle[] bundles = getResourceSet(rset); if (bundles == null) { throw new FileNotFoundException( "Unable to locate image resource [set=" + rset + ", path=" + path + "]"); } // look for the resource in any of the bundles int size = bundles.length; for (int ii = 0; ii < size; ii++) { BufferedImage image = null; // try a localized version first if (_localePrefix != null) { image = bundles[ii].getImageResource(PathUtil.appendPath(_localePrefix, path), false); } // if we didn't find that, try generic if (image == null) { image = bundles[ii].getImageResource(path, false); } if (image != null) { // Log.info("Found image resource [rset=" + rset + // ", bundle=" + bundles[ii].getSource() + ", path=" + path + "]."); return image; } } String errmsg = "Unable to locate image resource [set=" + rset + ", path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Returns a reference to the resource set with the specified name, or null if no set exists * with that name. Services that wish to load their own resources can allow the resource * manager to load up a resource set for them, from which they can easily load their resources. */ public ResourceBundle[] getResourceSet (String name) { return _sets.get(name); } /** * Adds a modification observer for the specified resource. Note that only a weak reference to * the observer will be retained, and thus this will not prevent the observer from being * garbage-collected. */ public void addModificationObserver (String path, ModificationObserver obs) { ObservedResource resource = _observed.get(path); if (resource == null) { File file = getResourceFile(path); if (file == null) { return; // only resource files will ever be modified } _observed.put(path, resource = new ObservedResource(file)); } resource.observers.add(obs); } /** * Removes a modification observer from the list maintained for the specified resource. */ public void removeModificationObserver (String path, ModificationObserver obs) { ObservedResource resource = _observed.get(path); if (resource != null) { resource.observers.remove(obs); } } /** * Checks all observed resources for changes to their {@link File#lastModified} properties, * notifying their listeners if the files have been modified since the last call to this * method. */ public void checkForModifications () { for (Iterator<Map.Entry<String, ObservedResource>> it = _observed.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, ObservedResource> entry = it.next(); ObservedResource resource = entry.getValue(); if (resource.checkForModification(entry.getKey())) { it.remove(); } } } /** * Loads the configuration properties for our resource sets. */ protected Properties loadConfig (String configPath) throws IOException { Properties config = new Properties(); try { config.load(new FileInputStream(new File(_rdir, configPath))); } catch (Exception e) { String errmsg = "Unable to load resource manager config [rdir=" + _rdir + ", cpath=" + configPath + "]"; log.warning(errmsg + ".", e); throw new IOException(errmsg); } return config; } /** * If we have a full list of the resources available, we return it. A return value of null * means that we do not know what's available and we'll have to try all possibilities. This * is fine for most applications. */ public HashSet<String> getResourceList () { return null; } /** * Loads up a resource set based on the supplied definition information. */ protected void resolveResourceSet ( String setName, String definition, String setType, List<ResourceBundle> dlist) { List<ResourceBundle> set = new ArrayList<ResourceBundle>(); StringTokenizer tok = new StringTokenizer(definition, ":"); while (tok.hasMoreTokens()) { set.add(createResourceBundle(setType, tok.nextToken().trim(), dlist)); } // convert our array list into an array and stick it in the table ResourceBundle[] setvec = set.toArray(new ResourceBundle[set.size()]); _sets.put(setName, setvec); // if this is our default resource bundle, keep a reference to it if (DEFAULT_RESOURCE_SET.equals(setName)) { _default = setvec; } } /** * Creates a ResourceBundle based on the supplied definition information. */ protected ResourceBundle createResourceBundle (String setType, String path, List<ResourceBundle> dlist) { if (setType.equals(FILE_SET_TYPE)) { FileResourceBundle bundle = createFileResourceBundle(getResourceFile(path), true, _unpack); if (!bundle.isUnpacked() || !bundle.sourceIsReady()) { dlist.add(bundle); } return bundle; } else if (setType.equals(NETWORK_SET_TYPE)) { return createNetworkResourceBundle(_networkRootPath, path, getResourceList()); } else { throw new IllegalArgumentException("Unknown set type: " + setType); } } /** * Creates an appropriate bundle for fetching resources from files. */ protected FileResourceBundle createFileResourceBundle( File source, boolean delay, boolean unpack) { return new FileResourceBundle(source, delay, unpack); } /** * Creates an appropriate bundle for fetching resources from the network. */ protected NetworkResourceBundle createNetworkResourceBundle( String root, String path, HashSet<String> rsrcList) { return new NetworkResourceBundle(root, path, rsrcList); } /** * Loads an image from the supplied file. Supports {@link FastImageIO} files and formats * supported by {@link ImageIO} and will load the appropriate one based on the useFastIO param. */ protected static BufferedImage loadImage (File file, boolean useFastIO) throws IOException { if (file == null) { return null; } else if (useFastIO) { return FastImageIO.read(file); } else { return ImageIO.read(file); } } /** * Loads an image from the supplied input stream. Supports formats supported by {@link ImageIO} * but not {@link FastImageIO}. */ protected static BufferedImage loadImage (InputStream iis) throws IOException { BufferedImage image; // Java 1.4.2 and below can't deal with the MemoryCacheImageInputStream without throwing // a hissy fit. if (iis instanceof ImageInputStream || getNumericJavaVersion(System.getProperty("java.version")) < getNumericJavaVersion("1.5.0")) { image = ImageIO.read(iis); } else { // if we don't already have an image input stream, create a memory cache image input // stream to avoid causing freakout if we're used in a sandbox because ImageIO // otherwise use FileCacheImageInputStream which tries to create a temp file MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(iis); image = ImageIO.read(mciis); try { // this doesn't close the underlying stream mciis.close(); } catch (IOException ioe) { // ImageInputStreamImpl.close() throws an IOException if it's already closed; // there's no way to find out if it's already closed or not, so we have to check // the exception message to determine if this is actually warning worthy if (!"closed".equals(ioe.getMessage())) { log.warning("Failure closing image input '" + iis + "'.", ioe); } } } // finally close our input stream StreamUtil.close(iis); return image; } /** * Converts the java version string to a more comparable numeric version number. */ protected static int getNumericJavaVersion (String verstr) { Matcher m = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(_\\d+)?.*").matcher(verstr); if (!m.matches()) { // if we can't parse the java version we're in weird land and should probably just try // our luck with what we've got rather than try to download a new jvm log.warning("Unable to parse VM version, hoping for the best [version=" + verstr + "]"); return 0; } int one = Integer.parseInt(m.group(1)); // will there ever be a two? int major = Integer.parseInt(m.group(2)); int minor = Integer.parseInt(m.group(3)); int patch = m.group(4) == null ? 0 : Integer.parseInt(m.group(4).substring(1)); return patch + 100 * (minor + 100 * (major + 100 * one)); } /** Used to unpack bundles on a separate thread. */ protected static class Unpacker extends Thread { public Unpacker (List<ResourceBundle> bundles, InitObserver obs) { _bundles = bundles; _obs = obs; } @Override public void run () { try { // Tell the observer were starting if (_obs != null) { _obs.progress(0, 1); } int count = 0; for (ResourceBundle bundle : _bundles) { if (bundle instanceof FileResourceBundle && !((FileResourceBundle)bundle).sourceIsReady()) { log.warning("Bundle failed to initialize " + bundle + "."); } if (_obs != null) { int pct = count*100/_bundles.size(); if (pct < 100) { _obs.progress(pct, 1); } } count++; } if (_obs != null) { _obs.progress(100, 0); } } catch (Exception e) { if (_obs != null) { _obs.initializationFailed(e); } } } protected List<ResourceBundle> _bundles; protected InitObserver _obs; } /** Contains the state of an observed file resource. */ protected static class ObservedResource { /** The observers listening for modifications to this resource. */ public WeakObserverList<ModificationObserver> observers = WeakObserverList.newFastUnsafe(); public ObservedResource (File file) { _file = file; _lastModified = file.lastModified(); } /** * Checks for a modification to the observed resource, notifying the observers if * one is detected. * * @param path the path of the resource (to forward to observers). * @return <code>true</code> if the list of observers is empty and the resource should be * removed from the observed list, <code>false</code> if it should remain in the list. */ public boolean checkForModification (String path) { long newLastModified = _file.lastModified(); if (newLastModified > _lastModified) { _resourceModifiedOp.init(path, _lastModified = newLastModified); observers.apply(_resourceModifiedOp); } else { // remove any observers that have been garbage-collected observers.prune(); } return observers.isEmpty(); } protected File _file; protected long _lastModified; } /** An observer op that calls {@link ModificationObserver#resourceModified}. */ protected static class ResourceModifiedOp implements ObserverList.ObserverOp<ModificationObserver> { public void init (String path, long lastModified) { _path = path; _lastModified = lastModified; } // documentation inherited from interface ObserverOp public boolean apply (ModificationObserver obs) { obs.resourceModified(_path, _lastModified); return true; } protected String _path; protected long _lastModified; } /** The classloader we use for classpath-based resource loading. */ protected ClassLoader _loader; /** The directory that contains our resource bundles. */ protected File _rdir; /** The prefix we prepend to resource paths before attempting to load them from the * classpath. */ protected String _rootPath; /** The root path we give to network bundles for all resources they're interested in. */ protected String _networkRootPath; /** Whether or not to unpack our resource bundles. */ protected boolean _unpack; /** Our default resource set. */ protected ResourceBundle[] _default = new ResourceBundle[0]; /** A table of our resource sets. */ protected HashMap<String, ResourceBundle[]> _sets = Maps.newHashMap(); /** Locale to search for locale-specific resources, if any. */ protected String _localePrefix = null; /** Maps resource paths to observed file resources. */ protected HashMap<String, ObservedResource> _observed = Maps.newHashMap(); /** A reusable instance of {@link ResourceModifiedOp}. */ protected static ResourceModifiedOp _resourceModifiedOp = new ResourceModifiedOp(); /** The prefix of configuration entries that describe a resource set. */ protected static final String RESOURCE_SET_PREFIX = "resource.set."; /** The prefix of configuration entries that describe a resource set. */ protected static final String RESOURCE_SET_TYPE_PREFIX = "resource.set_type."; /** The name of the default resource set. */ protected static final String DEFAULT_RESOURCE_SET = "default"; /** Resource set type indicating the resources should be loaded from local files. */ protected static final String FILE_SET_TYPE = "file"; /** Resource set type indicating the resources should be loaded over the network. */ protected static final String NETWORK_SET_TYPE = "network"; }
package jdbc_adapter; import java.io.IOException; import java.io.Reader; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.sql.Types; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.RubyHash; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.RubyObjectAdapter; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.RubyTime; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.Java; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.javasupport.JavaObject; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.load.BasicLibraryService; import org.jruby.util.ByteList; public class JdbcAdapterInternalService implements BasicLibraryService { private static RubyObjectAdapter rubyApi; public boolean basicLoad(final Ruby runtime) throws IOException { RubyModule jdbcConnection = ((RubyModule)(runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters"))). defineClassUnder("JdbcConnection",runtime.getObject(),runtime.getObject().getAllocator()); jdbcConnection.defineAnnotatedMethods(JdbcAdapterInternalService.class); RubyModule jdbcSpec = runtime.getOrCreateModule("JdbcSpec"); rubyApi = JavaEmbedUtils.newObjectAdapter(); JdbcMySQLSpec.load(jdbcSpec); JdbcDerbySpec.load(jdbcSpec, rubyApi); return true; } private static int whitespace(int p, final int pend, ByteList bl) { while(p < pend) { switch(bl.bytes[p]) { case ' ': case '\n': case '\r': case '\t': p++; break; default: return p; } } return p; } @JRubyMethod(name = "insert?", required = 1, meta = true) public static IRubyObject insert_p(IRubyObject recv, IRubyObject _sql) { ByteList bl = rubyApi.convertToRubyString(_sql).getByteList(); int p = bl.begin; int pend = p + bl.realSize; p = whitespace(p, pend, bl); if(pend - p >= 6) { switch(bl.bytes[p++]) { case 'i': case 'I': switch(bl.bytes[p++]) { case 'n': case 'N': switch(bl.bytes[p++]) { case 's': case 'S': switch(bl.bytes[p++]) { case 'e': case 'E': switch(bl.bytes[p++]) { case 'r': case 'R': switch(bl.bytes[p++]) { case 't': case 'T': return recv.getRuntime().getTrue(); } } } } } } } return recv.getRuntime().getFalse(); } @JRubyMethod(name = "select?", required = 1, meta = true) public static IRubyObject select_p(IRubyObject recv, IRubyObject _sql) { ByteList bl = rubyApi.convertToRubyString(_sql).getByteList(); int p = bl.begin; int pend = p + bl.realSize; p = whitespace(p, pend, bl); if(pend - p >= 6) { if(bl.bytes[p] == '(') { p++; p = whitespace(p, pend, bl); } if(pend - p >= 6) { switch(bl.bytes[p++]) { case 's': case 'S': switch(bl.bytes[p++]) { case 'e': case 'E': switch(bl.bytes[p++]) { case 'l': case 'L': switch(bl.bytes[p++]) { case 'e': case 'E': switch(bl.bytes[p++]) { case 'c': case 'C': switch(bl.bytes[p++]) { case 't': case 'T': return recv.getRuntime().getTrue(); } } } } case 'h': case 'H': switch(bl.bytes[p++]) { case 'o': case 'O': switch(bl.bytes[p++]) { case 'w': case 'W': return recv.getRuntime().getTrue(); } } } } } } return recv.getRuntime().getFalse(); } @JRubyMethod(name = "connection") public static IRubyObject connection(IRubyObject recv) { Connection c = getConnection(recv); if (c == null) { reconnect(recv); } return rubyApi.getInstanceVariable(recv, "@connection"); } @JRubyMethod(name = "disconnect!") public static IRubyObject disconnect(IRubyObject recv) { setConnection(recv, null); return recv; } @JRubyMethod(name = "reconnect!") public static IRubyObject reconnect(IRubyObject recv) { setConnection(recv, getConnectionFactory(recv).newConnection()); return recv; } @JRubyMethod(name = "with_connection_retry_guard", frame = true) public static IRubyObject with_connection_retry_guard(final IRubyObject recv, final Block block) { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { return block.call(recv.getRuntime().getCurrentContext(), new IRubyObject[] { wrappedConnection(recv, c) }); } }); } private static IRubyObject withConnectionAndRetry(IRubyObject recv, SQLBlock block) { int tries = 1; int i = 0; Throwable toWrap = null; while (i < tries) { Connection c = getConnection(recv); try { return block.call(c); } catch (Exception e) { toWrap = e; while (toWrap.getCause() != null && toWrap.getCause() != toWrap) { toWrap = toWrap.getCause(); } if (i == 0) { tries = (int) rubyApi.convertToRubyInteger(config_value(recv, "retry_count")).getLongValue(); if (tries <= 0) { tries = 1; } } i++; if (isConnectionBroken(recv, c)) { reconnect(recv); } else { throw wrap(recv, toWrap); } } } throw wrap(recv, toWrap); } private static SQLBlock tableLookupBlock(final Ruby runtime, final String catalog, final String schemapat, final String tablepat, final String[] types) { return new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { ResultSet rs = null; try { DatabaseMetaData metadata = c.getMetaData(); String clzName = metadata.getClass().getName().toLowerCase(); boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1; String realschema = schemapat; if (realschema == null && isOracle) { ResultSet schemas = metadata.getSchemas(); String username = metadata.getUserName(); while (schemas.next()) { if (schemas.getString(1).equalsIgnoreCase(username)) { realschema = schemas.getString(1); break; } } schemas.close(); } rs = metadata.getTables(catalog, realschema, tablepat, types); List arr = new ArrayList(); while (rs.next()) { String name = rs.getString(3).toLowerCase(); // Handle stupid Oracle 10g RecycleBin feature if (!isOracle || !name.startsWith("bin$")) { arr.add(RubyString.newUnicodeString(runtime, name)); } } return runtime.newArray(arr); } finally { try { rs.close(); } catch (Exception e) { } } } }; } @JRubyMethod(name = "tables", rest = true) public static IRubyObject tables(final IRubyObject recv, IRubyObject[] args) { final Ruby runtime = recv.getRuntime(); final String catalog = getCatalog(args); final String schemapat = getSchemaPattern(args); final String tablepat = getTablePattern(args); final String[] types = getTypes(args); return withConnectionAndRetry(recv, tableLookupBlock(runtime, catalog, schemapat, tablepat, types)); } private static String getCatalog(IRubyObject[] args) { if (args != null && args.length > 0) { return convertToStringOrNull(args[0]); } return null; } private static String getSchemaPattern(IRubyObject[] args) { if (args != null && args.length > 1) { return convertToStringOrNull(args[1]); } return null; } private static String getTablePattern(IRubyObject[] args) { if (args != null && args.length > 2) { return convertToStringOrNull(args[2]); } return null; } private static String[] getTypes(IRubyObject[] args) { String[] types = new String[]{"TABLE"}; if (args != null && args.length > 3) { IRubyObject typearr = args[3]; if (typearr instanceof RubyArray) { IRubyObject[] arr = rubyApi.convertToJavaArray(typearr); types = new String[arr.length]; for (int i = 0; i < types.length; i++) { types[i] = arr[i].toString(); } } else { types = new String[]{types.toString()}; } } return types; } @JRubyMethod(name = "native_database_types") public static IRubyObject native_database_types(IRubyObject recv) { return rubyApi.getInstanceVariable(recv, "@tps"); } @JRubyMethod(name = "set_native_database_types") public static IRubyObject set_native_database_types(IRubyObject recv) throws SQLException, IOException { Ruby runtime = recv.getRuntime(); IRubyObject types = unmarshal_result_downcase(recv, getConnection(recv).getMetaData().getTypeInfo()); IRubyObject typeConverter = ((RubyModule) (runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters"))).getConstant("JdbcTypeConverter"); IRubyObject value = rubyApi.callMethod(rubyApi.callMethod(typeConverter, "new", types), "choose_best_types"); rubyApi.setInstanceVariable(recv, "@native_types", value); return runtime.getNil(); } @JRubyMethod(name = "database_name") public static IRubyObject database_name(IRubyObject recv) throws SQLException { String name = getConnection(recv).getCatalog(); if(null == name) { name = getConnection(recv).getMetaData().getUserName(); if(null == name) { name = "db1"; } } return recv.getRuntime().newString(name); } @JRubyMethod(name = "begin") public static IRubyObject begin(IRubyObject recv) throws SQLException { getConnection(recv).setAutoCommit(false); return recv.getRuntime().getNil(); } @JRubyMethod(name = "commit") public static IRubyObject commit(IRubyObject recv) throws SQLException { try { getConnection(recv).commit(); return recv.getRuntime().getNil(); } finally { getConnection(recv).setAutoCommit(true); } } @JRubyMethod(name = "rollback") public static IRubyObject rollback(IRubyObject recv) throws SQLException { try { getConnection(recv).rollback(); return recv.getRuntime().getNil(); } finally { getConnection(recv).setAutoCommit(true); } } @JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2) public static IRubyObject columns_internal(final IRubyObject recv, final IRubyObject[] args) throws SQLException, IOException { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { ResultSet results = null; try { String table_name = rubyApi.convertToRubyString(args[0]).getUnicodeValue(); String schemaName = null; if(table_name.indexOf(".") != -1) { schemaName = table_name.substring(table_name.indexOf(".")+1); table_name = table_name.substring(0, table_name.indexOf(".")+1); } DatabaseMetaData metadata = c.getMetaData(); String clzName = metadata.getClass().getName().toLowerCase(); boolean isDerby = clzName.indexOf("derby") != -1; boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1; if(args.length>2) { schemaName = args[2].toString(); } if(metadata.storesUpperCaseIdentifiers()) { table_name = table_name.toUpperCase(); } else if(metadata.storesLowerCaseIdentifiers()) { table_name = table_name.toLowerCase(); } if(schemaName == null && (isDerby || isOracle)) { ResultSet schemas = metadata.getSchemas(); String username = metadata.getUserName(); while(schemas.next()) { if(schemas.getString(1).equalsIgnoreCase(username)) { schemaName = schemas.getString(1); break; } } schemas.close(); } RubyArray matchingTables = (RubyArray) tableLookupBlock(recv.getRuntime(), c.getCatalog(), schemaName, table_name, new String[]{"TABLE","VIEW"}).call(c); if (matchingTables.isEmpty()) { throw new SQLException("Table " + table_name + " does not exist"); } results = metadata.getColumns(c.getCatalog(),schemaName,table_name,null); return unmarshal_columns(recv, metadata, results); } finally { try { if (results != null) results.close(); } catch (SQLException sqx) {} } } }); } private static final java.util.regex.Pattern HAS_SMALL = java.util.regex.Pattern.compile("[a-z]"); private static IRubyObject unmarshal_columns(IRubyObject recv, DatabaseMetaData metadata, ResultSet rs) throws SQLException { try { List columns = new ArrayList(); String clzName = metadata.getClass().getName().toLowerCase(); boolean isDerby = clzName.indexOf("derby") != -1; boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1; Ruby runtime = recv.getRuntime(); IRubyObject adapter = rubyApi.callMethod(recv, "adapter"); RubyHash tps = (RubyHash) rubyApi.callMethod(adapter, "native_database_types"); IRubyObject jdbcCol = ((RubyModule)(runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters"))).getConstant("JdbcColumn"); while(rs.next()) { String column_name = rs.getString(4); if(metadata.storesUpperCaseIdentifiers() && !HAS_SMALL.matcher(column_name).find()) { column_name = column_name.toLowerCase(); } String prec = rs.getString(7); String scal = rs.getString(9); int precision = -1; int scale = -1; if(prec != null) { precision = Integer.parseInt(prec); if(scal != null) { scale = Integer.parseInt(scal); } } String type = rs.getString(6); if(prec != null && precision > 0) { type += "(" + precision; if(scal != null && scale > 0) { type += "," + scale; } type += ")"; } String def = rs.getString(13); IRubyObject _def; if(def == null || (isOracle && def.toLowerCase().trim().equals("null"))) { _def = runtime.getNil(); } else { if(isOracle) { def = def.trim(); } if((isDerby || isOracle) && def.length() > 0 && def.charAt(0) == '\'') { def = def.substring(1, def.length()-1); } _def = RubyString.newUnicodeString(runtime, def); } IRubyObject config = rubyApi.getInstanceVariable(recv, "@config"); IRubyObject c = rubyApi.callMethod(jdbcCol, "new", new IRubyObject[]{ config, RubyString.newUnicodeString(runtime, column_name), _def, RubyString.newUnicodeString(runtime, type), runtime.newBoolean(!rs.getString(18).trim().equals("NO")) }); columns.add(c); IRubyObject tp = (IRubyObject)tps.fastARef(rubyApi.callMethod(c,"type")); if(tp != null && !tp.isNil() && rubyApi.callMethod(tp, "[]", runtime.newSymbol("limit")).isNil()) { rubyApi.callMethod(c, "limit=", runtime.getNil()); if(!rubyApi.callMethod(c, "type").equals(runtime.newSymbol("decimal"))) { rubyApi.callMethod(c, "precision=", runtime.getNil()); } } } return runtime.newArray(columns); } finally { try { rs.close(); } catch(Exception e) {} } } @JRubyMethod(name = "primary_keys", required = 1) public static IRubyObject primary_keys(final IRubyObject recv, final IRubyObject _table_name) throws SQLException { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { DatabaseMetaData metadata = c.getMetaData(); String table_name = _table_name.toString(); if (metadata.storesUpperCaseIdentifiers()) { table_name = table_name.toUpperCase(); } else if (metadata.storesLowerCaseIdentifiers()) { table_name = table_name.toLowerCase(); } ResultSet result_set = metadata.getPrimaryKeys(null, null, table_name); List keyNames = new ArrayList(); Ruby runtime = recv.getRuntime(); while (result_set.next()) { String s1 = result_set.getString(4); if (metadata.storesUpperCaseIdentifiers() && !HAS_SMALL.matcher(s1).find()) { s1 = s1.toLowerCase(); } keyNames.add(RubyString.newUnicodeString(runtime,s1)); } try { result_set.close(); } catch (Exception e) { } return runtime.newArray(keyNames); } }); } @JRubyMethod(name = "execute_id_insert", required = 2) public static IRubyObject execute_id_insert(IRubyObject recv, final IRubyObject sql, final IRubyObject id) throws SQLException { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { PreparedStatement ps = c.prepareStatement(rubyApi.convertToRubyString(sql).getUnicodeValue()); try { ps.setLong(1, RubyNumeric.fix2long(id)); ps.executeUpdate(); } finally { ps.close(); } return id; } }); } @JRubyMethod(name = "execute_update", required = 1) public static IRubyObject execute_update(final IRubyObject recv, final IRubyObject sql) throws SQLException { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { Statement stmt = null; try { stmt = c.createStatement(); return recv.getRuntime().newFixnum(stmt.executeUpdate(rubyApi.convertToRubyString(sql).getUnicodeValue())); } finally { if (null != stmt) { try { stmt.close(); } catch (Exception e) { } } } } }); } @JRubyMethod(name = "execute_query", rest = true) public static IRubyObject execute_query(final IRubyObject recv, IRubyObject[] args) throws SQLException, IOException { final IRubyObject sql = args[0]; final int maxrows; if (args.length > 1) { maxrows = RubyNumeric.fix2int(args[1]); } else { maxrows = 0; } return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { Statement stmt = null; try { stmt = c.createStatement(); stmt.setMaxRows(maxrows); return unmarshal_result(recv, stmt.executeQuery(rubyApi.convertToRubyString(sql).getUnicodeValue())); } finally { if (null != stmt) { try { stmt.close(); } catch (Exception e) { } } } } }); } @JRubyMethod(name = "execute_insert", required = 1) public static IRubyObject execute_insert(final IRubyObject recv, final IRubyObject sql) throws SQLException { return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { Statement stmt = null; try { stmt = c.createStatement(); stmt.executeUpdate(rubyApi.convertToRubyString(sql).getUnicodeValue(), Statement.RETURN_GENERATED_KEYS); return unmarshal_id_result(recv.getRuntime(), stmt.getGeneratedKeys()); } finally { if (null != stmt) { try { stmt.close(); } catch (Exception e) { } } } } }); } public static IRubyObject unmarshal_result_downcase(IRubyObject recv, ResultSet rs) throws SQLException, IOException { List results = new ArrayList(); Ruby runtime = recv.getRuntime(); try { ResultSetMetaData metadata = rs.getMetaData(); int col_count = metadata.getColumnCount(); IRubyObject[] col_names = new IRubyObject[col_count]; int[] col_types = new int[col_count]; int[] col_scale = new int[col_count]; for(int i=0;i<col_count;i++) { col_names[i] = RubyString.newUnicodeString(runtime, metadata.getColumnLabel(i+1).toLowerCase()); col_types[i] = metadata.getColumnType(i+1); col_scale[i] = metadata.getScale(i+1); } while(rs.next()) { RubyHash row = RubyHash.newHash(runtime); for(int i=0;i<col_count;i++) { rubyApi.callMethod(row, "[]=", new IRubyObject[] { col_names[i], jdbc_to_ruby(runtime, i+1, col_types[i], col_scale[i], rs) }); } results.add(row); } } finally { try { rs.close(); } catch(Exception e) {} } return runtime.newArray(results); } public static IRubyObject unmarshal_result(IRubyObject recv, ResultSet rs) throws SQLException { Ruby runtime = recv.getRuntime(); List results = new ArrayList(); try { ResultSetMetaData metadata = rs.getMetaData(); boolean storesUpper = rs.getStatement().getConnection().getMetaData().storesUpperCaseIdentifiers(); int col_count = metadata.getColumnCount(); IRubyObject[] col_names = new IRubyObject[col_count]; int[] col_types = new int[col_count]; int[] col_scale = new int[col_count]; for(int i=0;i<col_count;i++) { String s1 = metadata.getColumnLabel(i+1); if(storesUpper && !HAS_SMALL.matcher(s1).find()) { s1 = s1.toLowerCase(); } col_names[i] = RubyString.newUnicodeString(runtime, s1); col_types[i] = metadata.getColumnType(i+1); col_scale[i] = metadata.getScale(i+1); } while(rs.next()) { RubyHash row = RubyHash.newHash(runtime); for(int i=0;i<col_count;i++) { rubyApi.callMethod(row, "[]=", new IRubyObject[] { col_names[i], jdbc_to_ruby(runtime, i+1, col_types[i], col_scale[i], rs) }); } results.add(row); } } finally { try { rs.close(); } catch(Exception e) {} } return runtime.newArray(results); } @JRubyMethod(name = "unmarshal_result", required = 1) public static IRubyObject unmarshal_result(IRubyObject recv, IRubyObject resultset, Block row_filter) throws SQLException, IOException { Ruby runtime = recv.getRuntime(); ResultSet rs = intoResultSet(resultset); List results = new ArrayList(); try { ResultSetMetaData metadata = rs.getMetaData(); int col_count = metadata.getColumnCount(); IRubyObject[] col_names = new IRubyObject[col_count]; int[] col_types = new int[col_count]; int[] col_scale = new int[col_count]; for (int i=0;i<col_count;i++) { col_names[i] = RubyString.newUnicodeString(runtime, metadata.getColumnLabel(i+1)); col_types[i] = metadata.getColumnType(i+1); col_scale[i] = metadata.getScale(i+1); } if (row_filter.isGiven()) { while (rs.next()) { if (row_filter.yield(runtime.getCurrentContext(),resultset).isTrue()) { RubyHash row = RubyHash.newHash(runtime); for (int i=0;i<col_count;i++) { rubyApi.callMethod(row, "[]=", new IRubyObject[] { col_names[i], jdbc_to_ruby(runtime, i+1, col_types[i], col_scale[i], rs) }); } results.add(row); } } } else { while (rs.next()) { RubyHash row = RubyHash.newHash(runtime); for (int i=0;i<col_count;i++) { rubyApi.callMethod(row, "[]=", new IRubyObject[] { col_names[i], jdbc_to_ruby(runtime, i+1, col_types[i], col_scale[i], rs) }); } results.add(row); } } } finally { try { rs.close(); } catch(Exception e) {} } return runtime.newArray(results); } private static IRubyObject jdbc_to_ruby(Ruby runtime, int row, int type, int scale, ResultSet rs) throws SQLException { try { int n; switch (type) { case Types.BINARY: case Types.BLOB: case Types.LONGVARBINARY: case Types.VARBINARY: InputStream is = rs.getBinaryStream(row); if (is == null || rs.wasNull()) { return runtime.getNil(); } ByteList str = new ByteList(2048); byte[] buf = new byte[2048]; while ((n = is.read(buf)) != -1) { str.append(buf, 0, n); } is.close(); return runtime.newString(str); case Types.LONGVARCHAR: case Types.CLOB: Reader rss = rs.getCharacterStream(row); if (rss == null || rs.wasNull()) { return runtime.getNil(); } StringBuffer str2 = new StringBuffer(2048); char[] cuf = new char[2048]; while ((n = rss.read(cuf)) != -1) { str2.append(cuf, 0, n); } rss.close(); return RubyString.newUnicodeString(runtime, str2.toString()); case Types.TIMESTAMP: Timestamp time = rs.getTimestamp(row); if (time == null || rs.wasNull()) { return runtime.getNil(); } String sttr = time.toString(); if (sttr.endsWith(" 00:00:00.0")) { sttr = sttr.substring(0, sttr.length() - (" 00:00:00.0".length())); } return RubyString.newUnicodeString(runtime, sttr); default: String vs = rs.getString(row); if (vs == null || rs.wasNull()) { return runtime.getNil(); } return RubyString.newUnicodeString(runtime, vs); } } catch (IOException ioe) { throw (SQLException) new SQLException(ioe.getMessage()).initCause(ioe); } } public static IRubyObject unmarshal_id_result(Ruby runtime, ResultSet rs) throws SQLException { try { if(rs.next()) { if(rs.getMetaData().getColumnCount() > 0) { return runtime.newFixnum(rs.getLong(1)); } } return runtime.getNil(); } finally { try { rs.close(); } catch(Exception e) {} } } private static String convertToStringOrNull(IRubyObject obj) { if (obj.isNil()) { return null; } return obj.toString(); } private static int getTypeValueFor(Ruby runtime, IRubyObject type) throws SQLException { if(!(type instanceof RubySymbol)) { type = rubyApi.callMethod(type, "type"); } if(type == runtime.newSymbol("string")) { return Types.VARCHAR; } else if(type == runtime.newSymbol("text")) { return Types.CLOB; } else if(type == runtime.newSymbol("integer")) { return Types.INTEGER; } else if(type == runtime.newSymbol("decimal")) { return Types.DECIMAL; } else if(type == runtime.newSymbol("float")) { return Types.FLOAT; } else if(type == runtime.newSymbol("datetime")) { return Types.TIMESTAMP; } else if(type == runtime.newSymbol("timestamp")) { return Types.TIMESTAMP; } else if(type == runtime.newSymbol("time")) { return Types.TIME; } else if(type == runtime.newSymbol("date")) { return Types.DATE; } else if(type == runtime.newSymbol("binary")) { return Types.BLOB; } else if(type == runtime.newSymbol("boolean")) { return Types.BOOLEAN; } else { return -1; } } private final static DateFormat FORMAT = new SimpleDateFormat("%y-%M-%d %H:%m:%s"); private static void setValue(PreparedStatement ps, int index, Ruby runtime, ThreadContext context, IRubyObject value, IRubyObject type) throws SQLException { final int tp = getTypeValueFor(runtime, type); if(value.isNil()) { ps.setNull(index, tp); return; } switch(tp) { case Types.VARCHAR: case Types.CLOB: ps.setString(index, RubyString.objAsString(context, value).toString()); break; case Types.INTEGER: ps.setLong(index, RubyNumeric.fix2long(value)); break; case Types.FLOAT: ps.setDouble(index, ((RubyNumeric)value).getDoubleValue()); break; case Types.TIMESTAMP: case Types.TIME: case Types.DATE: if(!(value instanceof RubyTime)) { try { Date dd = FORMAT.parse(RubyString.objAsString(context, value).toString()); ps.setTimestamp(index, new java.sql.Timestamp(dd.getTime()), Calendar.getInstance()); } catch(Exception e) { ps.setString(index, RubyString.objAsString(context, value).toString()); } } else { RubyTime rubyTime = (RubyTime) value; java.util.Date date = rubyTime.getJavaDate(); long millis = date.getTime(); long micros = rubyTime.microseconds() - millis / 1000; java.sql.Timestamp ts = new java.sql.Timestamp(millis); java.util.Calendar cal = Calendar.getInstance(); cal.setTime(date); ts.setNanos((int)(micros * 1000)); ps.setTimestamp(index, ts, cal); } break; case Types.BOOLEAN: ps.setBoolean(index, value.isTrue()); break; default: throw new RuntimeException("type " + type + " not supported in _bind yet"); } } private static void setValuesOnPS(PreparedStatement ps, Ruby runtime, ThreadContext context, IRubyObject values, IRubyObject types) throws SQLException { RubyArray vals = (RubyArray)values; RubyArray tps = (RubyArray)types; for(int i=0, j=vals.getLength(); i<j; i++) { setValue(ps, i+1, runtime, context, vals.eltInternal(i), tps.eltInternal(i)); } } /* * sql, values, types, name = nil, pk = nil, id_value = nil, sequence_name = nil */ @JRubyMethod(name = "insert_bind", required = 3, rest = true) public static IRubyObject insert_bind(final ThreadContext context, IRubyObject recv, final IRubyObject[] args) throws SQLException { final Ruby runtime = recv.getRuntime(); return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { PreparedStatement ps = null; try { ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString(), Statement.RETURN_GENERATED_KEYS); setValuesOnPS(ps, runtime, context, args[1], args[2]); ps.executeUpdate(); return unmarshal_id_result(runtime, ps.getGeneratedKeys()); } finally { try { ps.close(); } catch (Exception e) { } } } }); } /* * sql, values, types, name = nil */ @JRubyMethod(name = "update_bind", required = 3, rest = true) public static IRubyObject update_bind(final ThreadContext context, IRubyObject recv, final IRubyObject[] args) throws SQLException { final Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 3, 4); return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { PreparedStatement ps = null; try { ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString()); setValuesOnPS(ps, runtime, context, args[1], args[2]); ps.executeUpdate(); } finally { try { ps.close(); } catch (Exception e) { } } return runtime.getNil(); } }); } /* * (is binary?, colname, tablename, primary key, id, value) */ @JRubyMethod(name = "write_large_object", required = 6) public static IRubyObject write_large_object(IRubyObject recv, final IRubyObject[] args) throws SQLException, IOException { final Ruby runtime = recv.getRuntime(); return withConnectionAndRetry(recv, new SQLBlock() { public IRubyObject call(Connection c) throws SQLException { String sql = "UPDATE " + rubyApi.convertToRubyString(args[2]) + " SET " + rubyApi.convertToRubyString(args[1]) + " = ? WHERE " + rubyApi.convertToRubyString(args[3]) + "=" + rubyApi.convertToRubyString(args[4]); PreparedStatement ps = null; try { ps = c.prepareStatement(sql); if (args[0].isTrue()) { // binary ByteList outp = rubyApi.convertToRubyString(args[5]).getByteList(); ps.setBinaryStream(1, new ByteArrayInputStream(outp.bytes, outp.begin, outp.realSize), outp.realSize); } else { // clob String ss = rubyApi.convertToRubyString(args[5]).getUnicodeValue(); ps.setCharacterStream(1, new StringReader(ss), ss.length()); } ps.executeUpdate(); } finally { try { ps.close(); } catch (Exception e) { } } return runtime.getNil(); } }); } private static Connection getConnection(IRubyObject recv) { Connection conn = (Connection) recv.dataGetStruct(); return conn; } private static RuntimeException wrap(IRubyObject recv, Throwable exception) { RubyClass err = recv.getRuntime().getModule("ActiveRecord").getClass("ActiveRecordError"); return (RuntimeException) new RaiseException(recv.getRuntime(), err, exception.getMessage(), false).initCause(exception); } private static ResultSet intoResultSet(IRubyObject inp) { JavaObject jo; if (inp instanceof JavaObject) { jo = (JavaObject) inp; } else { jo = (JavaObject) rubyApi.getInstanceVariable(inp, "@java_object"); } return (ResultSet) jo.getValue(); } private static boolean isConnectionBroken(IRubyObject recv, Connection c) { try { IRubyObject alive = config_value(recv, "connection_alive_sql"); if (select_p(recv, alive).isTrue()) { String connectionSQL = rubyApi.convertToRubyString(alive).toString(); Statement s = c.createStatement(); try { s.execute(connectionSQL); } finally { try { s.close(); } catch (SQLException ignored) {} } return true; } else { return !c.isClosed(); } } catch (SQLException sx) { return true; } } private static IRubyObject setConnection(IRubyObject recv, Connection c) { Connection prev = getConnection(recv); if (prev != null) { try { prev.close(); } catch(Exception e) {} } IRubyObject rubyconn = recv.getRuntime().getNil(); if (c != null) { rubyconn = wrappedConnection(recv,c); } rubyApi.setInstanceVariable(recv, "@connection", rubyconn); recv.dataWrapStruct(c); return recv; } private static IRubyObject wrappedConnection(IRubyObject recv, Connection c) { return Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(), c), Block.NULL_BLOCK); } private static JdbcConnectionFactory getConnectionFactory(IRubyObject recv) throws RaiseException { IRubyObject connection_factory = rubyApi.getInstanceVariable(recv, "@connection_factory"); JdbcConnectionFactory factory = null; try { factory = (JdbcConnectionFactory) ((JavaObject) rubyApi.getInstanceVariable(connection_factory, "@java_object")).getValue(); } catch (Exception e) { factory = null; } if (factory == null) { throw recv.getRuntime().newRuntimeError("@connection_factory not set properly"); } return factory; } private static IRubyObject config_value(IRubyObject recv, String key) { Ruby runtime = recv.getRuntime(); IRubyObject config_hash = rubyApi.getInstanceVariable(recv, "@config"); return rubyApi.callMethod(config_hash, "[]", runtime.newSymbol(key)); } }
package org.jaxen.saxpath.base; import java.util.LinkedList; import org.jaxen.saxpath.Axis; import org.jaxen.saxpath.Operator; import org.jaxen.saxpath.XPathHandler; import org.jaxen.saxpath.XPathSyntaxException; /** Implementation of SAXPath's <code>XPathReader</code> which * generates callbacks to an <code>XPathHandler</code>. * * @author bob mcwhirter (bob@werken.com) */ public class XPathReader extends TokenTypes implements org.jaxen.saxpath.XPathReader { private LinkedList tokens; private XPathLexer lexer; private XPathHandler handler; public XPathReader() { setXPathHandler( DefaultXPathHandler.getInstance() ); } public void setXPathHandler(XPathHandler handler) { this.handler = handler; } public XPathHandler getXPathHandler() { return this.handler; } public void parse(String xpath) throws org.jaxen.saxpath.SAXPathException { setUpParse( xpath ); getXPathHandler().startXPath(); expr(); getXPathHandler().endXPath(); if ( LA(1) != EOF ) { throwUnexpected(); } lexer = null; tokens = null; } void setUpParse(String xpath) { this.tokens = new LinkedList(); this.lexer = new XPathLexer( xpath ); } void pathExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startPathExpr(); switch ( LA(1) ) { case INTEGER: case DOUBLE: case LITERAL: case LEFT_PAREN: case DOLLAR: { filterExpr(); if ( LA(1) == SLASH || LA(1) == DOUBLE_SLASH ) { XPathSyntaxException ex = this.createSyntaxException("Node-set expected"); throw ex; } break; } case IDENTIFIER: { if ( ( LA(2) == LEFT_PAREN && ! isNodeTypeName( LT(1) ) ) || ( LA(2) == COLON && LA(4) == LEFT_PAREN) ) { filterExpr(); if ( LA(1) == SLASH || LA(1) == DOUBLE_SLASH) { locationPath( false ); } break; } else { locationPath( false ); break; } } case DOT: case DOT_DOT: case STAR: case AT: { locationPath( false ); break; } case SLASH: case DOUBLE_SLASH: { locationPath( true ); break; } default: { throwUnexpected(); } } getXPathHandler().endPathExpr(); } void numberDouble() throws org.jaxen.saxpath.SAXPathException { Token token = match( DOUBLE ); getXPathHandler().number( Double.parseDouble( token.getTokenText() ) ); } void numberInteger() throws org.jaxen.saxpath.SAXPathException { Token token = match( INTEGER ); String text = token.getTokenText(); try { getXPathHandler().number( Integer.parseInt( text ) ); } catch (NumberFormatException ex) { getXPathHandler().number( Double.parseDouble( text ) ); } } void literal() throws org.jaxen.saxpath.SAXPathException { Token token = match( LITERAL ); getXPathHandler().literal( token.getTokenText() ); } void functionCall() throws org.jaxen.saxpath.SAXPathException { String prefix = null; String functionName = null; if ( LA(2) == COLON ) { prefix = match( IDENTIFIER ).getTokenText(); match( COLON ); } else { prefix = ""; } functionName = match( IDENTIFIER ).getTokenText(); getXPathHandler().startFunction( prefix, functionName ); match ( LEFT_PAREN ); arguments(); match ( RIGHT_PAREN ); getXPathHandler().endFunction(); } void arguments() throws org.jaxen.saxpath.SAXPathException { while ( LA(1) != RIGHT_PAREN ) { expr(); if ( LA(1) == COMMA ) { match( COMMA ); } else { break; } } } void filterExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startFilterExpr(); switch ( LA(1) ) { case INTEGER: { numberInteger(); break; } case DOUBLE: { numberDouble(); break; } case LITERAL: { literal(); break; } case LEFT_PAREN: { match( LEFT_PAREN ); expr(); match( RIGHT_PAREN ); break; } case IDENTIFIER: { functionCall(); break; } case DOLLAR: { variableReference(); break; } } predicates(); getXPathHandler().endFilterExpr(); } void variableReference() throws org.jaxen.saxpath.SAXPathException { match( DOLLAR ); String prefix = null; String variableName = null; if ( LA(2) == COLON ) { prefix = match( IDENTIFIER ).getTokenText(); match( COLON ); } else { prefix = ""; } variableName = match( IDENTIFIER ).getTokenText(); getXPathHandler().variableReference( prefix, variableName ); } void locationPath(boolean isAbsolute) throws org.jaxen.saxpath.SAXPathException { switch ( LA(1) ) { case SLASH: case DOUBLE_SLASH: { if ( isAbsolute ) { absoluteLocationPath(); } else { relativeLocationPath(); } break; } case AT: case IDENTIFIER: case DOT: case DOT_DOT: case STAR: { relativeLocationPath(); break; } default: { throwUnexpected(); break; } } } void absoluteLocationPath() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startAbsoluteLocationPath(); switch ( LA(1) ) { case SLASH: { match( SLASH ); switch ( LA(1) ) { case DOT: case DOT_DOT: case AT: case IDENTIFIER: case STAR: { steps(); break; } case EOF: { return; } } break; } case DOUBLE_SLASH: { getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF ); getXPathHandler().endAllNodeStep(); match( DOUBLE_SLASH ); // XXX this may be the place where // gets allowed // and it shouldn't be switch ( LA(1) ) { case DOT: case DOT_DOT: case AT: case IDENTIFIER: case STAR: { steps(); break; } default: XPathSyntaxException ex = this.createSyntaxException("Location path cannot end with throw ex; } break; } } getXPathHandler().endAbsoluteLocationPath(); } void relativeLocationPath() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startRelativeLocationPath(); switch ( LA(1) ) { case SLASH: { match( SLASH ); break; } case DOUBLE_SLASH: { getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF ); getXPathHandler().endAllNodeStep(); match( DOUBLE_SLASH ); break; } } steps(); getXPathHandler().endRelativeLocationPath(); } void steps() throws org.jaxen.saxpath.SAXPathException { switch ( LA(1) ) { case DOT: case DOT_DOT: case AT: case IDENTIFIER: case STAR: { step(); break; } case EOF: { return; } default: { throw createSyntaxException( "Expected one of '.', '..', '@', '*', <QName>" ); } } do { if ( ( LA(1) == SLASH) || ( LA(1) == DOUBLE_SLASH ) ) { switch ( LA(1) ) { case SLASH: { match( SLASH ); break; } case DOUBLE_SLASH: { getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF ); getXPathHandler().endAllNodeStep(); match( DOUBLE_SLASH ); break; } } } else { return; } switch ( LA(1) ) { case DOT: case DOT_DOT: case AT: case IDENTIFIER: case STAR: { step(); break; } default: { throw createSyntaxException( "Expected one of '.', '..', '@', '*', <QName>" ); } } } while ( true ); } void step() throws org.jaxen.saxpath.SAXPathException { int axis = 0; switch ( LA(1) ) { case DOT: case DOT_DOT: { abbrStep(); return; } case AT: { axis = axisSpecifier(); break; } case IDENTIFIER: { if ( LA(2) == DOUBLE_COLON ) { axis = axisSpecifier(); } else { axis = Axis.CHILD; } break; } case STAR: { axis = Axis.CHILD; break; } } nodeTest( axis ); } int axisSpecifier() throws org.jaxen.saxpath.SAXPathException { int axis = 0; switch ( LA(1) ) { case AT: { match( AT ); axis = Axis.ATTRIBUTE; break; } case IDENTIFIER: { Token token = LT( 1 ); axis = Axis.lookup( token.getTokenText() ); if ( axis == Axis.INVALID_AXIS ) { throwInvalidAxis( token.getTokenText() ); } match( IDENTIFIER ); match( DOUBLE_COLON ); break; } } return axis; } void nodeTest(int axis) throws org.jaxen.saxpath.SAXPathException { switch ( LA(1) ) { case IDENTIFIER: { switch ( LA(2) ) { case LEFT_PAREN: { nodeTypeTest( axis ); break; } default: { nameTest( axis ); break; } } break; } case STAR: { nameTest( axis ); break; } default: throw createSyntaxException("Expected <QName> or *"); } } void nodeTypeTest(int axis) throws org.jaxen.saxpath.SAXPathException { Token nodeTypeToken = match( IDENTIFIER ); String nodeType = nodeTypeToken.getTokenText(); match( LEFT_PAREN ); if ( "processing-instruction".equals( nodeType ) ) { String piName = ""; if ( LA(1) == LITERAL ) { piName = match( LITERAL ).getTokenText(); } match( RIGHT_PAREN ); getXPathHandler().startProcessingInstructionNodeStep( axis, piName ); predicates(); getXPathHandler().endProcessingInstructionNodeStep(); } else if ( "node".equals( nodeType ) ) { match( RIGHT_PAREN ); getXPathHandler().startAllNodeStep( axis ); predicates(); getXPathHandler().endAllNodeStep(); } else if ( "text".equals( nodeType ) ) { match( RIGHT_PAREN ); getXPathHandler().startTextNodeStep( axis ); predicates(); getXPathHandler().endTextNodeStep(); } else if ( "comment".equals( nodeType ) ) { match( RIGHT_PAREN ); getXPathHandler().startCommentNodeStep( axis ); predicates(); getXPathHandler().endCommentNodeStep(); } else { throw createSyntaxException( "Expected node-type" ); } } void nameTest(int axis) throws org.jaxen.saxpath.SAXPathException { String prefix = null; String localName = null; switch ( LA(2) ) { case COLON: { switch ( LA(1) ) { case IDENTIFIER: { prefix = match( IDENTIFIER ).getTokenText(); match( COLON ); break; } } break; } } switch ( LA(1) ) { case IDENTIFIER: { localName = match( IDENTIFIER ).getTokenText(); break; } case STAR: { match( STAR ); localName = "*"; break; } } if ( prefix == null ) { prefix = ""; } getXPathHandler().startNameStep( axis, prefix, localName ); predicates(); getXPathHandler().endNameStep(); } void abbrStep() throws org.jaxen.saxpath.SAXPathException { switch ( LA(1) ) { case DOT: { match( DOT ); getXPathHandler().startAllNodeStep( Axis.SELF ); predicates(); getXPathHandler().endAllNodeStep(); break; } case DOT_DOT: { match( DOT_DOT ); getXPathHandler().startAllNodeStep( Axis.PARENT ); predicates(); getXPathHandler().endAllNodeStep(); break; } } } void predicates() throws org.jaxen.saxpath.SAXPathException { while (true ) { if ( LA(1) == LEFT_BRACKET ) { predicate(); } else { break; } } } void predicate() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startPredicate(); match( LEFT_BRACKET ); predicateExpr(); match( RIGHT_BRACKET ); getXPathHandler().endPredicate(); } void predicateExpr() throws org.jaxen.saxpath.SAXPathException { expr(); } void expr() throws org.jaxen.saxpath.SAXPathException { orExpr(); } void orExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startOrExpr(); andExpr(); boolean create = false; switch ( LA(1) ) { case OR: { create = true; match( OR ); orExpr(); break; } } getXPathHandler().endOrExpr( create ); } void andExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startAndExpr(); equalityExpr(); boolean create = false; switch ( LA(1) ) { case AND: { create = true; match( AND ); andExpr(); break; } } getXPathHandler().endAndExpr( create ); } void equalityExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startEqualityExpr(); // XXX why call this twice? getXPathHandler().startEqualityExpr(); relationalExpr(); int operator = Operator.NO_OP; switch ( LA(1) ) { case EQUALS: { match( EQUALS ); relationalExpr(); operator = Operator.EQUALS; break; } case NOT_EQUALS: { match( NOT_EQUALS ); relationalExpr(); operator = Operator.NOT_EQUALS; break; } } getXPathHandler().endEqualityExpr( operator ); operator = Operator.NO_OP; switch ( LA(1) ) { case EQUALS: { match( EQUALS ); equalityExpr(); operator = Operator.EQUALS; break; } case NOT_EQUALS: { match( NOT_EQUALS ); equalityExpr(); operator = Operator.NOT_EQUALS; break; } } getXPathHandler().endEqualityExpr( operator ); } void relationalExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startRelationalExpr(); getXPathHandler().startRelationalExpr(); additiveExpr(); int operator = Operator.NO_OP; switch ( LA(1) ) { case LESS_THAN: { match( LESS_THAN ); additiveExpr(); operator = Operator.LESS_THAN; break; } case GREATER_THAN: { match( GREATER_THAN ); additiveExpr(); operator = Operator.GREATER_THAN; break; } case LESS_THAN_EQUALS: { match( LESS_THAN_EQUALS ); additiveExpr(); operator = Operator.LESS_THAN_EQUALS; break; } case GREATER_THAN_EQUALS: { match( GREATER_THAN_EQUALS ); additiveExpr(); operator = Operator.GREATER_THAN_EQUALS; break; } } getXPathHandler().endRelationalExpr( operator ); operator = Operator.NO_OP; switch ( LA(1) ) { case LESS_THAN: { match( LESS_THAN ); relationalExpr(); operator = Operator.LESS_THAN; break; } case GREATER_THAN: { match( GREATER_THAN ); relationalExpr(); operator = Operator.GREATER_THAN; break; } case LESS_THAN_EQUALS: { match( LESS_THAN_EQUALS ); relationalExpr(); operator = Operator.LESS_THAN_EQUALS; break; } case GREATER_THAN_EQUALS: { match( GREATER_THAN_EQUALS ); relationalExpr(); operator = Operator.GREATER_THAN_EQUALS; break; } } getXPathHandler().endRelationalExpr( operator ); } void additiveExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startAdditiveExpr(); getXPathHandler().startAdditiveExpr(); multiplicativeExpr(); int operator = Operator.NO_OP; switch ( LA(1) ) { case PLUS: { match( PLUS ); operator = Operator.ADD; multiplicativeExpr(); break; } case MINUS: { match( MINUS ); operator = Operator.SUBTRACT; multiplicativeExpr(); break; } } getXPathHandler().endAdditiveExpr( operator ); operator = Operator.NO_OP; switch ( LA(1) ) { case PLUS: { match( PLUS ); operator = Operator.ADD; additiveExpr(); break; } case MINUS: { match( MINUS ); operator = Operator.SUBTRACT; additiveExpr(); break; } default: { operator = Operator.NO_OP; break; } } getXPathHandler().endAdditiveExpr( operator ); } void multiplicativeExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startMultiplicativeExpr(); getXPathHandler().startMultiplicativeExpr(); unaryExpr(); int operator = Operator.NO_OP; switch ( LA(1) ) { case STAR: { match( STAR ); unaryExpr(); operator = Operator.MULTIPLY; break; } case DIV: { match( DIV ); unaryExpr(); operator = Operator.DIV; break; } case MOD: { match( MOD ); unaryExpr(); operator = Operator.MOD; break; } } getXPathHandler().endMultiplicativeExpr( operator ); operator = Operator.NO_OP; switch ( LA(1) ) { case STAR: { match( STAR ); multiplicativeExpr(); operator = Operator.MULTIPLY; break; } case DIV: { match( DIV ); multiplicativeExpr(); operator = Operator.DIV; break; } case MOD: { match( MOD ); multiplicativeExpr(); operator = Operator.MOD; break; } } getXPathHandler().endMultiplicativeExpr( operator ); } void unaryExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startUnaryExpr(); int operator = Operator.NO_OP; switch ( LA(1) ) { case MINUS: { match( MINUS ); operator = Operator.NEGATIVE; unaryExpr(); break; } default: { unionExpr(); break; } } getXPathHandler().endUnaryExpr( operator ); } void unionExpr() throws org.jaxen.saxpath.SAXPathException { getXPathHandler().startUnionExpr(); pathExpr(); boolean create = false; switch ( LA(1) ) { case PIPE: { match( PIPE ); create = true; expr(); break; } } getXPathHandler().endUnionExpr( create ); } Token match(int tokenType) throws XPathSyntaxException { LT(1); Token token = (Token) tokens.get( 0 ); if ( token.getTokenType() == tokenType ) { tokens.removeFirst(); return token; } throw createSyntaxException( "Expected: " + getTokenText( tokenType ) ); } int LA(int position) { return LT(position).getTokenType(); } Token LT(int position) { if ( tokens.size() <= ( position - 1 ) ) { for ( int i = 0 ; i < position ; ++i ) { tokens.add( lexer.nextToken() ); } } return (Token) tokens.get( position - 1 ); } boolean isNodeTypeName(Token name) { String text = name.getTokenText(); if ( "node".equals( text ) || "comment".equals( text ) || "text".equals( text ) || "processing-instruction".equals( text ) ) { return true; } return false; } XPathSyntaxException createSyntaxException(String message) { String xpath = this.lexer.getXPath(); int position = LT(1).getTokenBegin(); return new XPathSyntaxException( xpath, position, message ); } void throwInvalidAxis(String invalidAxis) throws org.jaxen.saxpath.SAXPathException { String xpath = this.lexer.getXPath(); int position = LT(1).getTokenBegin(); String message = "Expected valid axis name instead of [" + invalidAxis + "]"; throw new XPathSyntaxException( xpath, position, message ); } void throwUnexpected() throws org.jaxen.saxpath.SAXPathException { throw createSyntaxException( "Unexpected '" + LT(1).getTokenText() + "'" ); } }
// arch-tag: 21495D4D-9106-4A3F-AFD0-8D08C18AF3DC package net.spy.memcached; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Date; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.spy.SpyObject; import net.spy.util.CloseUtil; /** * Transcoder that serializes and compresses objects. */ public class SerializingTranscoder extends SpyObject implements Transcoder { // General flags public static final int SERIALIZED=1; public static final int COMPRESSED=2; // Special flags for specially handled types. private static final int SPECIAL_MASK=0xff00; private static final int SPECIAL_BOOLEAN=(1<<8); private static final int SPECIAL_INT=(2<<8); private static final int SPECIAL_LONG=(3<<8); private static final int SPECIAL_DATE=(4<<8); private static final int SPECIAL_BYTE=(5<<8); private static final int SPECIAL_FLOAT=(6<<8); private static final int SPECIAL_DOUBLE=(7<<8); private static final int SPECIAL_BYTEARRAY=(8<<8); private int compressionThreshold=16384; public SerializingTranscoder() { super(); } /** * Set the compression threshold to the given value. */ public void setCompressionThreshold(int to) { compressionThreshold=to; } public Object decode(CachedData d) { byte[] data=d.getData(); Object rv=null; if((d.getFlags() & COMPRESSED) != 0) { data=decompress(d.getData()); } if((d.getFlags() & SERIALIZED) != 0) { rv=deserialize(data); } else if((d.getFlags() & SPECIAL_MASK) != 0) { switch(d.getFlags() & SPECIAL_MASK) { case SPECIAL_BOOLEAN: rv=Boolean.valueOf(decodeBoolean(data)); break; case SPECIAL_INT: rv=new Integer(decodeInt(data)); break; case SPECIAL_LONG: rv=new Long(decodeLong(data)); break; case SPECIAL_DATE: rv=new Date(decodeLong(data)); break; case SPECIAL_BYTE: rv=new Byte(decodeByte(data)); break; case SPECIAL_FLOAT: rv=new Float(Float.intBitsToFloat(decodeInt(data))); break; case SPECIAL_DOUBLE: rv=new Double(Double.longBitsToDouble(decodeLong(data))); break; case SPECIAL_BYTEARRAY: rv=data; break; default: assert false; } } else { rv=new String(data); } return rv; } public CachedData encode(Object o) { CachedData rv=null; byte[] b=null; int flags=0; if(o instanceof String) { b=((String)o).getBytes(); } else if(o instanceof Long) { b=encodeLong((Long)o); flags |= SPECIAL_LONG; } else if(o instanceof Integer) { b=encodeInt((Integer)o); flags |= SPECIAL_INT; } else if(o instanceof Boolean) { b=encodeBoolean((Boolean)o); flags |= SPECIAL_BOOLEAN; } else if(o instanceof Date) { b=encodeLong(((Date)o).getTime()); flags |= SPECIAL_DATE; } else if(o instanceof Byte) { b=encodeByte((Byte)o); flags |= SPECIAL_BYTE; } else if(o instanceof Float) { b=encodeInt(Float.floatToRawIntBits((Float)o)); flags |= SPECIAL_FLOAT; } else if(o instanceof Double) { b=encodeLong(Double.doubleToRawLongBits((Double)o)); flags |= SPECIAL_DOUBLE; } else if(o instanceof byte[]) { b=(byte[])o; flags |= SPECIAL_BYTEARRAY; } else { b=serialize(o); flags |= SERIALIZED; } if(b != null) { if(b.length > compressionThreshold) { byte[] compressed=compress(b); if(compressed.length < b.length) { getLogger().info("Compressed %s from %d to %d", o.getClass().getName(), b.length, compressed.length); b=compressed; flags |= COMPRESSED; } else { getLogger().info( "Compression increased the size of %s from %d to %d", o.getClass().getName(), b.length, compressed.length); } } rv=new CachedData(flags, b); } return rv; } private byte[] serialize(Object o) { assert o != null; byte[] rv=null; try { ByteArrayOutputStream bos=new ByteArrayOutputStream(); ObjectOutputStream os=new ObjectOutputStream(bos); os.writeObject(o); os.close(); bos.close(); rv=bos.toByteArray(); } catch(IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } return rv; } private Object deserialize(byte[] in) { Object rv=null; assert in != null; try { ByteArrayInputStream bis=new ByteArrayInputStream(in); ObjectInputStream is=new ObjectInputStream(bis); rv=is.readObject(); is.close(); bis.close(); } catch(IOException e) { getLogger().warn("Caught IOException decoding %d bytes of data", in.length, e); } catch (ClassNotFoundException e) { getLogger().warn("Caught CNFE decoding %d bytes of data", in.length, e); } return rv; } private byte[] compress(byte[] in) { assert in != null; ByteArrayOutputStream bos=new ByteArrayOutputStream(); GZIPOutputStream gz=null; try { gz = new GZIPOutputStream(bos); gz.write(in); } catch (IOException e) { throw new RuntimeException("IO exception compressing data", e); } finally { CloseUtil.close(gz); CloseUtil.close(bos); } byte[] rv=bos.toByteArray(); getLogger().debug("Compressed %d bytes to %d", in.length, rv.length); return rv; } private byte[] decompress(byte[] in) { assert in != null; ByteArrayInputStream bis=new ByteArrayInputStream(in); ByteArrayOutputStream bos=new ByteArrayOutputStream(); GZIPInputStream gis; try { gis = new GZIPInputStream(bis); byte[] buf=new byte[8192]; int r=-1; while((r=gis.read(buf)) > 0) { bos.write(buf, 0, r); } } catch (IOException e) { throw new RuntimeException("Error decompressing data", e); } return bos.toByteArray(); } private byte[] encodeNum(long l, int maxBytes) { byte[] rv=new byte[maxBytes]; for(int i=0; i<rv.length; i++) { int pos=rv.length-i-1; rv[pos]=(byte) ((l >> (8 * i)) & 0xff); } int firstNonZero=0; for(;firstNonZero<rv.length && rv[firstNonZero]==0; firstNonZero++) { // Just looking for what we can reduce } if(firstNonZero > 0) { byte[] tmp=new byte[rv.length - firstNonZero]; System.arraycopy(rv, firstNonZero, tmp, 0, rv.length-firstNonZero); rv=tmp; } return rv; } byte[] encodeLong(long l) { return encodeNum(l, 8); } long decodeLong(byte[] b) { long rv=0; for(byte i : b) { rv = (rv << 8) | (i<0?256+i:i); } return rv; } byte[] encodeInt(int in) { return encodeNum(in, 4); } int decodeInt(byte[] in) { assert in.length <= 4 : "Too long to be an int (" + in.length + ") bytes"; return (int)decodeLong(in); } byte[] encodeByte(byte in) { return new byte[]{in}; } byte decodeByte(byte[] in) { assert in.length <= 1 : "Too long for a byte"; byte rv=0; if(in.length == 1) { rv=in[0]; } return rv; } byte[] encodeBoolean(boolean b) { byte[] rv=new byte[1]; rv[0]=(byte)(b?'1':'0'); return rv; } boolean decodeBoolean(byte[] in) { assert in.length == 1 : "Wrong length for a boolean"; return in[0] == '1'; } }
package opennlp.tools.lang.english; import java.io.File; import java.io.IOException; import java.util.List; import opennlp.maxent.MaxentModel; import opennlp.maxent.io.SuffixSensitiveGISModelReader; import opennlp.tools.ngram.Dictionary; import opennlp.tools.postag.DefaultPOSContextGenerator; import opennlp.tools.postag.POSDictionary; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.util.Sequence; public class ParserTagger extends POSTaggerME implements opennlp.tools.parser.ParserTagger { private static final int K = 10; int beamSize; public ParserTagger(MaxentModel model, Dictionary dict) { super(model, dict); beamSize = K; } public ParserTagger(String modelFile,Dictionary dict) throws IOException { this(modelFile,K,K,dict); } public ParserTagger(MaxentModel model, String tagDictionary, boolean useCase) throws IOException { this(model,K,null,tagDictionary,useCase,K); } public ParserTagger(MaxentModel model, int beamSize, Dictionary dict, String tagDictionary, boolean useCase, int cacheSize) throws IOException { super(beamSize, model, new DefaultPOSContextGenerator(cacheSize,dict), new POSDictionary(tagDictionary, useCase)); this.beamSize = beamSize; } public ParserTagger(String modelFile,int beamSize, int cacheSize,Dictionary dict) throws IOException { super(beamSize, new SuffixSensitiveGISModelReader(new File(modelFile)).getModel(), new DefaultPOSContextGenerator(cacheSize,dict), null); this.beamSize = beamSize; } public ParserTagger(String modelFile, String tagDictionary, boolean useCase) throws IOException { this(modelFile,K,null,tagDictionary,useCase,K); } public ParserTagger(String modelFile, String tagDictionary, boolean useCase, Dictionary dict) throws IOException { this(modelFile,K,dict,tagDictionary,useCase,K); } public ParserTagger(String modelFile, int beamSize, Dictionary dict, String tagDictionary, boolean useCase, int cacheSize) throws IOException { super(beamSize, new SuffixSensitiveGISModelReader(new File(modelFile)).getModel(), new DefaultPOSContextGenerator(cacheSize,dict), new POSDictionary(tagDictionary, useCase)); this.beamSize = beamSize; } public Sequence[] topKSequences(List sentence) { return beam.bestSequences(beamSize, sentence.toArray(), null); } public Sequence[] topKSequences(String[] sentence) { return beam.bestSequences(beamSize, sentence, null); } }
package org.jcoderz.commons.taskdefs; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.transform.Transformer; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.XMLAbstractTranscoder; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.jcoderz.commons.util.Constants; import org.jcoderz.commons.util.IoUtil; /** * Xtreme Documentation Ant task. * * @author Michael Griffel */ public class XtremeDocs extends Task { private static final String FORMAT_PDF = "PDF"; private static final String FORMAT_HTML = "HTML"; private static final String FORMAT_ALL = "ALL"; private static final String TYPE_QUALITY_REPORT = "Quality-Report"; private static final String TYPE_TEST_SPEC = "TestSpec"; private static final String TYPE_USE_CASE = "UseCase"; private static final String TYPE_SAD = "SAD"; private static final String IMAGE_DIR = "images"; private static final String APIDOC_DIR = "apidoc"; private static final String DEFAULT_COMPANY_NAME = "jCoderZ.org"; private static final String DEFAULT_COMPANY_LOGO = "jcoderz-org"; private static final boolean DEFAULT_VALIDATION_ONLY_FLAG = false; /** The output directory. */ private File mOutDir; /** XEP home directory. */ private File mXepHome; /** The input file. */ private File mInFile; /** terminate ant build on error. */ private boolean mFailOnError; /** Type of document. (SAD|UseCase) */ private String mType; /** Format of document. (HTML|PDF|ALL) */ private String mFormat; private String mTypeLowerCase; private final Path mDocletPath = new Path(getProject()); private final Path mClassPath = new Path(getProject()); private final List mFormatters = new ArrayList(); /** Source path - list of SourceDirectory. */ private final List mSources = new ArrayList(); /** Cruise Control label */ private String mCcLabel; /** company name */ private String mCompanyName = DEFAULT_COMPANY_NAME; /** company logo without suffix */ private String mCompanyLogo = DEFAULT_COMPANY_LOGO; /** flag for execution of validation tasks only */ private boolean mValidationOnly = DEFAULT_VALIDATION_ONLY_FLAG; /** List of Variables set as Properties in the Transformer context. */ private final List mTransformerProperties = new ArrayList(); /** * Add the given property to be sent to the transformer. * * @param var the property to be sent to the transformer. */ public void addParam (org.apache.tools.ant.types.Environment.Variable var) { mTransformerProperties.add(var); } void setXdocTransformerParams (Transformer transformer) { // TODO: Implement this in the corresponding first pass style // sheets // or remove this! transformer.setParameter("basedir", getProject().getBaseDir() .toString()); transformer.setParameter("cclabel", mCcLabel); transformer.setParameter("user", System.getProperty("user.name")); transformer.setParameter("companyname", mCompanyName); transformer.setParameter("companylogo", mCompanyLogo); final Iterator i = mTransformerProperties.iterator(); while (i.hasNext()) { final org.apache.tools.ant.types.Environment.Variable var = (org.apache.tools.ant.types.Environment.Variable) i .next(); transformer.setParameter(var.getKey(), var.getValue()); } } /** * Sets the XML input file that contains the document. * * @param f the XML input file (log message info). */ public void setIn (File f) { mInFile = f; } /** * Set the destination directory into which the result files should * be copied to. This parameter is required. * * @param dir the name of the destination directory. */ public void setOut (File dir) { mOutDir = dir; } /** * Set the XEP home directory. * * @param dir the name of the XEP home directory. */ public void setXephome (File dir) { mXepHome = dir; } /** * Set the document type. * * @param type the document type. */ public void setType (String type) { mType = type; mTypeLowerCase = type.toLowerCase(Constants.SYSTEM_LOCALE); } /** * Set the document format. * * @param format the document format. */ public void setFormat (String format) { mFormat = format; } /** * Set the document type. * * @param label the cruise control label. */ public void setCclabel (String label) { mCcLabel = label; } /** * Set the name of the company or organisation. * * @param companyName The mCompanyName to set. */ public void setCompanyName (String companyName) { mCompanyName = companyName; } /** * Set the flag, whether only validation should be executed or not. * * @param validationOnly The mValidationOnly to set. */ public void setValidationOnly (boolean validationOnly) { mValidationOnly = validationOnly; } /** * Set the name of the company logo without suffix. * * @param companyLogo The mCompanyLogo to set. */ public void setCompanyLogo (String companyLogo) { mCompanyLogo = companyLogo; } /** * Set whether we should fail on an error. * * @param b Whether we should fail on an error. */ public void setFailonerror (boolean b) { mFailOnError = b; } /** * Additional path that is used to find the javadoc doclets. * * @return a path. */ public Path createDocletpath () { return mDocletPath; } /** * The classpath that is used to find the classes for the DocBook * formatters. * * @return a path. */ public Path createClasspath () { return mClassPath; } /** * Creates a new FormatterInfoData object used as nested element to * describe the DocBook formatters. * * @return a new FormatterInfoData object. */ public FormatterInfoData createFormatter () { final FormatterInfoData result = FormatterInfoData.create(); mFormatters.add(result); return result; } /** * Returns the classpath element. * * @return the classpath element. */ public Path getClassPath () { return mClassPath; } /** * Returns <tt>true</tt> if this task (or subtasks) should fail on * any error; <tt>false</tt> otherwise. * * @return <tt>true</tt> if this task (or subtasks) should fail on * any error; <tt>false</tt> otherwise. */ public boolean failOnError () { return mFailOnError; } /** * Set the source path to be used for this task run. * * @param src an Ant FileSet object containing the compilation * source path. */ public void addSrc (SourceDirectory src) { mSources.add(src); } /** * Execute this task. * * @throws BuildException An building exception occurred. */ public void execute () throws BuildException { try { checkAttributes(); log("Generating documentation into directory " + mOutDir); final File imageDir = new File(mOutDir, IMAGE_DIR); // convertPackageHtml2DocBook(); final File filePassOne = transformPassOne(mInFile); if (TYPE_SAD.equals(mType)) { generateApiDocs(filePassOne); generateSadDiagrams(filePassOne); } else if (TYPE_USE_CASE.equals(mType)) { if (!mValidationOnly) { generateUseCaseDiagrams(filePassOne, imageDir); exportToXmi(filePassOne, imageDir); } } else if (TYPE_TEST_SPEC.equals(mType)) { // Nothing to do } else if (TYPE_QUALITY_REPORT.equals(mType)) { // Nothing to do } else { throw new RuntimeException("Unsupported type " + mType); } if (!mValidationOnly) { if (isOutputEnabled(FORMAT_HTML)) { rasterizeSvgFiles(imageDir); } if (isOutputEnabled(FORMAT_PDF)) { scaleSvgImages(imageDir); } } if (TYPE_TEST_SPEC.equals(mType)) { renderDocbookFilesFromPassOne(filePassOne); } else { final File docBookFile = transformPassTwo(filePassOne); renderDocBook(docBookFile, mInFile); } } catch (BuildException e) { if (mFailOnError) { throw e; } log(e.getMessage(), Project.MSG_ERR); } } private boolean isOutputEnabled (String format) { final boolean result; if (mFormat == null || mFormat.equals(FORMAT_ALL) || mFormat.equals(format)) { result = true; } else { result = false; } return result; } File getXepHome () { return mXepHome; } private void renderDocBook (File docBookFile, File inFile) { for (final Iterator i = mFormatters.iterator(); i.hasNext();) { final FormatterInfoData f = (FormatterInfoData) i.next(); final Formatter formatter = Formatter.getInstance(f); final File out = new File(docBookFile.getParentFile(), AntTaskUtil .stripFileExtension(inFile.getName()) + "." + formatter.getFileExtension()); if (isOutputEnabled(formatter.getInfoData().getType())) { formatter.transform(this, docBookFile, out); } } } private void renderDocbookFilesFromPassOne (File filePassOne) { File docbookDir = new File(filePassOne.getParent()); transformPassTwo(filePassOne); log("Search files to render in directory: " + docbookDir.getParent()); final File[] docbookFiles = docbookDir.listFiles(new FilenameFilter() { public boolean accept (File dir, String name) { final boolean result; if (name.endsWith(".p2")) { result = true; } else { result = false; } return result; } }); if (docbookFiles != null) { for (int i = 0; i < docbookFiles.length; i++) { final File docbookFile = docbookFiles[i]; final File passOneFile = new File(AntTaskUtil .stripFileExtension(AntTaskUtil .stripFileExtension(docbookFile.getName()))); renderDocBook(docbookFile, passOneFile); log("Will render file: " + docbookFile.getName(), Project.MSG_VERBOSE); } } else { log("No .xml files found to render", Project.MSG_VERBOSE); } } private File transformPassOne (File in) { final XsltBasedTask task = new XsltBasedTask() { String getDefaultStyleSheet () { return mTypeLowerCase + "-pass-one.xsl"; } void setAdditionalTransformerParameters (Transformer transformer) { setXdocTransformerParams(transformer); } }; task.setProject(getProject()); task.setTaskName(mTypeLowerCase + "2db:p1"); task.setIn(in); task.setForce(true); // FIXME final File outFile = new File(mOutDir, in.getName() + ".p1"); task.setOut(outFile); task.setFailonerror(mFailOnError); task.setDestdir(outFile.getParentFile()); task.execute(); return outFile; } private File transformPassTwo (File filePassOne) { final XsltBasedTask task = new XsltBasedTask() { String getDefaultStyleSheet () { return mTypeLowerCase + "-pass-two.xsl"; } void setAdditionalTransformerParameters (Transformer transformer) { setXdocTransformerParams(transformer); } }; task.setProject(getProject()); task.setTaskName(mTypeLowerCase + "2db:p2"); task.setIn(filePassOne); task.setForce(true); // FIXME final File outFile = new File(mOutDir, filePassOne.getName() + ".p2"); task.setOut(outFile); task.setFailonerror(mFailOnError); task.setDestdir(outFile.getParentFile()); task.execute(); return outFile; } private void generateUseCaseDiagrams (File filePassOne, final File imageDir) { final XsltBasedTask task = new XsltBasedTask() { String getDefaultStyleSheet () { return "usecase_diagrams.xsl"; } void setAdditionalTransformerParameters (Transformer transformer) { transformer.setParameter("basedir", getProject().getBaseDir() .toString()); transformer.setParameter("imagedir", imageDir.toString()); } }; task.setProject(getProject()); task.setTaskName("uc-diagrams"); task.setIn(filePassOne); task.setForce(true); // FIXME final File outFile = new File(mOutDir, "use-case-diagrams" + ".tmp"); task.setOut(outFile); task.setFailonerror(mFailOnError); task.setDestdir(outFile.getParentFile()); task.execute(); // .dot files -> .svg files AntTaskUtil.renderDotFiles(this, imageDir, mFailOnError); } private void exportToXmi (File filePassOne, final File imageDir) { final XsltBasedTask task = new XsltBasedTask() { String getDefaultStyleSheet () { return "usecase_xmi_export.xsl"; } void setAdditionalTransformerParameters (Transformer transformer) { transformer.setParameter("basedir", getProject().getBaseDir() .toString()); transformer.setParameter("imagedir", imageDir.toString()); } }; task.setProject(getProject()); task.setTaskName("uc-xmi"); task.setIn(filePassOne); task.setForce(true); // FIXME final File outFile = new File(mOutDir, "use-case-xmi" + ".tmp"); task.setOut(outFile); task.setFailonerror(mFailOnError); task.setDestdir(outFile.getParentFile()); task.execute(); // .dot files -> .svg files AntTaskUtil.renderDotFiles(this, imageDir, mFailOnError); } private void generateSadDiagrams (File in) { final DiagramTask task = new DiagramTask(); task.setTaskName(DiagramTask.NAME); task.setProject(getProject()); task.setIn(in); for (final Iterator i = mSources.iterator(); i.hasNext();) { final SourceDirectory src = (SourceDirectory) i.next(); task.addSrc(src); } task.setFailonerror(mFailOnError); final File out = new File(mOutDir, IMAGE_DIR); task.setOut(out); task.setDocletPath(mDocletPath); task.execute(); } private void scaleSvgImages (File dir) { final XsltBatchProcessor x = new XsltBatchProcessor(); x.setProject(getProject()); x.setTaskName("svg-scale"); x.setFailonerror(mFailOnError); x.setXsl("svg-image-transform.xsl"); x.resolveExternalEntities(false); final FileSet fs = new FileSet(); fs.setDir(dir); fs.setIncludes("*.svg"); x.addFiles(fs); x.execute(); } private void generateApiDocs (File in) { final ApiDocTask task = new ApiDocTask(); task.setTaskName(ApiDocTask.NAME); task.setProject(getProject()); task.setIn(in); for (final Iterator i = mSources.iterator(); i.hasNext();) { final SourceDirectory src = (SourceDirectory) i.next(); task.addSrc(src); } task.setFailonerror(mFailOnError); final File out = new File(mOutDir, APIDOC_DIR); out.mkdirs(); task.setOut(out); task.setDocletPath(mDocletPath); task.execute(); // Transform to DocBook final XsltBatchProcessor x = new XsltBatchProcessor(); x.setProject(getProject()); x.setTaskName("java2docbook"); x.setFailonerror(mFailOnError); x.setXsl("java2docbook.xsl"); final FileSet fs = new FileSet(); fs.setDir(out); fs.setIncludes("*.xml"); x.addFiles(fs); x.execute(); } /** * Checks the attributes provided by this class. * * @throws BuildException */ private void checkAttributes () throws BuildException { checkAttributeInFile(); XsltBasedTask.checkXercesVersion(this); } private void checkAttributeInFile () { if (mInFile == null) { throw new BuildException("Missing mandatory attribute 'in'.", getLocation()); } if (!mInFile.exists()) { throw new BuildException("Input file '" + mInFile + "' not found.", getLocation()); } } private void rasterizeSvgFiles (File directory) { final File[] svgFiles = directory.listFiles(new FilenameFilter() { public boolean accept (File dir, String name) { final boolean result; if (name.endsWith(".svg")) { result = true; } else { result = false; } return result; } }); log("Creating raster images for " + svgFiles.length + " images", Project.MSG_INFO); for (int i = 0; i < svgFiles.length; i++) { final File svgFile = svgFiles[i]; try { log("Creating raster image for '" + svgFile.getCanonicalPath() + "'", Project.MSG_VERBOSE); /* * final String[] args = new String[] { "-maxw", * "700.0", "-scriptSecurityOff", * svgFile.getCanonicalPath()}; final Main conv = new * Main(args); // execute the conversion conv.execute(); */ final File pngFile = new File(svgFile.getParentFile(), svgFile .getName().substring(0, svgFile.getName().indexOf('.')) + ".png"); Rasterizer.rasterize(svgFile, pngFile); } catch (Exception ex) { throw new BuildException( "Could not generate raster image for '" + svgFile.getName() + "' (" + ex + ")"); } } } private static final class Rasterizer { private static final PNGTranscoder TRANSCODER; static { TRANSCODER = new PNGTranscoder(); // force Xerces as XML Reader TRANSCODER.addTranscodingHint( XMLAbstractTranscoder.KEY_XML_PARSER_CLASSNAME, "org.apache.xerces.parsers.SAXParser"); } private Rasterizer () { // utility class -- provides only static methods } public static void rasterize (File in, File out) throws TranscoderException, IOException { final OutputStream ostream = new FileOutputStream(out); try { // Create the transcoder input final TranscoderInput input = new TranscoderInput( new FileInputStream(in)); input.setURI(in.toURL().toExternalForm()); // Create the transcoder output final TranscoderOutput output = new TranscoderOutput(ostream); // Transform the SVG document into a PNG image TRANSCODER.transcode(input, output); ostream.flush(); } finally { IoUtil.close(ostream); } } } /** * The Class FormatterInfoData. */ public static class FormatterInfoData { private File mStyleSheet; private File mCascadingStyleSheet; private String mType; /** * Gets the cascading style sheet. * * @return the cascading style sheet */ public File getCascadingStyleSheet () { return mCascadingStyleSheet; } /** * Sets the cascading style sheet. * * @param cascadingStyleSheet the new cascading style sheet */ public void setCss (File cascadingStyleSheet) { mCascadingStyleSheet = cascadingStyleSheet; } /** * Gets the style sheet. * * @return the style sheet */ public File getStyleSheet () { return mStyleSheet; } /** * Sets the style. * * @param styleSheet the new style */ public void setStyle (File styleSheet) { mStyleSheet = styleSheet; } /** * Gets the type. * * @return the type */ public String getType () { return mType; } /** * Sets the type. * * @param type the new type */ public void setType (String type) { mType = type; } /** * Create the formatter info data. * * @return the formatter info data */ public static FormatterInfoData create () { return new FormatterInfoData(); } } }
package test.org.relique.jdbc.csv; import java.io.StringReader; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.relique.jdbc.csv.ExpressionParser; import org.relique.jdbc.csv.ParseException; import org.relique.jdbc.csv.SqlParser; import org.relique.jdbc.csv.TokenMgrError; /** * This class is used to test the SqlParser class. * * @author Jonathan Ackerman * @version $Id: TestSqlParser.java,v 1.23 2011/10/25 17:24:38 simoc Exp $ */ public class TestSqlParser extends TestCase { public TestSqlParser(String name) { super(name); } public void testParserSimple() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT location, parameter, ts, waarde, unit FROM total"); assertTrue("Incorrect table name", parser.getTableName() .equals("total")); String[] colNames = parser.getColumnNames(); assertTrue("Incorrect Column Count", colNames.length == 5); assertEquals("Incorrect Column Name Col 0", colNames[0].toLowerCase(), "location"); assertEquals("Incorrect Column Name Col 1", colNames[1].toLowerCase(), "parameter"); assertEquals("Incorrect Column Name Col 2", colNames[2].toLowerCase(), "ts"); assertEquals("Incorrect Column Name Col 3", colNames[3].toLowerCase(), "waarde"); assertEquals("Incorrect Column Name Col 4", colNames[4].toLowerCase(), "unit"); parser .parse("SELECT location, parameter, ts, name.suffix as value FROM total"); assertTrue("Incorrect table name", parser.getTableName() .equals("total")); assertEquals("Incorrect Column Count", 4, parser.getColumns().size()); List cols = parser.getColumns(); assertEquals("Incorrect Column Count", 4, cols.size()); Object[] colSpec = (Object[]) cols.get(3); assertEquals("Incorrect Column Name Col 3", "VALUE", colSpec[0] .toString()); assertEquals("Incorrect Column Name Col 3", "[NAME.SUFFIX]", colSpec[1] .toString()); try { String query = "SELECT location!parameter FROM total"; parser.parse(query); fail("incorrect query '" + query + "' parsed as correct"); } catch (Exception e) { } parser.parse("SELECT location+parameter FROM total"); colNames = parser.getColumnNames(); assertEquals("Incorrect Column Name Col 1", "+ [LOCATION] [PARAMETER]", colNames[0]); parser.parse("SELECT location-parameter FROM total"); colNames = parser.getColumnNames(); assertEquals("Incorrect Column Name Col 1", "- [LOCATION] [PARAMETER]", colNames[0]); parser.parse("SELECT location*parameter FROM total"); colNames = parser.getColumnNames(); assertEquals("Incorrect Column Name Col 1", "* [LOCATION] [PARAMETER]", colNames[0]); } public void testParser() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT FLD_A,FLD_B, TEST, H FROM test"); assertTrue("Incorrect table name", parser.getTableName().equals("test")); String[] cols = parser.getColumnNames(); assertTrue("Incorrect Column Count", cols.length == 4); assertTrue("Incorrect Column Name Col 0", cols[0].equals("FLD_A")); assertTrue("Incorrect Column Name Col 1", cols[1].equals("FLD_B")); assertTrue("Incorrect Column Name Col 2", cols[2].equals("TEST")); assertTrue("Incorrect Column Name Col 3", cols[3].equals("H")); } public void testLiteralAsAlias() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT 'abc' as FLD_A, 123 as FLD_B FROM test"); assertTrue("Incorrect table name", parser.getTableName().equals("test")); String[] cols = parser.getColumnNames(); assertTrue("Incorrect Column Count", cols.length == 2); assertTrue("Column Name Col 0 '" + cols[0] + "' is not equal FLD_A", cols[0].equalsIgnoreCase("fld_a")); assertTrue("Column Name Col 1 '" + cols[1] + "' is not equal FLD_B", cols[1].equalsIgnoreCase("FLD_B")); } public void testFieldAsAlias() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT abc as FLD_A, eee as FLD_B FROM test"); assertTrue("Incorrect table name", parser.getTableName().equals("test")); String[] cols = parser.getColumnNames(); assertTrue("Incorrect Column Count", cols.length == 2); assertTrue("Column Name Col 0 '" + cols[0] + "' is not equal FLD_A", cols[0].equalsIgnoreCase("fld_a")); assertTrue("Column Name Col 1 '" + cols[1] + "' is not equal FLD_B", cols[1].equalsIgnoreCase("FLD_B")); } /** * this case is only partially decoded by the parser... * * @throws Exception */ public void testAllColumns() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT * FROM test"); assertTrue("Incorrect table name", parser.getTableName().equals("test")); String[] cols = parser.getColumnNames(); assertEquals("Incorrect Column Count", 1, cols.length); } /** * Test that where conditions are handled correctly * * @throws Exception */ public void testWhereCorrect() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT FLD_A, FLD_B FROM test WHERE FLD_A = 20"); assertEquals("Incorrect table name", "test", parser.getTableName()); parser.parse("SELECT FLD_A, FLD_B FROM test WHERE FLD_A = '20'"); assertEquals("Incorrect table name", "test", parser.getTableName()); parser.parse("SELECT FLD_A,FLD_B FROM test WHERE FLD_A =20"); assertEquals("Incorrect table name", "test", parser.getTableName()); parser.parse("SELECT FLD_A FROM test WHERE FLD_A=20"); assertEquals("Incorrect table name", "test", parser.getTableName()); parser.parse("SELECT FLD_A, FLD_B FROM test WHERE FLD_B='Test Me'"); assertEquals("Incorrect table name", "test", parser.getTableName()); } /** * Test that where conditions with AND operator are parsed correctly * * @throws Exception */ public void testWhereParsing() throws Exception { SqlParser parser = new SqlParser(); ExpressionParser whereClause; parser.parse("SELECT * FROM test WHERE A='20'"); whereClause = parser.getWhereClause(); assertNotNull("query has a WHERE clause", whereClause); assertEquals("Incorrect WHERE", "= [A] '20'", whereClause.toString()); parser.parse("SELECT * FROM test WHERE A='20' AND B='AA'"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "AND = [A] '20' = [B] 'AA'", whereClause.toString()); parser.parse("SELECT * FROM test WHERE A='20' OR B='AA'"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "OR = [A] '20' = [B] 'AA'", whereClause .toString()); parser.parse("SELECT * FROM test WHERE A='20' OR B='AA' AND c=1"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "OR = [A] '20' AND = [B] 'AA' = [C] 1", whereClause.toString()); parser.parse("SELECT * FROM test WHERE (A='20' OR B='AA') AND c=1"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "AND OR = [A] '20' = [B] 'AA' = [C] 1", whereClause.toString()); } public void testWhereMoreParsing() throws Exception { SqlParser parser = new SqlParser(); String query; try { query = "SELECT * FROM test WHERE FLD_A = '20' AND AND = 'AA'"; parser.parse(query); fail("incorrect query '" + query + "' parsed as correct"); } catch (ParseException e) { } try { query = "SELECT * FROM test WHERE = 'AA'"; parser.parse(query); fail("incorrect query '" + query + "' parsed as correct"); } catch (ParseException e) { } try { query = "SELECT * FROM test WHERE FLD_A = '20' = 'AA'"; parser.parse(query); fail("incorrect query '" + query + "' parsed as correct"); } catch (ParseException e) { } parser.parse("SELECT * FROM test WHERE B IS NULL"); ExpressionParser whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "N [B]", whereClause.toString()); parser.parse("SELECT * FROM test WHERE B BETWEEN '20' AND 'AA'"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "B [B] '20' 'AA'", whereClause .toString()); parser.parse("SELECT * FROM test WHERE B LIKE '20 AND AA'"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "L [B] '20 AND AA'", whereClause .toString()); parser .parse("SELECT * FROM test WHERE B IS NULL OR B BETWEEN '20' AND 'AA' AND B LIKE '20 AND AA'"); whereClause = parser.getWhereClause(); assertEquals("Incorrect WHERE", "OR N [B] AND B [B] '20' 'AA' L [B] '20 AND AA'", whereClause .toString()); try { query = "SELECT * FROM test WHERE a=0 AND FLD_A"; parser.parse(query); fail("incorrect query '" + query + "' parsed as correct"); } catch (ParseException e) { } } /** * Test that where conditions with AND operator are parsed correctly * * @throws Exception */ public void testWhereEvaluating() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); parser.parse("SELECT * FROM test WHERE c=1"); env.clear(); env.put("C", new Integer("1")); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c='1'"); env.clear(); env.put("C", new String("1")); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c=1.0"); env.clear(); env.put("C", new Double("1.0")); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE (A='20' OR B='AA') AND c=1"); ExpressionParser whereClause = parser.getWhereClause(); env.clear(); env.put("A", new String("20")); env.put("B", new String("AA")); env.put("C", new Integer("1")); assertEquals(true, whereClause.isTrue(env)); env.put("A", new Double("20")); assertEquals(true, whereClause.isTrue(env)); env.put("B", new String("")); assertEquals(false, whereClause.isTrue(env)); env.put("A", new String("20")); assertEquals(true, whereClause.isTrue(env)); env.put("C", new Integer("3")); assertEquals(false, whereClause.isTrue(env)); } /** * Test that where conditions with AND operator are parsed correctly * * @throws Exception */ public void testWhereComparisons() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); env.put("C", new Integer("12")); parser.parse("SELECT * FROM test WHERE c=1"); assertEquals(false, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c<1"); assertEquals(false, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c>1"); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c<=1"); assertEquals(false, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c>=1"); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c<=12"); assertEquals(true, parser.getWhereClause().isTrue(env)); parser.parse("SELECT * FROM test WHERE c>=12"); assertEquals(true, parser.getWhereClause().isTrue(env)); } public void testParsingWhereEmptyString() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); env.put("C", new String("")); parser.parse("SELECT * FROM test WHERE c=''"); assertEquals(true, parser.getWhereClause().isTrue(env)); } public void testParsingWhereSingleQuoteString() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); env.put("C", new String("it's")); parser.parse("SELECT * FROM test WHERE c='it''s'"); assertEquals(true, parser.getWhereClause().isTrue(env)); } public void testWhereEvaluatingIndistinguishedNumbers() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); parser.parse("SELECT * FROM test WHERE c=1.0"); env.clear(); env.put("C", new Integer("1")); assertEquals(true, parser.getWhereClause().isTrue(env)); env.put("C", new Double("1")); assertEquals(true, parser.getWhereClause().isTrue(env)); env.put("C", new Float("1")); assertEquals(true, parser.getWhereClause().isTrue(env)); } public void testWhereEvaluatingIndistinguishedNegativeNumbers() throws Exception { SqlParser parser = new SqlParser(); Map env = new HashMap(); parser.parse("SELECT * FROM test WHERE c=-1.0"); env.clear(); env.put("C", new Integer("-1")); assertEquals(true, parser.getWhereClause().isTrue(env)); env.put("C", new Double("-1")); assertEquals(true, parser.getWhereClause().isTrue(env)); env.put("C", new Float("-1")); assertEquals(true, parser.getWhereClause().isTrue(env)); } public void testParsingQueryEnvironmentEntries() throws Exception { ExpressionParser cs; cs = new ExpressionParser(new StringReader("*")); cs.parseQueryEnvEntry(); assertEquals("*: *", cs.toString()); cs = new ExpressionParser(new StringReader("A")); cs.parseQueryEnvEntry(); assertEquals("A: [A]", cs.toString()); cs = new ExpressionParser(new StringReader("123 A")); cs.parseQueryEnvEntry(); assertEquals("A: 123", cs.toString()); cs = new ExpressionParser(new StringReader("123+2 A")); cs.parseQueryEnvEntry(); assertEquals("A: + 123 2", cs.toString()); cs = new ExpressionParser(new StringReader("123/2 A")); cs.parseQueryEnvEntry(); assertEquals("A: / 123 2", cs.toString()); cs = new ExpressionParser(new StringReader("123/-2 A")); cs.parseQueryEnvEntry(); assertEquals("A: / 123 -2", cs.toString()); cs = new ExpressionParser(new StringReader("'123' A")); cs.parseQueryEnvEntry(); assertEquals("A: '123'", cs.toString()); cs = new ExpressionParser(new StringReader("A+B AS sum")); cs.parseQueryEnvEntry(); assertEquals("SUM: + [A] [B]", cs.toString()); cs = new ExpressionParser(new StringReader("A+B sum")); cs.parseQueryEnvEntry(); assertEquals("SUM: + [A] [B]", cs.toString()); cs = new ExpressionParser(new StringReader("B+C+'123' t1")); cs.parseQueryEnvEntry(); assertEquals("T1: + + [B] [C] '123'", cs.toString()); cs = new ExpressionParser(new StringReader("loc * par")); cs.parseQueryEnvEntry(); assertEquals("* [LOC] [PAR]: * [LOC] [PAR]", cs.toString()); cs = new ExpressionParser(new StringReader("123")); cs.parseQueryEnvEntry(); assertEquals("123: 123", cs.toString()); cs = new ExpressionParser(new StringReader("123+2")); cs.parseQueryEnvEntry(); assertEquals("+ 123 2: + 123 2", cs.toString()); cs = new ExpressionParser(new StringReader("'123'")); cs.parseQueryEnvEntry(); assertEquals("'123': '123'", cs.toString()); cs = new ExpressionParser(new StringReader("UPPER(A)")); cs.parseQueryEnvEntry(); assertEquals("UPPER([A]): UPPER([A])", cs.toString()); } public void testParsingQueryEnvironmentWithoutExpressions() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT A FROM test"); assertEquals("[A]", parser.getExpression(0).toString()); parser.parse("SELECT 123 a FROM test"); assertEquals("123", parser.getExpression(0).toString()); parser.parse("SELECT '123' a FROM test"); assertEquals("'123'", parser.getExpression(0).toString()); } public void testParsingQueryEnvironmentWithExpressions() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT A+B AS SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); parser.parse("SELECT A+B SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); parser.parse("SELECT A+B SUM, B+C+'123' t12 FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); assertEquals("+ + [B] [C] '123'", parser.getExpression(1).toString()); } public void testEvaluateBinaryOperationsSum() throws Exception { ExpressionParser cs; cs = new ExpressionParser(new StringReader("A+b AS result")); cs.parseQueryEnvEntry(); Map env = new HashMap(); env.put("A", new Integer(1)); env.put("B", new Integer(1)); assertEquals((Object)(new Integer("2")), cs.eval(env)); env.put("A", new Double(1)); assertEquals((Object)(new Double("2")), cs.eval(env)); env.put("A", new String("1")); assertEquals("11", ""+cs.eval(env)); } public void testEvaluateBinaryOperationsOtherThanSum() throws Exception { ExpressionParser cs; cs = new ExpressionParser(new StringReader("a-b AS result")); cs.parseQueryEnvEntry(); Map env = new HashMap(); env.put("A", new Integer(5)); env.put("B", new Integer(1)); assertEquals((Object)(new Integer("4")), cs.eval(env)); env.put("B", new Double(1)); assertEquals((Object)(new Double("4")), cs.eval(env)); cs = new ExpressionParser(new StringReader("a*b AS result")); cs.parseQueryEnvEntry(); env.put("B", new Integer(1)); assertEquals((Object)(new Integer("5")), cs.eval(env)); env.put("B", new Double(1)); assertEquals((Object)(new Double("5")), cs.eval(env)); cs = new ExpressionParser(new StringReader("a/b AS result")); cs.parseQueryEnvEntry(); env.put("B", new Integer(2)); assertEquals((Object)(new Integer("2")), cs.eval(env)); env.put("B", new Double(2)); assertEquals((Object)(new Double("2.5")), cs.eval(env)); } public void testParsingIgnoresCase() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT A+B AS SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); parser.parse("SELECT A+B As SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); parser.parse("SELECT A+B aS SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); parser.parse("SELECT A+B as SUM FROM test"); assertEquals("+ [A] [B]", parser.getExpression(0).toString()); } public void testParsingTableAlias() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT Ab.Name FROM sample AS Ab WHERE Ab.ID='A123'"); assertEquals("AB", parser.getTableAlias()); } public void testParsingWithNewlines() throws Exception { SqlParser parser = new SqlParser(); parser.parse("\r\nSELECT NAME\r\nas FLD_A\r\nFROM test\r\nWHERE ID=1\r\n"); assertTrue("Incorrect table name", parser.getTableName().equals("test")); String[] cols = parser.getColumnNames(); assertTrue("Incorrect Column Count", cols.length == 1); assertTrue("Column Name Col 0 '" + cols[0] + "' is not equal FLD_A", cols[0].equalsIgnoreCase("fld_a")); } public void testParsingComma() throws Exception { SqlParser parser = new SqlParser(); parser.parse("SELECT Id + ',' + Name FROM sample"); assertEquals("+ + [ID] ',' [NAME]", parser.getExpression(0).toString()); } public void testParsingQuotedFrom() throws Exception { SqlParser parser = new SqlParser(); ExpressionParser whereClause; parser.parse("SELECT Id FROM sample where Signature = 'sent from my iPhone'"); whereClause = parser.getWhereClause(); assertNotNull("query has a WHERE clause", whereClause); assertEquals("Incorrect WHERE", "= [SIGNATURE] 'sent from my iPhone'", whereClause.toString()); } }
package net.katsuster.strview.io; import net.katsuster.strview.util.*; /** * <p> * * </p> * * <p> * ByteToBitList MemoryByteList * </p> */ public class MemoryBitList extends AbstractLargeBitList { // 1 2 public static final int ELEM_SHIFT = 5; public static final int ELEM_BITS = (1 << ELEM_SHIFT); public static final int ELEM_MASK = (1 << ELEM_SHIFT) - 1; private int[] buf; /** * <p> * 0 * </p> */ public MemoryBitList() { this(0); } public MemoryBitList(long len) { super(len); boolean[] array; if (len == LENGTH_UNKNOWN) { array = new boolean[0]; } else { array = new boolean[(int)len]; } buf = new int[getBufferElementPosition(array.length + ELEM_MASK)]; length(array.length); getRange().setLength(array.length); set(0, array, 0, array.length); } public MemoryBitList(boolean[] array) { super(0); if (array == null) { throw new IllegalArgumentException( "array is null."); } buf = new int[getBufferElementPosition(array.length + ELEM_MASK)]; length(array.length); getRange().setLength(array.length); set(0, array, 0, array.length); } @Override public MemoryBitList clone() throws CloneNotSupportedException { MemoryBitList obj = (MemoryBitList)super.clone(); obj.buf = buf.clone(); return obj; } @Override protected Boolean getInner(long index) { int b, p, shifts; b = getBufferElementPosition(index); p = getElementBitPosition(index); shifts = ELEM_MASK - p; if (((getElement(b) >>> shifts) & 1) == 1) { return true; } else { return false; } } @Override protected void setInner(long index, Boolean data) { int b, p, shifts; int t; b = getBufferElementPosition(index); p = getElementBitPosition(index); shifts = ELEM_MASK - p; t = getElement(b); t &= ~(1 << shifts); if (data) { t |= (1 << shifts); } setElement(b, t); } @Override protected long getPackedLongInner(long index, int n) { int epos, remain; int elem; long result = 0; epos = getBufferElementPosition(index); remain = ELEM_BITS - getElementBitPosition(index); elem = getElement(epos); while (n > remain) { n -= remain; result |= (getRightBits64(remain, elem) << n); epos += 1; elem = getElement(epos); // ELEM_BITS remain = ELEM_BITS; } if (n > 0) { result |= getRightBits64(n, elem >>> (remain - n)); } return result; } @Override protected void setPackedLongInner(long index, int n, long val) { int epos, remain; int elem; epos = getBufferElementPosition(index); remain = ELEM_BITS - getElementBitPosition(index); elem = getElement(epos); while (n > remain) { n -= remain; elem &= ~(getRightBits64(remain, 0xffffffffffffffffL)); elem |= getRightBits64(remain, val >>> n); setElement(epos, elem); epos += 1; elem = getElement(epos); // ELEM_BITS remain = ELEM_BITS; } if (n > 0) { elem &= ~(getRightBits64(n, 0xffffffffffffffffL) << (remain - n)); elem |= getRightBits64(n, val) << (remain - n); setElement(epos, elem); } } /** * <p> * n * </p> * * @param n * @return */ private int getBufferElementPosition(long n) { return (int)(n >>> ELEM_SHIFT); } /** * <p> * n * * </p> * * @param n * @return */ private int getElementBitPosition(long n) { return (int)(n & ELEM_MASK); } /** * <p> * * </p> * * @param n * @return */ private int getElement(int n) { return buf[n]; } /** * <p> * * </p> * * @param n * @param v */ private void setElement(int n, int v) { buf[n] = v; } }
/** * CodeWriter -- Andrew C. Myers, March 2001 */ package jltools.util; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.io.IOException; import java.util.Vector; /** * A <code>CodeWriter</code> is a pretty-printing engine. * It formats structured text onto an output stream <code>o</code> in the * minimum number of lines, while keeping the width of the output * within <code>width</code> characters if possible. */ public class CodeWriter { /** * Create a CodeWriter object with output stream <code>o</code> * and width <code>width_</code>. */ public CodeWriter(OutputStream o, int width_) { output = new OutputStreamWriter(o); width = width_; current = input = new Block(null, 0); } /** * Create a CodeWriter object with output <code>w</code> and * width <code>width_</code>. */ public CodeWriter(Writer w, int width_) { output = w; width = width_; current = input = new Block(null, 0); } /** Print the string <code>s</code> verbatim on the output stream. */ public void write(String s) { if (s.length() > 0) current.add(new StringItem(s)); } /** Force a newline with no added indentation. */ public void newline() { newline(0); } /** * Start a new block with a relative indentation of <code>n</code> * characters. * <br> * A block is a formatting unit. The formatting algorithm will try * to put the whole block in one line unless * <ul> * <li>there is a <code>newline</code> item in the block.</li> * <li>the block cannot fit in one line.</li> * </ul> * If either of the two conditions is satisfied, the * formatting algorithm will break the block into lines: every * <code>allowBreak</code> will cause a line change, the first line * is printed at the current cursor position <code>pos</code>, * all the following lines are printed at the position * <code>pos+n</code>. * * @param n the number of characters increased on indentation (relative * to the current position) for all lines in the block. */ public void begin(int n) { Block b = new Block(current, n); current.add(b); current = b; } /** * Terminate the most recent outstanding <code>begin</code>. */ public void end() { current = current.parent; if (current == null) throw new RuntimeException(); } /** * Allow a newline. Indentation will be preserved. * If no newline is inserted, a single space character is output instead. * * @param n the amount of increase in indentation if * the newline is inserted. */ public void allowBreak(int n) { current.add(new AllowBreak(n, " ")); } /** * Allow a newline. Indentation will be preserved. * * @param n the amount of increase in indentation if * the newline is inserted. * @param alt if no newline is inserted, the string <code>alt</code> is * output instead. */ public void allowBreak(int n, String alt) { current.add(new AllowBreak(n, alt)); } /** * Force a newline. Indentation will be preserved. This method * should be used sparingly; usually a call to <code>allowBreak</code> is * preferable because forcing a newline also causes all breaks * in containing blocks to be broken. */ public void newline(int n) { current.add(new Newline(n)); } /** * Send out the current batch of text to be formatted. All * outstanding <code>begin</code>'s are closed and the current * indentation level is reset to 0. Returns true if formatting * was completely successful (the margins were obeyed). */ public boolean flush() throws IOException { boolean success = true; try { input.format1(0, 0, width, width, true, true); } catch (Overrun e) { success = false; } input.sendOutput(output, 0, 0); output.flush(); input.free(); current = input = new Block(null, 0); return success; } Block input; Block current; Writer output; int width; public static final boolean debug = false; } /** * An <code>Overrun</code> represents a formatting that failed because the right * margin was exceeded by at least <code>amount</code> chars. */ class Overrun extends Exception { int amount; Overrun(int amount_) { amount = amount_; if (CodeWriter.debug) System.err.println("Overrun: " + amount); } } /** * An <code>Item</code> is a piece of input handed to the formatter. It * contains a reference to a possibly empty list of items that follow it. */ abstract class Item { Item next; protected Item() { next = null; } /** * Try to format this item. The current cursor position is * <code>pos</code>, left and right margins are as * specified. Returns the final position, which must be * <code>&lt; fin</code>. If breaks may be broken, * <code>can_break</code> is set. Return the new cursor position * and set any contained breaks appropriately if formatting was * successful. If <code>nofail</code>, formatting is forced to * "succeed" (best effort) even if it doesn't; <code>nofail</code> * requires <code>can_break</code>. * * Requires: rmargin &lt; lmargin, pos &lt;= rmargin. */ abstract int format1(int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun; /** * Send the output associated with this item to <code>o</code>, using the * current break settings. */ abstract int sendOutput(Writer o, int lmargin, int pos) throws IOException; /** Free references to any other items. */ void free() { if( next != null) { next.free(); next = null; } } /** try to format a whole sequence of items in the manner of format1 */ static int formatList(Item it, int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun { if (CodeWriter.debug) System.err.println("Formatting list " + it + "\n lmargin = " + lmargin + " pos = " + pos + " fin = " + fin + (can_break ? " can break" : " no breaks") + (nofail ? " [no fail]" : "")); int this_fin = rmargin; boolean thisnofail = false; if (it.next == null) this_fin = fin; // this_fin is final position bound for current item. We crank // it in from the right margin as subsequent items overrun. while (true) { int nextpos; try { nextpos = it.format1(lmargin, pos, rmargin, this_fin, can_break, thisnofail); } catch (Overrun o) { if (!nofail) throw o; if (CodeWriter.debug && thisnofail) { System.err.println("Failed with nofail!"); throw o; } thisnofail = true; continue; } if (it.next == null) return nextpos; try { return formatList(it.next, lmargin, nextpos, rmargin, fin, can_break, nofail); } catch (Overrun o) { if (!can_break) throw o; if (nextpos > this_fin) { nextpos = this_fin; if (!nofail) { System.err.println("Formatting failed silently!"); } thisnofail = true; } this_fin = nextpos - o.amount; if (this_fin < lmargin) throw o; if (CodeWriter.debug) System.err.println(" Trying list " + it.next + " again with fin = " + this_fin); // try again! } } } public String toString() { if (next == null) return selfToString(); return selfToString() + "," + next.toString(); } abstract String selfToString(); } /** * A Block is a formatting unit containing a list of other items * to be formatted. */ class Block extends Item { Block parent; Item first; Item last; int indent; Block(Block parent_, int indent_) { parent = parent_; first = last = null; indent = indent_; } /** * Add a new item to the end of the block. Successive * StringItems are concatenated together to limit recursion * depth when formatting. */ void add(Item it) { if (first == null) { first = it; } else { if (it instanceof StringItem && last instanceof StringItem) { StringItem lasts = (StringItem)last; lasts.appendString(((StringItem)it).s); return; } else { last.next = it; } } last = it; } int format1(int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun { if (CodeWriter.debug) System.err.println("Block format " + this + "\n lmargin = " + "lmargin + pos = " + pos + " fin = " + fin + (can_break ? " can break" : " no breaks") + (nofail ? " [no fail]" : "")); if (first == null) return pos; try { return formatList(first, pos + indent, pos, rmargin, fin, false, false); } catch (Overrun overrun) { if (!can_break) throw overrun; try { return formatList(first, pos + indent, pos, rmargin, fin, true, false); } catch (Overrun o) { if (!nofail) throw o; return formatList(first, pos + indent, pos, rmargin, fin, true, true); } } } int sendOutput(Writer o, int lmargin, int pos) throws IOException { Item it = first; lmargin = pos+indent; while (it != null) { pos = it.sendOutput(o, lmargin, pos); it = it.next; } return pos; } void free() { super.free(); parent = null; if( first != null) { first.free(); } last = null; } String selfToString() { return "[" + first.toString() + "]"; } } class StringItem extends Item { String s; StringItem(String s_) { s = s_; } int format1(int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun { pos += s.length(); if (pos > fin && !nofail) throw new Overrun(pos - fin); return pos; } int sendOutput(Writer o, int lm, int pos) throws IOException { o.write(s); return pos + s.length(); } void appendString(String s) { this.s = this.s + s; } String selfToString() { return s; } } class AllowBreak extends Item { int indent; boolean broken = true; String alt; AllowBreak(int n_, String alt_) { indent = n_; alt = alt_; } int format1(int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun { int ret; if (can_break || nofail) { broken = true; ret = lmargin + indent; } else { broken = false; ret = pos + alt.length(); } if (ret > fin && !nofail) throw new Overrun(ret - fin); return ret; } int sendOutput(Writer o, int lmargin, int pos) throws IOException { if (broken) { o.write("\r\n"); for (int i = 0; i < lmargin + indent; i++) o.write(" "); return lmargin + indent; } else { o.write(alt); return pos + alt.length(); } } String selfToString() { return "^"; } } class Newline extends AllowBreak { Newline(int n_) { super(n_, ""); } int format1(int lmargin, int pos, int rmargin, int fin, boolean can_break, boolean nofail) throws Overrun { if (!can_break) throw new Overrun(1); broken = true; return lmargin + indent; } int sendOutput(Writer o, int lmargin, int pos) throws IOException { o.write("\r\n"); for (int i = 0; i < lmargin + indent; i++) o.write(" "); return lmargin + indent; } }
package dr.evomodel.MSSD; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Parameter; public class AnyTipObservationProcess extends AbstractObservationProcess { protected double[] u0; protected double[] p; public AnyTipObservationProcess(String modelName, TreeModel treeModel, PatternList patterns, SiteModel siteModel, BranchRateModel branchRateModel, Parameter mu, Parameter lam) { super(modelName, treeModel, patterns, siteModel, branchRateModel, mu, lam); } public double calculateLogTreeWeight() { int L = treeModel.getNodeCount(); if (u0 == null || p == null) { u0 = new double[L]; // probability that the trait at node i survives to no leaf p = new double[L]; // probability of survival on the branch ancestral to i } int i, j, childNumber; NodeRef node; double logWeight = 0.0; for (i = 0; i < L; ++i) { p[i] = 1.0 - getNodeSurvivalProbability(i); } for (i = 0; i < treeModel.getExternalNodeCount(); ++i) { u0[i] = 0.0; logWeight += 1.0 - p[i]; } // TODO There is a bug here; the code below assumes nodes are numbered in post-order for (i = treeModel.getExternalNodeCount(); i < L; ++i) { u0[i] = 1.0; node = treeModel.getNode(i); for (j = 0; j < treeModel.getChildCount(node); ++j) { //childNode = treeModel.getChild(node,j); childNumber = treeModel.getChild(node, j).getNumber(); u0[i] *= 1.0 - p[childNumber] * (1.0 - u0[childNumber]); } logWeight += (1.0 - u0[i]) * (1.0 - p[i]); } return -logWeight * lam.getParameterValue(0) / (getAverageRate() * mu.getParameterValue(0)); } private void setTipNodePatternInclusion() { // These values never change for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); final int nChildren = treeModel.getChildCount(node); if (nChildren == 0) { for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { extantInTipsBelow[i][patternIndex] = 1; int taxonIndex = patterns.getTaxonIndex(treeModel.getNodeTaxon(node)); int[] states = dataType.getStates(patterns.getPatternState(taxonIndex, patternIndex)); for (int state : states) { if (state == deathState) { extantInTipsBelow[i][patternIndex] = 0; } } extantInTips[patternIndex] += extantInTipsBelow[i][patternIndex]; } } } } void setNodePatternInclusion() { int patternIndex, i, j; if (nodePatternInclusion == null) { nodePatternInclusion = new boolean[nodeCount][patternCount]; } if (this.extantInTips == null) { extantInTips = new int[patternCount]; extantInTipsBelow = new int[nodeCount][patternCount]; setTipNodePatternInclusion(); } for (patternIndex = 0; patternIndex < patternCount; ++patternIndex) { for (i = 0; i < treeModel.getNodeCount(); ++i) { NodeRef node = treeModel.getNode(i); int nChildren = treeModel.getChildCount(node); // TODO There is a bug here; the code below assumes nodes are numbered in post-order if (nChildren > 0) { extantInTipsBelow[i][patternIndex] = 0; for (j = 0; j < nChildren; ++j) { int childIndex = treeModel.getChild(node, j).getNumber(); extantInTipsBelow[i][patternIndex] += extantInTipsBelow[childIndex][patternIndex]; } } } for (i = 0; i < treeModel.getNodeCount(); ++i) { nodePatternInclusion[i][patternIndex] = (extantInTipsBelow[i][patternIndex] >= this.extantInTips[patternIndex]); } } nodePatternInclusionKnown = true; } private int[] extantInTips; private int[][] extantInTipsBelow; }
package dr.evomodel.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evolution.datatype.DataType; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.xml.*; import java.util.logging.Logger; /** * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. * * @author Andrew Rambaut * @author Alexei Drummond * * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $ */ public class TreeLikelihood extends AbstractTreeLikelihood { public static final String TREE_LIKELIHOOD = "treeLikelihood"; public static final String USE_AMBIGUITIES = "useAmbiguities"; public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa"; public static final String STORE_PARTIALS = "storePartials"; public static final String SCALING_FACTOR = "scalingFactor"; public static final String SCALING_THRESHOLD = "scalingThreshold"; public static final String FORCE_JAVA_CORE = "forceJavaCore"; /** * Constructor. */ public TreeLikelihood( PatternList patternList, TreeModel treeModel, SiteModel siteModel, BranchRateModel branchRateModel, TipPartialsModel tipPartialsModel, boolean useAmbiguities, boolean allowMissingTaxa, boolean storePartials, boolean forceJavaCore) { super(TREE_LIKELIHOOD, patternList, treeModel); this.storePartials = storePartials; try { this.siteModel = siteModel; addModel(siteModel); this.frequencyModel = siteModel.getFrequencyModel(); addModel(frequencyModel); this.tipPartialsModel = tipPartialsModel; integrateAcrossCategories = siteModel.integrateAcrossCategories(); this.categoryCount = siteModel.getCategoryCount(); final Logger logger = Logger.getLogger("dr.evomodel"); String coreName = "Java general"; if (integrateAcrossCategories) { final DataType dataType = patternList.getDataType(); if (dataType instanceof dr.evolution.datatype.Nucleotides) { if (!forceJavaCore && NativeNucleotideLikelihoodCore.isAvailable()) { coreName = "native nucleotide"; likelihoodCore = new NativeNucleotideLikelihoodCore(); } else { coreName = "Java nucleotide"; likelihoodCore = new NucleotideLikelihoodCore(); } } else if (dataType instanceof dr.evolution.datatype.AminoAcids) { if (!forceJavaCore && NativeAminoAcidLikelihoodCore.isAvailable()) { coreName = "native amino acid"; likelihoodCore = new NativeAminoAcidLikelihoodCore(); } else { coreName = "Java amino acid"; likelihoodCore = new AminoAcidLikelihoodCore(); } } else if (dataType instanceof dr.evolution.datatype.Codons) { // The codon core was out of date and did nothing more than the general core... likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); useAmbiguities = true; } else { likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); } } else { likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); } logger.info("TreeLikelihood using " + coreName + " likelihood core"); logger.info( " " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); // logger.info(" Partial likelihood scaling " + (scalingThreshold > 0 ? // "on: node count threshold = " + scalingThreshold + ", factor = " + scalingFactor : "off.")); if (branchRateModel != null) { this.branchRateModel = branchRateModel; logger.info("Branch rate model used: " + branchRateModel.getModelName()); } else { this.branchRateModel = new DefaultBranchRateModel(); } addModel(this.branchRateModel); probabilities = new double[stateCount * stateCount]; likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories); int extNodeCount = treeModel.getExternalNodeCount(); int intNodeCount = treeModel.getInternalNodeCount(); if (tipPartialsModel != null) { for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } tipPartialsModel.setStates(patternList, index, i); } addModel(tipPartialsModel); updateTipPartials(); useAmbiguities = true; } else { for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { if (!allowMissingTaxa) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } if (useAmbiguities) { setMissingPartials(likelihoodCore, i); } else { setMissingStates(likelihoodCore, i); } } else { if (useAmbiguities) { setPartials(likelihoodCore, patternList, categoryCount, index, i); } else { setStates(likelihoodCore, patternList, index, i); } } } } for (int i = 0; i < intNodeCount; i++) { likelihoodCore.createNodePartials(extNodeCount + i); } } catch (TaxonList.MissingTaxonException mte) { throw new RuntimeException(mte.toString()); } } // ModelListener IMPLEMENTATION /** * Handles model changed events from the submodels. */ protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == treeModel) { if (object instanceof TreeModel.TreeChangedEvent) { if (((TreeModel.TreeChangedEvent)object).isNodeChanged()) { // If a node event occurs the node and its two child nodes // are flagged for updating (this will result in everything // above being updated as well. Node events occur when a node // is added to a branch, removed from a branch or its height or // rate changes. updateNodeAndChildren(((TreeModel.TreeChangedEvent)object).getNode()); } else if (((TreeModel.TreeChangedEvent)object).isTreeChanged()) { // Full tree events result in a complete updating of the tree likelihood // Currently this event type is not used. System.err.println("Full tree update event - these events currently aren't used\n" + "so either this is in error or a new feature is using them so remove this message."); updateAllNodes(); } else { // Other event types are ignored (probably trait changes). //System.err.println("Another tree event has occured (possibly a trait change)."); } } } else if (model == branchRateModel) { if (index == -1) { updateAllNodes(); } else { updateNode(treeModel.getNode(index)); } } else if (model == frequencyModel) { updateAllNodes(); } else if (model == tipPartialsModel) { updateTipPartials(); } else if (model instanceof SiteModel) { updateAllNodes(); } else { throw new RuntimeException("Unknown componentChangedEvent"); } super.handleModelChangedEvent(model, object, index); } private void updateTipPartials() { int extNodeCount = treeModel.getExternalNodeCount(); for (int index = 0; index < extNodeCount; index++) { double[] partials = tipPartialsModel.getTipPartials(index); likelihoodCore.setNodePartials(index, partials); } updateAllNodes(); } // Model IMPLEMENTATION /** * Stores the additional state other than model components */ protected void storeState() { if (storePartials) { likelihoodCore.storeState(); } super.storeState(); } /** * Restore the additional stored state */ protected void restoreState() { if (storePartials) { likelihoodCore.restoreState(); } else { updateAllNodes(); } super.restoreState(); } // Likelihood IMPLEMENTATION /** * Calculate the log likelihood of the current state. * @return the log likelihood. */ protected double calculateLogLikelihood() { if (patternLogLikelihoods == null) { patternLogLikelihoods = new double[patternCount]; } if (!integrateAcrossCategories) { if (siteCategories == null) { siteCategories = new int[patternCount]; } for (int i = 0; i < patternCount; i++) { siteCategories[i] = siteModel.getCategoryOfSite(i); } } final NodeRef root = treeModel.getRoot(); traverse(treeModel, root); double logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } if (logL == Double.NEGATIVE_INFINITY) { Logger.getLogger("dr.evomodel").info("TreeLikelihood, " + this.getId() + ", turning on partial likelihood scaling to avoid precision loss"); // We probably had an underflow... turn on scaling likelihoodCore.setUseScaling(true); // and try again... updateAllNodes(); updateAllPatterns(); traverse(treeModel, root); logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } } /** * Check whether the scaling is still required. If the sum of all the logScalingFactors * is zero then we simply turn off the useScaling flag. This will speed up the likelihood * calculations when scaling is not required. */ public void checkScaling() { // if (useScaling) { // if (scalingCheckCount % 1000 == 0) { // double totalScalingFactor = 0.0; // for (int i = 0; i < nodeCount; i++) { // for (int j = 0; j < patternCount; j++) { // totalScalingFactor += scalingFactors[currentPartialsIndices[i]][i][j]; // useScaling = totalScalingFactor < 0.0; // Logger.getLogger("dr.evomodel").info("LikelihoodCore total log scaling factor: " + totalScalingFactor); // if (!useScaling) { // Logger.getLogger("dr.evomodel").info("LikelihoodCore scaling turned off."); // scalingCheckCount++; } /** * Traverse the tree calculating partial likelihoods. * @return whether the partials for this node were recalculated. */ private boolean traverse(Tree tree, NodeRef node) { boolean update = false; int nodeNum = node.getNumber(); NodeRef parent = tree.getParent(node); // First update the transition probability matrix(ices) for this branch if (parent != null && updateNode[nodeNum]) { final double branchRate = branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * ( tree.getNodeHeight(parent) - tree.getNodeHeight(node) ); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } likelihoodCore.setNodeMatrixForUpdate(nodeNum); for (int i = 0; i < categoryCount; i++) { siteModel.getTransitionProbabilitiesForCategory(i, branchTime, probabilities); likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); } update = true; } // If the node is internal, update the partial likelihoods. if (!tree.isExternal(node)) { // Traverse down the two child nodes NodeRef child1 = tree.getChild(node, 0); final boolean update1 = traverse(tree, child1); NodeRef child2 = tree.getChild(node, 1); final boolean update2 = traverse(tree, child2); // If either child node was updated then update this node too if (update1 || update2) { final int childNum1 = child1.getNumber(); final int childNum2 = child2.getNumber(); likelihoodCore.setNodePartialsForUpdate(nodeNum); if (integrateAcrossCategories) { likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); } else { likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories); } if (parent == null) { // No parent this is the root of the tree - // calculate the pattern likelihoods double[] frequencies = frequencyModel.getFrequencies(); double[] partials = getRootPartials(); likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods); } update = true; } } return update; } public final double[] getRootPartials() { if (rootPartials == null) { rootPartials = new double[patternCount * stateCount]; } int nodeNum = treeModel.getRoot().getNumber(); if (integrateAcrossCategories) { // moved this call to here, because non-integrating siteModels don't need to support it - AD double[] proportions = siteModel.getCategoryProportions(); likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); } else { likelihoodCore.getPartials(nodeNum, rootPartials); } return rootPartials; } /** the root partial likelihoods (a temporary array that is used * to fetch the partials - it should not be examined directly - * use getRootPartials() instead). */ private double[] rootPartials = null; /** * The XML parser */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { boolean useAmbiguities = false; boolean allowMissingTaxa = false; boolean storePartials = true; boolean forceJavaCore = false; if (xo.hasAttribute(USE_AMBIGUITIES)) { useAmbiguities = xo.getBooleanAttribute(USE_AMBIGUITIES); } if (xo.hasAttribute(ALLOW_MISSING_TAXA)) { allowMissingTaxa = xo.getBooleanAttribute(ALLOW_MISSING_TAXA); } if (xo.hasAttribute(STORE_PARTIALS)) { storePartials = xo.getBooleanAttribute(STORE_PARTIALS); } if (xo.hasAttribute(FORCE_JAVA_CORE)) { forceJavaCore = xo.getBooleanAttribute(FORCE_JAVA_CORE); } PatternList patternList = (PatternList)xo.getChild(PatternList.class); TreeModel treeModel = (TreeModel)xo.getChild(TreeModel.class); SiteModel siteModel = (SiteModel)xo.getChild(SiteModel.class); BranchRateModel branchRateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); TipPartialsModel tipPartialsModel = (TipPartialsModel)xo.getChild(TipPartialsModel.class); return new TreeLikelihood( patternList, treeModel, siteModel, branchRateModel, tipPartialsModel, useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore); } /** the frequency model for these sites */ /** the site model for these sites */ /** the branch rate model */ /** the tip partials model */ /** the categories for each site */ /** the pattern likelihoods */ /** the number of rate categories */ /** an array used to store transition probabilities */ /** the LikelihoodCore */
package dr.inference.operators; import dr.inference.model.Likelihood; import dr.inference.prior.Prior; public abstract class SimpleMCMCOperator implements MCMCOperator { public double getTargetAcceptanceProbability() { return targetAcceptanceProb; } public void setTargetAcceptanceProbability(double tap) { targetAcceptanceProb = tap; } public double getMinimumAcceptanceLevel() { return 0.05; } public double getMaximumAcceptanceLevel() { return 0.50; } public double getMinimumGoodAcceptanceLevel() { return 0.10; } public double getMaximumGoodAcceptanceLevel() { return 0.40; } public abstract String getOperatorName(); /** * @return the weight of this operator. */ public final double getWeight() { return weight; } /** * Sets the weight of this operator. */ public final void setWeight(double w) { if (w > 0) { weight = w; } else throw new IllegalArgumentException( "Weight must be a positive real, but tried to set weight to " + w); } public void accept(double deviation) { lastDeviation = deviation; if (!operateAllowed) { operateAllowed = true; accepted += 1; sumDeviation += deviation; spanDeviation[0] = Math.min(spanDeviation[0], deviation); spanDeviation[1] = Math.max(spanDeviation[1], deviation); spanCount += 1; } else { throw new RuntimeException( "Accept/reject methods called twice without operate called in between!"); } } public void reject() { if (!operateAllowed) { operateAllowed = true; rejected += 1; } else { throw new RuntimeException( "Accept/reject methods called twice without operate called in between!"); } } public void reset() { operateAllowed = true; accepted = 0; rejected = 0; lastDeviation = 0.0; sumDeviation = 0.0; } public final int getAccepted() { return accepted; } public final void setAccepted(int accepted) { this.accepted = accepted; } public final int getRejected() { return rejected; } public final void setRejected(int rejected) { this.rejected = rejected; } public final double getMeanDeviation() { return sumDeviation / accepted; } public final double getDeviation() { return lastDeviation; } public final double getSumDeviation() { return sumDeviation; } public final void setSumDeviation(double sumDeviation) { this.sumDeviation = sumDeviation; } public double getSpan(boolean reset) { double span = 0; if (spanDeviation[1] > spanDeviation[0] && spanCount > 2000) { span = spanDeviation[1] - spanDeviation[0]; if (reset) { spanDeviation[0] = Double.MAX_VALUE; spanDeviation[1] = -Double.MAX_VALUE; spanCount = 0; } } return span; } public final double operate() throws OperatorFailedException { if (operateAllowed) { operateAllowed = false; return doOperation(); } else { throw new RuntimeException( "Operate called twice without accept/reject in between!"); } } public final double operate(Prior prior, Likelihood likelihood) throws OperatorFailedException { if (operateAllowed) { operateAllowed = false; return doOperation(prior, likelihood); } else throw new RuntimeException( "Operate called twice without accept/reject in between!"); } public final double getAcceptanceProbability() { return (double) accepted / (double) (accepted + rejected); } /** * Called by operate(), does the actual operation. * * @return the hastings ratio * @throws OperatorFailedException * if operator fails and should be rejected */ public double doOperation(Prior prior, Likelihood likelihood) throws OperatorFailedException { return 0.0; } /** * Called by operate(), does the actual operation. * * @return the hastings ratio * @throws OperatorFailedException * if operator fails and should be rejected */ public abstract double doOperation() throws OperatorFailedException; private double weight = 1.0; private int accepted = 0; private int rejected = 0; private double sumDeviation = 0.0; private double lastDeviation = 0.0; private boolean operateAllowed = true; private double targetAcceptanceProb = 0.234; private final double[] spanDeviation = { Double.MAX_VALUE, -Double.MAX_VALUE }; private int spanCount = 0; }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JTabbedPane; import nl.mpi.kinnate.kindata.VisiblePanelSetting; public class HidePane extends JPanel { public enum HidePanePosition { left, right, top, bottom } private JTabbedPane tabbedPane = new JTabbedPane(); private boolean hiddenState = true; private int lastSelectedTab = -1; private int defaultShownWidth = 300; private int shownWidth; private int hiddenWidth = 30; private HidePanePosition borderPosition; private boolean horizontalDivider; private int dragStartPosition = 0; private boolean lastWasDrag = false; private HashSet<VisiblePanelSetting> registeredPanelSettings; public HidePane(HidePanePosition borderPositionLocal, int startWidth) { this.setLayout(new BorderLayout()); JPanel separatorBar = new JPanel(); separatorBar.setPreferredSize(new Dimension(5, 5)); separatorBar.setMaximumSize(new Dimension(5, 5)); separatorBar.setMinimumSize(new Dimension(5, 5)); registeredPanelSettings = new HashSet<VisiblePanelSetting>(); shownWidth = startWidth; borderPosition = borderPositionLocal; horizontalDivider = (!borderPosition.equals(HidePanePosition.left) && !borderPosition.equals(HidePanePosition.right)); switch (borderPosition) { case left: // separatorBar = new JSeparator(JSeparator.VERTICAL); separatorBar.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); this.add(separatorBar, BorderLayout.LINE_END); tabbedPane.setTabPlacement(javax.swing.JTabbedPane.TOP); // changed from RIGHT because only mac supports rotated tabs and rotated text is debatable usability wise anyway break; case right: // separatorBar = new JSeparator(JSeparator.VERTICAL); separatorBar.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); this.add(separatorBar, BorderLayout.LINE_START); tabbedPane.setTabPlacement(javax.swing.JTabbedPane.TOP); // changed from LEFT because only mac supports rotated tabs and rotated text is debatable usability wise anyway break; case top: // separatorBar = new JSeparator(JSeparator.HORIZONTAL); separatorBar.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); this.add(separatorBar, BorderLayout.PAGE_END); tabbedPane.setTabPlacement(javax.swing.JTabbedPane.BOTTOM); break; case bottom: default: // separatorBar = new JSeparator(JSeparator.HORIZONTAL); separatorBar.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); this.add(separatorBar, BorderLayout.PAGE_START); tabbedPane.setTabPlacement(javax.swing.JTabbedPane.TOP); break; } separatorBar.setBackground(Color.LIGHT_GRAY); this.add(tabbedPane, BorderLayout.CENTER); // this.add(contentComponent, labelStringLocal); separatorBar.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { // todo: check the max space and prevent oversizing lastWasDrag = true; if (hiddenState) { hiddenState = false; shownWidth = hiddenWidth; } switch (borderPosition) { case left: shownWidth = shownWidth - dragStartPosition + e.getXOnScreen(); dragStartPosition = e.getXOnScreen(); break; case right: shownWidth = shownWidth + dragStartPosition - e.getXOnScreen(); dragStartPosition = e.getXOnScreen(); break; case top: shownWidth = shownWidth - dragStartPosition + e.getYOnScreen(); dragStartPosition = e.getYOnScreen(); break; case bottom: shownWidth = shownWidth + dragStartPosition - e.getYOnScreen(); dragStartPosition = e.getYOnScreen(); break; } if (shownWidth < hiddenWidth) { shownWidth = hiddenWidth; hiddenState = true; } if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, shownWidth)); } else { HidePane.this.setPreferredSize(new Dimension(shownWidth, HidePane.this.getPreferredSize().height)); } // if (horizontalDivider) { // if (borderPosition.equals(BorderLayout.PAGE_END)) { // shownWidth = shownWidth - lastXpos + e.getY(); // } else { // shownWidth = shownWidth - lastXpos - e.getY(); //// if (shownWidth < removeButton.getPreferredSize().height * 2) { //// shownWidth = removeButton.getPreferredSize().height * 2; //// } else if (shownWidth > HidePane.this.getParent().getHeight()) { //// shownWidth = HidePane.this.getParent().getHeight() - removeButton.getPreferredSize().height; // HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, shownWidth)); // } else { // if (borderPosition.equals(BorderLayout.LINE_END)) { // shownWidth = shownWidth - lastXpos + e.getX(); // } else { // shownWidth = shownWidth - lastXpos - e.getX(); //// if (shownWidth < removeButton.getPreferredSize().width * 2) { //// shownWidth = removeButton.getPreferredSize().width * 2; //// } else if (shownWidth > HidePane.this.getParent().getWidth()) { //// shownWidth = HidePane.this.getParent().getWidth() - removeButton.getPreferredSize().width; // HidePane.this.setPreferredSize(new Dimension(shownWidth, HidePane.this.getPreferredSize().height)); HidePane.this.revalidate(); HidePane.this.repaint(); } }); separatorBar.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if (!hiddenState && lastSelectedTab != tabbedPane.getSelectedIndex()) { // skip hide action when the selected tab changes lastSelectedTab = tabbedPane.getSelectedIndex(); return; } lastSelectedTab = tabbedPane.getSelectedIndex(); if (!lastWasDrag) { toggleHiddenState(); } else if (shownWidth < hiddenWidth * 2) { shownWidth = hiddenWidth; hiddenState = true; if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, shownWidth)); } else { HidePane.this.setPreferredSize(new Dimension(shownWidth, HidePane.this.getPreferredSize().height)); } HidePane.this.revalidate(); HidePane.this.repaint(); } for (VisiblePanelSetting panelSetting : registeredPanelSettings) { panelSetting.setPanelWidth(shownWidth); } } @Override public void mousePressed(MouseEvent e) { lastWasDrag = false; if (horizontalDivider) { dragStartPosition = e.getYOnScreen(); } else { dragStartPosition = e.getXOnScreen(); } super.mousePressed(e); } }); if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, hiddenWidth)); } else { HidePane.this.setPreferredSize(new Dimension(hiddenWidth, HidePane.this.getPreferredSize().height)); } } public void addTab(String tabString, Component tabComponent) { int insertIndex = 0; for (int tabCounter = 0; tabCounter < tabbedPane.getTabCount(); tabCounter++) { if (tabString.compareToIgnoreCase(tabbedPane.getTitleAt(tabCounter)) < 0) { break; } insertIndex++; } tabbedPane.insertTab(tabString, null, tabComponent, tabString, insertIndex); } public void addTab(VisiblePanelSetting panelSetting, String tabString, Component tabComponent) { addTab(tabString, tabComponent); shownWidth = panelSetting.getPanelWidth(); hiddenState = false; if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, shownWidth)); } else { HidePane.this.setPreferredSize(new Dimension(shownWidth, HidePane.this.getPreferredSize().height)); } this.setVisible(true); HidePane.this.revalidate(); HidePane.this.repaint(); registeredPanelSettings.add(panelSetting); } @Override public Component[] getComponents() { return tabbedPane.getComponents(); } public Component getSelectedComponent() { return tabbedPane.getSelectedComponent(); } public void setSelectedComponent(Component component) { tabbedPane.setSelectedComponent(component); } public void removeTab(Component comp) { tabbedPane.remove(comp); // this.setVisible(tabbedPane.getComponentCount() > 0); } public void remove(VisiblePanelSetting panelSetting) { for (Component currentPanel : panelSetting.getTargetPanels()) { tabbedPane.remove(currentPanel); } this.setVisible(tabbedPane.getComponentCount() > 0); registeredPanelSettings.remove(panelSetting); } public void setHiddeState() { boolean showEditor = tabbedPane.getComponentCount() > 0; if (hiddenState == showEditor) { toggleHiddenState(); } this.setVisible(showEditor); } private void toggleHiddenState() { if (!hiddenState) { if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, hiddenWidth)); } else { HidePane.this.setPreferredSize(new Dimension(hiddenWidth, HidePane.this.getPreferredSize().height)); } } else { if (shownWidth < hiddenWidth * 2) { shownWidth = defaultShownWidth; } if (horizontalDivider) { HidePane.this.setPreferredSize(new Dimension(HidePane.this.getPreferredSize().width, shownWidth)); } else { HidePane.this.setPreferredSize(new Dimension(shownWidth, HidePane.this.getPreferredSize().height)); } } hiddenState = !hiddenState; HidePane.this.revalidate(); HidePane.this.repaint(); } }
package edu.mit.streamjit.impl.interp; import static com.google.common.base.Preconditions.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import edu.mit.streamjit.api.IllegalStreamGraphException; import edu.mit.streamjit.api.Rate; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.BlobFactory; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.MessageConstraint; import edu.mit.streamjit.impl.common.Workers; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * An Interpreter interprets a section of a stream graph. An Interpreter's * interpret() method will run a pull schedule on the "bottom-most" filters in * the section (filters that are not predecessor of other filters in the blob), * firing them as many times as possible. * * An Interpreter has input and output channels, identified by opaque Token * objects. An input channel is any channel from a worker not in the * Interpreter's stream graph section to one inside it, and an output channel, * vice versa. The Interpreter expects these channels to already be installed * on the workers. * * To communicate between two Interpreter instances on the same machine, use * a synchronized channel implementation to connect outputs of one interpreter * to the inputs of the other. * * To communicate between interpreter instances on different machines, have a * thread on one machine poll() on output channels (if you can afford one thread * per output, use a blocking channel implementation) and send that data to the * other machine, then use threads on the other machine to read the data and * offer() it to input channels. It's tempting to put the send/receive in the * channel implementations themselves, but this may block the interpreter on * I/O, and makes implementing peek() on the receiving side tricky. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 3/22/2013 */ public class Interpreter implements Blob { private final ImmutableSet<Worker<?, ?>> workers, sinks; private final ImmutableMap<Token, Channel<?>> inputChannels, outputChannels; /** * Maps workers to all constraints of which they are recipients. */ private final Map<Worker<?, ?>, List<MessageConstraint>> constraintsForRecipient = new IdentityHashMap<>(); public Interpreter(Iterable<Worker<?, ?>> workersIter, Iterable<MessageConstraint> constraintsIter) { this.workers = ImmutableSet.copyOf(workersIter); //Sinks are any filter that isn't a predecessor of another filter. Set<Worker<?, ?>> sinksAccum = new HashSet<>(); Iterables.addAll(sinksAccum, workers); for (Worker<?, ?> worker : workers) sinksAccum.removeAll(Workers.getAllPredecessors(worker)); this.sinks = ImmutableSet.copyOf(sinksAccum); for (MessageConstraint mc : constraintsIter) if (this.workers.contains(mc.getSender()) != this.workers.contains(mc.getRecipient())) throw new IllegalArgumentException("Constraint crosses interpreter boundary: "+mc); for (MessageConstraint constraint : constraintsIter) { Worker<?, ?> recipient = constraint.getRecipient(); List<MessageConstraint> constraintList = constraintsForRecipient.get(recipient); if (constraintList == null) { constraintList = new ArrayList<>(); constraintsForRecipient.put(recipient, constraintList); } constraintList.add(constraint); } ImmutableMap.Builder<Token, Channel<?>> inputChannelsBuilder = ImmutableMap.builder(); ImmutableMap.Builder<Token, Channel<?>> outputChannelsBuilder = ImmutableMap.builder(); for (Worker<?, ?> worker : workers) { List<Channel<?>> inChannels = ImmutableList.<Channel<?>>builder().addAll(Workers.getInputChannels(worker)).build(); ImmutableList<Worker<?, ?>> preds = ImmutableList.<Worker<?, ?>>builder().addAll(Workers.getPredecessors(worker)).build(); for (int i = 0; i < inChannels.size(); ++i) { //Get the predecessor, or if the input channel is the actual //input to the stream graph, null. Worker<?, ?> pred = Iterables.get(preds, i, null); //Null is "not in stream graph section" (so this works). if (!workers.contains(pred)) { Token token = pred == null ? Token.createOverallInputToken(worker) : new Token(pred, worker); Channel<?> channel = inChannels.get(i); inputChannelsBuilder.put(token, channel); } } List<Channel<?>> outChannels = ImmutableList.<Channel<?>>builder().addAll(Workers.getOutputChannels(worker)).build(); ImmutableList<Worker<?, ?>> succs = ImmutableList.<Worker<?, ?>>builder().addAll(Workers.getSuccessors(worker)).build(); for (int i = 0; i < outChannels.size(); ++i) { //Get the successor, or if the output channel is the actual //output of the stream graph, null. Worker<?, ?> succ = Iterables.get(succs, i, null); //Null is "not in stream graph section" (so this works). if (!workers.contains(succ)) { Token token = succ == null ? Token.createOverallOutputToken(worker) : new Token(worker, succ); Channel<?> channel = outChannels.get(i); outputChannelsBuilder.put(token, channel); } } } this.inputChannels = inputChannelsBuilder.build(); this.outputChannels = outputChannelsBuilder.build(); } @Override public ImmutableSet<Worker<?, ?>> getWorkers() { return workers; } @Override public Map<Token, Channel<?>> getInputChannels() { return inputChannels; } @Override public Map<Token, Channel<?>> getOutputChannels() { return outputChannels; } @Override public int getCoreCount() { return 1; } @Override public Runnable getCoreCode(int core) { checkElementIndex(core, getCoreCount()); return new Runnable() { @Override public void run() { interpret(); } }; } public static final class InterpreterBlobFactory implements BlobFactory { @Override public Blob makeBlob(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores) { //TODO: get the constraints! return new Interpreter(workers, Collections.<MessageConstraint>emptyList()); } @Override public boolean equals(Object o) { //All InterpreterBlobFactory instances are equal. return o != null && getClass() == o.getClass(); } @Override public int hashCode() { return 9001; } } /** * Interprets the stream graph section by running a pull schedule on the * "bottom-most" workers in the section (firing predecessors as required if * possible) until no more progress can be made. Returns true if any * "bottom-most" workers were fired. Note that returning false does not * mean no workers were fired -- some predecessors might have been fired, * but others prevented the "bottom-most" workers from firing. * @return true iff progress was made */ public boolean interpret() { //Fire each sink once if possible, then repeat until we can't fire any //sinks. boolean fired, everFired = false; do { fired = false; for (Worker<?, ?> sink : sinks) everFired |= fired |= pull(sink); } while (fired); return everFired; } /** * Fires upstream filters just enough to allow worker to fire, or returns * false if this is impossible. * * This is an implementation of Figure 3-12 from Bill's thesis. * * @param worker the worker to fire * @return true if the worker fired, false if it didn't */ private boolean pull(Worker<?, ?> worker) { //This stack holds all the unsatisfied workers we've encountered //while trying to fire the argument. Deque<Worker<?, ?>> stack = new ArrayDeque<>(); stack.push(worker); recurse: while (!stack.isEmpty()) { Worker<?, ?> current = stack.element(); assert workers.contains(current) : "Executing outside stream graph section"; //If we're already trying to fire current, current depends on //itself, so throw. TODO: explain which constraints are bad? //We have to pop then push so contains can't just find the top //of the stack every time. (no indexOf(), annoying) stack.pop(); if (stack.contains(current)) throw new IllegalStreamGraphException("Unsatisfiable message constraints", current); stack.push(current); //Execute predecessors based on data dependencies. int channel = indexOfUnsatisfiedChannel(current); if (channel != -1) { if (!workers.contains(Iterables.get(Workers.getPredecessors(current), channel, null))) //We need data from a worker not in our stream graph section, //so we can't do anything. return false; //Otherwise, recursively fire the worker blocking us. stack.push(Workers.getPredecessors(current).get(channel)); continue recurse; } List<MessageConstraint> constraints = constraintsForRecipient.get(current); if (constraints != null) //Execute predecessors based on message dependencies; that is, //execute any filter that might send a message to the current //worker for delivery just prior to its next firing, to ensure //that delivery cannot be missed. for (MessageConstraint constraint : constraintsForRecipient.get(current)) { Worker<?, ?> sender = constraint.getSender(); long deliveryTime = constraint.getDeliveryTime(Workers.getExecutions(sender)); //If deliveryTime == current.getExecutions() + 1, it's for //our next execution. (If it's <= current.getExecutions(), //we already missed it!) if (deliveryTime <= (Workers.getExecutions(sender) + 1)) { //We checked in our constructor that message constraints //do not cross the interpreter boundary. Assert that. assert workers.contains(sender); stack.push(sender); continue recurse; } } Workers.doWork(current); afterFire(current); stack.pop(); //return from the recursion } //Stack's empty: we fired the argument. return true; } /** * Searches the given worker's input channels for one that requires more * elements before the worker can fire, returning the index of the found * channel or -1 if the worker can fire. */ private <I, O> int indexOfUnsatisfiedChannel(Worker<I, O> worker) { List<Channel<? extends I>> channels = Workers.getInputChannels(worker); List<Rate> peekRates = worker.getPeekRates(); List<Rate> popRates = worker.getPopRates(); for (int i = 0; i < channels.size(); ++i) { Rate peek = peekRates.get(i), pop = popRates.get(i); if (peek.max() == Rate.DYNAMIC || pop.max() == Rate.DYNAMIC) throw new UnsupportedOperationException("Unbounded input rates not yet supported"); int required = Math.max(peek.max(), pop.max()); if (channels.get(i).size() < required) return i; } return -1; } /** * Called after the given worker is fired. Provided for the debug * interpreter to check rate declarations. * @param worker the worker that just fired */ protected void afterFire(Worker<?, ?> worker) {} }
package edu.washington.escience.myria; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Objects; import org.joda.time.DateTime; import com.google.common.base.Preconditions; import edu.washington.escience.myria.column.Column; import edu.washington.escience.myria.column.builder.BooleanColumnBuilder; import edu.washington.escience.myria.column.builder.ColumnBuilder; import edu.washington.escience.myria.column.builder.ColumnFactory; import edu.washington.escience.myria.column.builder.DateTimeColumnBuilder; import edu.washington.escience.myria.column.builder.DoubleColumnBuilder; import edu.washington.escience.myria.column.builder.FloatColumnBuilder; import edu.washington.escience.myria.column.builder.IntColumnBuilder; import edu.washington.escience.myria.column.builder.LongColumnBuilder; import edu.washington.escience.myria.column.builder.StringColumnBuilder; import edu.washington.escience.myria.column.mutable.BooleanMutableColumn; import edu.washington.escience.myria.column.mutable.DateTimeMutableColumn; import edu.washington.escience.myria.column.mutable.DoubleMutableColumn; import edu.washington.escience.myria.column.mutable.FloatMutableColumn; import edu.washington.escience.myria.column.mutable.IntArrayMutableColumn; import edu.washington.escience.myria.column.mutable.IntMutableColumn; import edu.washington.escience.myria.column.mutable.LongMutableColumn; import edu.washington.escience.myria.column.mutable.MutableColumn; import edu.washington.escience.myria.column.mutable.StringMutableColumn; /** A simplified TupleBatchBuffer which supports random access. Designed for hash tables to use. */ public class TupleBuffer implements Cloneable, Relation { /** Format of the emitted tuples. */ private final Schema schema; /** Convenience constant; must match schema.numColumns() and currentColumns.size(). */ private final int numColumns; /** List of completed TupleBatch objects. */ private final List<MutableColumn<?>[]> readyTuples; /** Internal state used to build up a TupleBatch. */ private ColumnBuilder<?>[] currentBuildingColumns; /** Internal state representing which columns are ready in the current tuple. */ private BitSet columnsReady; /** Internal state representing the number of columns that are ready in the current tuple. */ private int numColumnsReady; /** Internal state representing the number of tuples in the in-progress TupleBatch. */ private int currentInProgressTuples; /** * Constructs an empty TupleBuffer to hold tuples matching the specified Schema. * * @param schema specified the columns of the emitted TupleBatch objects. */ public TupleBuffer(final Schema schema) { this.schema = Objects.requireNonNull(schema); readyTuples = new ArrayList<MutableColumn<?>[]>(); currentBuildingColumns = ColumnFactory.allocateColumns(schema).toArray(new ColumnBuilder<?>[] {}); numColumns = schema.numColumns(); columnsReady = new BitSet(numColumns); numColumnsReady = 0; currentInProgressTuples = 0; } /** * clear this TBB. * */ public final void clear() { columnsReady.clear(); currentBuildingColumns = null; currentInProgressTuples = 0; numColumnsReady = 0; readyTuples.clear(); } /** * Makes a batch of any tuples in the buffer and appends it to the internal list. * */ private void finishBatch() { Preconditions.checkArgument(numColumnsReady == 0); Preconditions.checkArgument(currentInProgressTuples == TupleBatch.BATCH_SIZE); MutableColumn<?>[] buildingColumns = new MutableColumn<?>[numColumns]; int i = 0; for (ColumnBuilder<?> cb : currentBuildingColumns) { buildingColumns[i++] = cb.buildMutable(); } readyTuples.add(buildingColumns); currentBuildingColumns = ColumnFactory.allocateColumns(schema).toArray(new ColumnBuilder<?>[] {}); currentInProgressTuples = 0; } /** * @return the Schema of the tuples in this buffer. */ @Override public final Schema getSchema() { return schema; } /** * @return the number of complete tuples stored in this TupleBuffer. */ @Override public final int numTuples() { return readyTuples.size() * TupleBatch.BATCH_SIZE + currentInProgressTuples; } @Override @Deprecated public final Object getObject(final int colIndex, final int rowIndex) throws IndexOutOfBoundsException { int tupleBatchIndex = rowIndex / TupleBatch.BATCH_SIZE; int tupleIndex = rowIndex % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return readyTuples.get(tupleBatchIndex)[colIndex].getObject(tupleIndex); } return currentBuildingColumns[colIndex].get(tupleIndex); } @Override public final boolean getBoolean(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((BooleanMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getBoolean(tupleIndex); } return ((BooleanColumnBuilder) (currentBuildingColumns[column])).getBoolean(tupleIndex); } @Override public final double getDouble(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((DoubleMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getDouble(tupleIndex); } return ((DoubleColumnBuilder) (currentBuildingColumns[column])).getDouble(tupleIndex); } @Override public final float getFloat(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((FloatMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getFloat(tupleIndex); } return ((FloatColumnBuilder) (currentBuildingColumns[column])).getFloat(tupleIndex); } @Override public final long getLong(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((LongMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getLong(tupleIndex); } return ((LongColumnBuilder) (currentBuildingColumns[column])).getLong(tupleIndex); } @Override public final int getInt(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((IntMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getInt(tupleIndex); } return ((IntColumnBuilder) (currentBuildingColumns[column])).getInt(tupleIndex); } @Override public final String getString(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((StringMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getString(tupleIndex); } return ((StringColumnBuilder) (currentBuildingColumns[column])).get(tupleIndex); } @Override public final DateTime getDateTime(final int column, final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return ((DateTimeMutableColumn) (readyTuples.get(tupleBatchIndex)[column])).getDateTime(tupleIndex); } return ((DateTimeColumnBuilder) (currentBuildingColumns[column])).get(tupleIndex); } /** * @param row the row number * @return the columns of the TB that the row resides. * */ public MutableColumn<?>[] getColumns(final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return readyTuples.get(tupleBatchIndex); } return null; } /** * @param row the row number * @return the index of the row in the containing TB. * */ public final int getTupleIndexInContainingTB(final int row) { return row % TupleBatch.BATCH_SIZE; } /** * @param row the row number * @return the ColumnBuilder if the row resides in a in-building TB * */ public ColumnBuilder<?>[] getColumnBuilders(final int row) { int tupleBatchIndex = row / TupleBatch.BATCH_SIZE; int tupleIndex = row % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { return null; } return currentBuildingColumns; } /** * @return num columns. * */ @Override public final int numColumns() { return numColumns; } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ @Deprecated public final void put(final int column, final Object value) { checkPutIndex(column); currentBuildingColumns[column].appendObject(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putBoolean(final int column, final boolean value) { checkPutIndex(column); ((BooleanColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putDateTime(final int column, final DateTime value) { checkPutIndex(column); ((DateTimeColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putDouble(final int column, final double value) { checkPutIndex(column); ((DoubleColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putFloat(final int column, final float value) { checkPutIndex(column); ((FloatColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putInt(final int column, final int value) { checkPutIndex(column); ((IntColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putLong(final int column, final long value) { checkPutIndex(column); ((LongColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Append the specified value to the specified column. * * @param column index of the column. * @param value value to be appended. */ public final void putString(final int column, final String value) { checkPutIndex(column); ((StringColumnBuilder) currentBuildingColumns[column]).append(value); columnPut(column); } /** * Helper function: checks whether the specified column can be inserted into. * * @param column the column in which the value should be put. */ private void checkPutIndex(final int column) { Preconditions.checkElementIndex(column, numColumns); if (columnsReady.get(column)) { throw new RuntimeException("Need to fill up one row of TupleBatchBuffer before starting new one"); } } /** * Helper function to update the internal state after a value has been inserted into the specified column. * * @param column the column in which the value was put. */ private void columnPut(final int column) { columnsReady.set(column, true); numColumnsReady++; if (numColumnsReady == numColumns) { currentInProgressTuples++; numColumnsReady = 0; columnsReady.clear(); if (currentInProgressTuples == TupleBatch.BATCH_SIZE) { finishBatch(); } } } /** * Append the specified value to the specified destination column in this TupleBuffer from the source column. * * @param destColumn which column in this TB the value will be inserted. * @param sourceColumn the column from which data will be retrieved. * @param sourceRow the row in the source column from which data will be retrieved. */ public final void put(final int destColumn, final Column<?> sourceColumn, final int sourceRow) { checkPutIndex(destColumn); ColumnBuilder<?> dest = currentBuildingColumns[destColumn]; switch (dest.getType()) { case BOOLEAN_TYPE: ((BooleanColumnBuilder) dest).append(sourceColumn.getBoolean(sourceRow)); break; case DATETIME_TYPE: ((DateTimeColumnBuilder) dest).append(sourceColumn.getDateTime(sourceRow)); break; case DOUBLE_TYPE: ((DoubleColumnBuilder) dest).append(sourceColumn.getDouble(sourceRow)); break; case FLOAT_TYPE: ((FloatColumnBuilder) dest).append(sourceColumn.getFloat(sourceRow)); break; case INT_TYPE: ((IntColumnBuilder) dest).append(sourceColumn.getInt(sourceRow)); break; case LONG_TYPE: ((LongColumnBuilder) dest).append(sourceColumn.getLong(sourceRow)); break; case STRING_TYPE: ((StringColumnBuilder) dest).append(sourceColumn.getString(sourceRow)); break; } columnPut(destColumn); } /** * Swap the specified values from sourceRow to destRow in this TupleBuffer from the given column. * * @param column which column in this TB the value will be inserted. * @param destRow the row in the dest column from which data will be retrieved. * @param sourceRow the row in the source column from which data will be retrieved. */ public final void swap(final int column, final int destRow, final int sourceRow) { int tupleBatchIndex1 = destRow / TupleBatch.BATCH_SIZE; int tupleIndex1 = destRow % TupleBatch.BATCH_SIZE; if (tupleBatchIndex1 > readyTuples.size() || tupleBatchIndex1 == readyTuples.size() && tupleIndex1 >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } int tupleBatchIndex2 = sourceRow / TupleBatch.BATCH_SIZE; int tupleIndex2 = sourceRow % TupleBatch.BATCH_SIZE; if (tupleBatchIndex2 > readyTuples.size() || tupleBatchIndex2 == readyTuples.size() && tupleIndex2 >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } Type t = getSchema().getColumnType(column); switch (t) { case LONG_TYPE: { long v1, v2; LongMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (LongMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } LongMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (LongMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } LongColumnBuilder builder = (LongColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getLong(tupleIndex1); } else { v1 = builder.getLong(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getLong(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.getLong(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case INT_TYPE: { int v1, v2; IntMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (IntMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } IntMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (IntMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } IntColumnBuilder builder = (IntColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getInt(tupleIndex1); } else { v1 = builder.getInt(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getInt(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.getInt(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case DOUBLE_TYPE: { double v1, v2; DoubleMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (DoubleMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } DoubleMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (DoubleMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } DoubleColumnBuilder builder = (DoubleColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getDouble(tupleIndex1); } else { v1 = builder.getDouble(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getDouble(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.getDouble(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case FLOAT_TYPE: { float v1, v2; FloatMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (FloatMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } FloatMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (FloatMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } FloatColumnBuilder builder = (FloatColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getFloat(tupleIndex1); } else { v1 = builder.getFloat(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getFloat(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.getFloat(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case BOOLEAN_TYPE: { boolean v1, v2; BooleanMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (BooleanMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } BooleanMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (BooleanMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } BooleanColumnBuilder builder = (BooleanColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getBoolean(tupleIndex1); } else { v1 = builder.getBoolean(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getBoolean(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.getBoolean(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case STRING_TYPE: { String v1, v2; StringMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (StringMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } StringMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (StringMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } StringColumnBuilder builder = (StringColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getString(tupleIndex1); } else { v1 = builder.get(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getString(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.get(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } case DATETIME_TYPE: { DateTime v1, v2; DateTimeMutableColumn col1 = null; if (tupleBatchIndex1 < readyTuples.size()) { col1 = (DateTimeMutableColumn) (readyTuples.get(tupleBatchIndex1)[column]); } DateTimeMutableColumn col2 = null; if (tupleBatchIndex2 < readyTuples.size()) { col2 = (DateTimeMutableColumn) (readyTuples.get(tupleBatchIndex2)[column]); } DateTimeColumnBuilder builder = (DateTimeColumnBuilder) (currentBuildingColumns[column]); if (tupleBatchIndex1 < readyTuples.size()) { v1 = col1.getDateTime(tupleIndex1); } else { v1 = builder.get(tupleIndex1); } if (tupleBatchIndex2 < readyTuples.size()) { v2 = col2.getDateTime(tupleIndex2); col2.replace(tupleIndex2, v1); } else { v2 = builder.get(tupleIndex2); builder.replace(tupleIndex2, v1); } if (tupleBatchIndex1 < readyTuples.size()) { col1.replace(tupleIndex1, v2); } else { builder.replace(tupleIndex1, v2); } break; } } } /** * Replace the specified value to the specified destination column in this TupleBuffer from the source column. * * @param destColumn which column in this TB the value will be inserted. * @param destRow the row in the dest column from which data will be retrieved. * @param sourceColumn the column from which data will be retrieved. * @param sourceRow the row in the source column from which data will be retrieved. */ public final void replace(final int destColumn, final int destRow, final Column<?> sourceColumn, final int sourceRow) { checkPutIndex(destColumn); int tupleBatchIndex = destRow / TupleBatch.BATCH_SIZE; int tupleIndex = destRow % TupleBatch.BATCH_SIZE; if (tupleBatchIndex > readyTuples.size() || tupleBatchIndex == readyTuples.size() && tupleIndex >= currentInProgressTuples) { throw new IndexOutOfBoundsException(); } if (tupleBatchIndex < readyTuples.size()) { MutableColumn<?> dest = readyTuples.get(tupleBatchIndex)[destColumn]; switch (dest.getType()) { case BOOLEAN_TYPE: ((BooleanMutableColumn) dest).replace(tupleIndex, sourceColumn.getBoolean(sourceRow)); break; case DATETIME_TYPE: ((DateTimeMutableColumn) dest).replace(tupleIndex, sourceColumn.getDateTime(sourceRow)); break; case DOUBLE_TYPE: ((DoubleMutableColumn) dest).replace(tupleIndex, sourceColumn.getDouble(sourceRow)); break; case FLOAT_TYPE: ((FloatMutableColumn) dest).replace(tupleIndex, sourceColumn.getFloat(sourceRow)); break; case INT_TYPE: ((IntArrayMutableColumn) dest).replace(tupleIndex, sourceColumn.getInt(sourceRow)); break; case LONG_TYPE: ((LongMutableColumn) dest).replace(tupleIndex, sourceColumn.getLong(sourceRow)); break; case STRING_TYPE: ((StringMutableColumn) dest).replace(tupleIndex, sourceColumn.getString(sourceRow)); break; } } else { ColumnBuilder<?> dest = currentBuildingColumns[destColumn]; switch (dest.getType()) { case BOOLEAN_TYPE: ((BooleanColumnBuilder) dest).replace(tupleIndex, sourceColumn.getBoolean(sourceRow)); break; case DATETIME_TYPE: ((DateTimeColumnBuilder) dest).replace(tupleIndex, sourceColumn.getDateTime(sourceRow)); break; case DOUBLE_TYPE: ((DoubleColumnBuilder) dest).replace(tupleIndex, sourceColumn.getDouble(sourceRow)); break; case FLOAT_TYPE: ((FloatColumnBuilder) dest).replace(tupleIndex, sourceColumn.getFloat(sourceRow)); break; case INT_TYPE: ((IntColumnBuilder) dest).replace(tupleIndex, sourceColumn.getInt(sourceRow)); break; case LONG_TYPE: ((LongColumnBuilder) dest).replace(tupleIndex, sourceColumn.getLong(sourceRow)); break; case STRING_TYPE: ((StringColumnBuilder) dest).replace(tupleIndex, sourceColumn.getString(sourceRow)); break; } } } /** * Return all tuples in this buffer. The data do not get removed. * * @return a List<TupleBatch> containing all complete tuples that have been inserted into this buffer. */ public final List<TupleBatch> getAll() { final List<TupleBatch> output = new ArrayList<TupleBatch>(); for (final MutableColumn<?>[] mutableColumns : readyTuples) { List<Column<?>> columns = new ArrayList<Column<?>>(); for (MutableColumn<?> mutableColumn : mutableColumns) { columns.add(mutableColumn.toColumn()); } output.add(new TupleBatch(schema, columns, TupleBatch.BATCH_SIZE)); } if (currentInProgressTuples > 0) { output.add(new TupleBatch(schema, getInProgressColumns(), currentInProgressTuples)); } return output; } /** * Build the in progress columns. The builders' states are untouched. They can keep building. * * @return the built in progress columns. * */ private List<Column<?>> getInProgressColumns() { List<Column<?>> newColumns = new ArrayList<Column<?>>(currentBuildingColumns.length); for (ColumnBuilder<?> cb : currentBuildingColumns) { newColumns.add(cb.forkNewBuilder().build()); } return newColumns; } @Override public TupleBuffer clone() { TupleBuffer ret = new TupleBuffer(getSchema()); ret.columnsReady = (BitSet) columnsReady.clone(); ret.numColumnsReady = numColumnsReady; ret.currentInProgressTuples = currentInProgressTuples; for (MutableColumn<?>[] columns : readyTuples) { MutableColumn<?>[] tmp = new MutableColumn<?>[columns.length]; for (int i = 0; i < columns.length; ++i) { tmp[i] = columns[i].clone(); } ret.readyTuples.add(tmp); } for (int i = 0; i < currentBuildingColumns.length; ++i) { ret.currentBuildingColumns[i] = currentBuildingColumns[i].forkNewBuilder(); } return ret; } }
package com.trendrr.oss.appender; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.trendrr.oss.FileHelper; import com.trendrr.oss.StringHelper; import com.trendrr.oss.TimeAmount; import com.trendrr.oss.TypeCast; import com.trendrr.oss.appender.exceptions.FileClosedException; import com.trendrr.oss.exceptions.TrendrrIOException; /** * @author Dustin Norlander * @created Jun 17, 2013 * */ public class TimeAmountFile { protected static Log log = LogFactory.getLog(TimeAmountFile.class); private File file; private long epoch; private TimeAmount timeAmount; private boolean stale = false; private boolean callbackreturn = false; private long maxBytes; private long curBytes = 0; private FileWriter writer = null; private Date lastWrite = new Date(); public TimeAmountFile(TimeAmount ta, long epoch, String dir, long maxBytes) throws Exception { if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } this.epoch = epoch; this.timeAmount = ta; this.maxBytes = maxBytes; boolean exists = true; while(exists) { //guarentee uniqueness. String filename = dir + epoch +"_" + ta.abbreviation() + "__" + StringHelper.getRandomString(5); filename = FileHelper.toSystemDependantFilename(filename); FileHelper.createDirectories(filename); this.file = new File(filename); exists = !file.createNewFile(); } this.writer = new FileWriter(this.file, true); } /** * Creates from previously created file. * @param file * @throws Exception */ public TimeAmountFile(File file, long maxBytes) throws Exception { String filename = file.getName(); String tmp[] = filename.split("_"); if (tmp.length < 3) { throw new TrendrrIOException("File : " + filename + " is not a TimeAmountFile"); } this.epoch = TypeCast.cast(Long.class, tmp[0]); this.timeAmount = TimeAmount.instance(tmp[1]); this.file = file; this.writer = new FileWriter(this.file, true); this.maxBytes = maxBytes; } /** * stales the file. * @param callback * @return */ // Moved The delete code to callback level for deleting after the uploading protected synchronized void stale(TimeAmountFileCallback callback) { if (this.callbackreturn) return; //do nothing.. this.callbackreturn = true; callback.staleFile(this); } /** * Append to this file. note that * @param str * @throws FileClosedException * @throws IOException */ public synchronized void append(String str) throws FileClosedException, IOException { if (stale) { throw new FileClosedException(); } //check that we havent gone over the max bytes if (maxBytes > 0 && curBytes >= maxBytes) { this.setStale(); throw new FileClosedException(); } //Just count the chars for speed. this.curBytes += str.length(); this.lastWrite = new Date(); this.writer.append(str); this.writer.flush(); } public synchronized void setStale() { stale = true; try { this.writer.flush(); this.writer.close(); } catch (Exception x) { log.error("Caught", x); } } public synchronized File getFile() { return file; } public synchronized long getEpoch() { return epoch; } public synchronized TimeAmount getTimeAmount() { return timeAmount; } public synchronized long getMaxBytes() { return maxBytes; } public synchronized long getCurBytes() { return curBytes; } public synchronized Date getLastWrite() { return lastWrite; } }
package annotators; import java.util.ArrayList; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.jcas.JCas; import types.TextualSegment; public class TextualSegmentAnnotator extends JCasAnnotator_ImplBase { @Override public void process(JCas jCas) throws AnalysisEngineProcessException { ArrayList<Character> digits = new ArrayList<Character>(); for (Character i = '0'; i != '9'+1; ++i) digits.add(i); ArrayList<Character> caps = new ArrayList<Character>(); for (Character i = 'A'; i != 'Z' + 1; ++i) caps.add(i); String text = jCas.getDocumentText() + " "; int pred = 0; boolean skip = false; boolean digit_read = false; for(int i = 0; i < text.length(); ++i) { if (skip) { skip = false; continue; } if (text.charAt(i) == '.' && (text.charAt(i+1) == ' ' || text.charAt(i+1) == '\n')) { TextualSegment seg = new TextualSegment(jCas, pred, i); seg.addToIndexes(); pred = i+2; skip = true; } else if (text.charAt(i) == '\n' && caps.contains(text.charAt(i+1))) { TextualSegment seg = new TextualSegment(jCas, pred, i); seg.addToIndexes(); pred = i+1; } else if (!digit_read && digits.contains(text.charAt(i))) { TextualSegment seg = new TextualSegment(jCas, pred, i); seg.addToIndexes(); pred = i+1; skip = true; digit_read = true; } else if (digit_read && text.charAt(i) == ' ') { digit_read = false; pred = i+1; } } } }
package ca.sapon.jici.lexer; public class LexerException extends Exception { private static final long serialVersionUID = 1; public LexerException(String error, String source, int index) { super(generateMessage(error, source, index)); } private static String generateMessage(String error, String source, int index) { final String offender = escapeOffender(source.charAt(index)); // find start and end of line containing the offender int start = index, end = index - 1; while (--start >= 0 && source.charAt(start) != '\n'); while (++end < source.length() && source.charAt(end) != '\n'); source = source.substring(start + 1, end); index -= start; // build the error message with source and cursor lines final StringBuilder builder = new StringBuilder(error) .append(" caused by ") .append(offender) .append(" at position ") .append(index) .append(" in \n") .append(source) .append('\n'); for (int i = 0; i < index - 1; i++) { builder.append(' '); } builder.append('^'); return builder.toString(); } private static String escapeOffender(char offender) { if (Character.isWhitespace(offender)) { return Character.getName(offender); } return '\'' + String.valueOf(offender) + '\''; } }
package cn.momia.mapi.api.v1; import cn.momia.api.course.dto.CourseCommentDto; import cn.momia.api.feed.dto.FeedDto; import cn.momia.api.user.dto.ChildDto; import cn.momia.image.api.ImageFile; import cn.momia.mapi.api.AbstractApi; import cn.momia.api.user.dto.UserDto; import java.util.ArrayList; import java.util.List; public class AbstractV1Api extends AbstractApi { protected List<String> completeImgs(List<String> imgs) { if (imgs == null) return null; List<String> completedImgs = new ArrayList<String>(); for (String img : imgs) { completedImgs.add(ImageFile.url(img)); } return completedImgs; } protected List<String> completeLargeImgs(List<String> imgs) { if (imgs == null) return null; List<String> completedImgs = new ArrayList<String>(); for (String img : imgs) { completedImgs.add(ImageFile.largeUrl(img)); } return completedImgs; } protected List<String> completeMiddleImgs(List<String> imgs) { if (imgs == null) return null; List<String> completedImgs = new ArrayList<String>(); for (String img : imgs) { completedImgs.add(ImageFile.middleUrl(img)); } return completedImgs; } protected List<String> completeSmallImgs(List<String> imgs) { if (imgs == null) return null; List<String> completedImgs = new ArrayList<String>(); for (String img : imgs) { completedImgs.add(ImageFile.smallUrl(img)); } return completedImgs; } protected void processCourseComments(List<CourseCommentDto> comments) { for (CourseCommentDto comment : comments) { comment.setAvatar(ImageFile.smallUrl(comment.getAvatar())); List<String> imgs = comment.getImgs(); comment.setImgs(completeSmallImgs(imgs)); comment.setLargeImgs(completeImgs(imgs)); } } protected void processFeeds(List<FeedDto> feeds) { for (FeedDto feed : feeds) { processFeed(feed); } } protected void processFeed(FeedDto feed) { List<String> imgs = feed.getImgs(); feed.setImgs(completeMiddleImgs(imgs)); feed.setLargeImgs(completeImgs(imgs)); feed.setAvatar(ImageFile.smallUrl(feed.getAvatar())); } protected UserDto processUser(UserDto user) { user.setAvatar(ImageFile.smallUrl(user.getAvatar())); processChildren(user.getChildren()); return user; } protected List<ChildDto> processChildren(List<ChildDto> children) { for (ChildDto child : children) { processChild(child); } return children; } protected ChildDto processChild(ChildDto child) { child.setAvatar(ImageFile.smallUrl(child.getAvatar())); return child; } }
package cn.ranta.demo.luceneengine; import java.io.IOException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; /** * Hello world! * */ public class Program { public static void main(String[] args) { Directory directory = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(); CreateIndex(directory, analyzer); Search(directory, analyzer); System.out.println("the end."); } private static void CreateIndex(Directory directory, Analyzer analyzer) { try { IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig); for (int i = 0; i < 100; i++) { Document document = new Document(); FieldType storeOnlyFieldType = new FieldType(); storeOnlyFieldType.setStored(true); document.add(new Field("StoreOnly", String.format("Store Only %d %d", i / 10, i % 10), storeOnlyFieldType)); FieldType indexOnlyFieldType = new FieldType(); indexOnlyFieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); document.add(new Field("IndexOnly", String.format("Index Only %d %d", i / 10, i % 10), indexOnlyFieldType)); FieldType storeIndexFieldType = new FieldType(); storeIndexFieldType.setStored(true); storeIndexFieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); document.add(new Field("StoreIndex", String.format("Store Index %d %d", i / 10, i % 10), storeIndexFieldType)); indexWriter.addDocument(document); } // indexWriter.commit(); indexWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private static void Search(Directory directory, Analyzer analyzer) { try { IndexReader indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader); TopDocs topDocs = null; int demo = 4; switch (demo) { case 1: { TermQuery termQuery = new TermQuery(new Term("StoreOnly", "7")); topDocs = indexSearcher.search(termQuery, 5); } break; case 2: { TermQuery termQuery = new TermQuery(new Term("IndexOnly", "7")); topDocs = indexSearcher.search(termQuery, 5); } break; case 3: { TermQuery termQuery = new TermQuery(new Term("StoreIndex", "7")); topDocs = indexSearcher.search(termQuery, 5); } break; case 4: { TermQuery termQuery6 = new TermQuery(new Term("IndexOnly", "6")); TermQuery termQuery7 = new TermQuery(new Term("IndexOnly", "7")); BooleanQuery booleanQuery = new BooleanQuery.Builder() .add(new BooleanClause(termQuery6, Occur.MUST)) .add(new BooleanClause(termQuery7, Occur.MUST)) .build(); topDocs = indexSearcher.search(booleanQuery, 20); } break; default: break; } if (topDocs != null && topDocs.scoreDocs.length > 0) { for (ScoreDoc scoreDoc : topDocs.scoreDocs) { Document document = indexReader.document(scoreDoc.doc); // IndexableField storeOnlyField = document.getField("StoreOnly"); // if (storeOnlyField != null) { // System.out.println(storeOnlyField.stringValue()); // } else { // System.out.println("null"); // IndexableField indexOnlyField = document.getField("IndexOnly"); // if (indexOnlyField != null) { // System.out.println(indexOnlyField.stringValue()); // } else { // System.out.println("null"); IndexableField storeIndexField = document.getField("StoreIndex"); if (storeIndexField != null) { System.out.println(storeIndexField.stringValue()); } else { System.out.println("null"); } System.out.println(""); } } indexReader.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.checkmarx.jenkins; import static ch.lambdaj.Lambda.filter; import static ch.lambdaj.Lambda.having; import static ch.lambdaj.Lambda.on; import hudson.AbortException; import hudson.FilePath; import hudson.util.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.stream.XMLStreamException; import javax.xml.ws.BindingProvider; import javax.xml.ws.WebServiceException; import jenkins.model.Jenkins; import org.apache.commons.lang3.tuple.Pair; import org.apache.log4j.Logger; import org.hamcrest.Matchers; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.checkmarx.jenkins.xmlresponseparser.CreateAndRunProjectXmlResponseParser; import com.checkmarx.jenkins.xmlresponseparser.RunIncrementalScanXmlResponseParser; import com.checkmarx.jenkins.xmlresponseparser.RunScanAndAddToProjectXmlResponseParser; import com.checkmarx.jenkins.xmlresponseparser.XmlResponseParser; import com.checkmarx.ws.CxJenkinsWebService.ConfigurationSet; import com.checkmarx.ws.CxJenkinsWebService.CreateAndRunProject; import com.checkmarx.ws.CxJenkinsWebService.Credentials; import com.checkmarx.ws.CxJenkinsWebService.CxJenkinsWebService; import com.checkmarx.ws.CxJenkinsWebService.CxJenkinsWebServiceSoap; import com.checkmarx.ws.CxJenkinsWebService.CxWSBasicRepsonse; import com.checkmarx.ws.CxJenkinsWebService.CxWSCreateReportResponse; import com.checkmarx.ws.CxJenkinsWebService.CxWSReportRequest; import com.checkmarx.ws.CxJenkinsWebService.CxWSReportStatusResponse; import com.checkmarx.ws.CxJenkinsWebService.CxWSReportType; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseConfigSetList; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseGroupList; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseLoginData; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponsePresetList; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseProjectsDisplayData; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseRunID; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseScanResults; import com.checkmarx.ws.CxJenkinsWebService.CxWSResponseScanStatus; import com.checkmarx.ws.CxJenkinsWebService.Group; import com.checkmarx.ws.CxJenkinsWebService.LocalCodeContainer; import com.checkmarx.ws.CxJenkinsWebService.Preset; import com.checkmarx.ws.CxJenkinsWebService.ProjectDisplayData; import com.checkmarx.ws.CxJenkinsWebService.ProjectSettings; import com.checkmarx.ws.CxJenkinsWebService.RunIncrementalScan; import com.checkmarx.ws.CxJenkinsWebService.RunScanAndAddToProject; import com.checkmarx.ws.CxWSResolver.CxClientType; import com.checkmarx.ws.CxWSResolver.CxWSResolver; import com.checkmarx.ws.CxWSResolver.CxWSResolverSoap; import com.checkmarx.ws.CxWSResolver.CxWSResponseDiscovery; /** * Wraps all Web services invocations * * @author denis * @since 13/11/2013 */ public class CxWebService { private static final int WEBSERVICE_API_VERSION = 1; private static final String CXWSRESOLVER_PATH = "/cxwebinterface/cxwsresolver.asmx"; private static final int LCID = 1033; // English private static final int MILISEOUNDS_IN_HOUR = 1000 * 60 * 60; private final Logger logger; private String sessionId; private CxJenkinsWebServiceSoap cxJenkinsWebServiceSoap; private final URL webServiceUrl; public CxWebService(String serverUrl) throws MalformedURLException, AbortException { this(serverUrl, null); } public CxWebService(@NotNull final String serverUrl, @Nullable final String loggerSuffix) throws MalformedURLException, AbortException { logger = CxLogUtils.loggerWithSuffix(getClass(), loggerSuffix); @Nullable CxScanBuilder.DescriptorImpl descriptor = (CxScanBuilder.DescriptorImpl) Jenkins.getInstance().getDescriptor( CxScanBuilder.class); if (descriptor != null && !descriptor.isEnableCertificateValidation()) { logger.info("SSL/TLS Certificate Validation Disabled"); CxSSLUtility.disableSSLCertificateVerification(); } logger.info("Establishing connection with Checkmarx server at: " + serverUrl); URL serverUrlUrl = new URL(serverUrl); if (serverUrlUrl.getPath().length() > 0) { String message = "Checkmarx server url must not contain path: " + serverUrl; logger.debug(message); throw new AbortException(message); } URL resolverUrl = new URL(serverUrl + CXWSRESOLVER_PATH); logger.debug("Resolver url: " + resolverUrl); CxWSResolver cxWSResolver; try { cxWSResolver = new CxWSResolver(resolverUrl); } catch (javax.xml.ws.WebServiceException e) { logger.error("Failed to resolve Checkmarx webservice url with resolver at: " + resolverUrl, e); throw new AbortException("Checkmarx server was not found on url: " + serverUrl); } CxWSResolverSoap cxWSResolverSoap = cxWSResolver.getCxWSResolverSoap(); setClientTimeout((BindingProvider) cxWSResolverSoap, CxConfig.getRequestTimeOutDuration()); CxWSResponseDiscovery cxWSResponseDiscovery = cxWSResolverSoap.getWebServiceUrl(CxClientType.JENKINS, WEBSERVICE_API_VERSION); if (!cxWSResponseDiscovery.isIsSuccesfull()) { String message = "Failed to resolve Checkmarx webservice url: \n" + cxWSResponseDiscovery.getErrorMessage(); logger.error(message); throw new AbortException(message); } webServiceUrl = new URL(cxWSResponseDiscovery.getServiceURL()); logger.debug("Webservice url: " + webServiceUrl); CxJenkinsWebService cxJenkinsWebService = new CxJenkinsWebService(webServiceUrl); cxJenkinsWebServiceSoap = cxJenkinsWebService.getCxJenkinsWebServiceSoap(); setClientTimeout((BindingProvider) cxJenkinsWebServiceSoap, CxConfig.getRequestTimeOutDuration()); } private void setClientTimeout(BindingProvider provider, int seconds) { logger.debug("Setting connection timeout to " + seconds + " seconds"); int milliseconds = seconds * 1000; Map<String, Object> requestContext = provider.getRequestContext(); requestContext.put("com.sun.xml.internal.ws.connect.timeout", milliseconds); requestContext.put("com.sun.xml.internal.ws.request.timeout", milliseconds); requestContext.put("com.sun.xml.ws.request.timeout", milliseconds); requestContext.put("com.sun.xml.ws.connect.timeout", milliseconds); requestContext.put("javax.xml.ws.client.connectionTimeout", milliseconds); requestContext.put("javax.xml.ws.client.receiveTimeout", milliseconds); requestContext.put("timeout", milliseconds); // IBM } public void login(@Nullable String username, @Nullable String password) throws AbortException { sessionId = null; Credentials credentials = new Credentials(); credentials.setUser(username); credentials.setPass(password); CxWSResponseLoginData cxWSResponseLoginData = cxJenkinsWebServiceSoap.login(credentials, LCID); if (!cxWSResponseLoginData.isIsSuccesfull()) { logger.error("Login to Checkmarx server failed:"); logger.error(cxWSResponseLoginData.getErrorMessage()); throw new AbortException(cxWSResponseLoginData.getErrorMessage()); } sessionId = cxWSResponseLoginData.getSessionId(); logger.debug("Login successful, sessionId: " + sessionId); } private CxWSResponseScanStatus getScanStatus(CxWSResponseRunID cxWSResponseRunID) throws AbortException { assert sessionId != null : "Trying to get scan status before login"; CxWSResponseScanStatus cxWSResponseScanStatus = cxJenkinsWebServiceSoap.getStatusOfSingleScan(sessionId, cxWSResponseRunID.getRunId()); if (!cxWSResponseScanStatus.isIsSuccesfull()) { String message = "Error received from Checkmarx server: " + cxWSResponseScanStatus.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseScanStatus; } public long trackScanProgress(final CxWSResponseRunID cxWSResponseRunID, final String username, final String password, final boolean scanTimeOutEnabled, final long scanTimeoutDuration) throws AbortException, InterruptedException { assert sessionId != null : "Trying to track scan progress before login"; final long jobStartTime = System.currentTimeMillis(); int retryAttempts = CxConfig.getServerCallRetryNumber(); boolean locReported = false; while (true) { try { Thread.sleep(10L * 1000); if (scanTimeOutEnabled && jobStartTime + scanTimeoutDuration * MILISEOUNDS_IN_HOUR < System.currentTimeMillis()) { logger.info("Scan duration exceeded timeout threshold"); return 0; } CxWSResponseScanStatus status = this.getScanStatus(cxWSResponseRunID); switch (status.getCurrentStatus()) { // In progress states case WAITING_TO_PROCESS: logger.info("Scan job waiting for processing"); break; case QUEUED: if (!locReported) { logger.info("Source contains: " + status.getLOC() + " lines of code."); locReported = true; } logger.info("Scan job queued at position: " + status.getQueuePosition()); break; case UNZIPPING: logger.info("Unzipping: " + status.getCurrentStagePercent() + "% finished"); logger.info("LOC: " + status.getLOC()); logger.info("StageMessage: " + status.getStageMessage()); logger.info("StepMessage: " + status.getStepMessage()); logger.info("StepDetails: " + status.getStepDetails()); break; case WORKING: logger.info("Scanning: " + status.getStageMessage() + " " + status.getStepDetails() + " (Current stage progress: " + status.getCurrentStagePercent() + "%, Total progress: " + status.getTotalPercent() + "%)"); break; // End of progress states case FINISHED: logger.info("Scan Finished Successfully - RunID: " + status.getRunId() + " ScanID:" + status.getScanId()); return status.getScanId(); case FAILED: case DELETED: case UNKNOWN: case CANCELED: String message = "Scan " + status.getStageName() + " - RunID: " + status.getRunId() + " ScanID: " + status.getScanId() + " Server scan status: " + status.getStageMessage(); logger.info(message); throw new AbortException(message); } } catch (AbortException | WebServiceException e) { // Here we handle a case where the sessionId was timed out in // the server // and we need to re-login to continue working. The default // sessionId // timeout in the server is 24 hours. if (e.getMessage().contains("Unauthorized")) { logger.info("Session was rejected by the Checkmarx server, trying to re-login"); this.login(username, password); continue; } else if (retryAttempts > 0) { retryAttempts } else { throw e; } } } } public CxWSCreateReportResponse generateScanReport(long scanId, CxWSReportType reportType) throws AbortException { assert sessionId != null : "Trying to retrieve scan report before login"; CxWSReportRequest cxWSReportRequest = new CxWSReportRequest(); cxWSReportRequest.setScanID(scanId); cxWSReportRequest.setType(reportType); logger.info("Requesting " + reportType.toString().toUpperCase() + " Scan Report Generation"); int retryAttempts = CxConfig.getServerCallRetryNumber(); CxWSCreateReportResponse cxWSCreateReportResponse; do { cxWSCreateReportResponse = cxJenkinsWebServiceSoap.createScanReport(sessionId, cxWSReportRequest); if (!cxWSCreateReportResponse.isIsSuccesfull()) { retryAttempts logger.warn("Error requesting scan report generation: " + cxWSCreateReportResponse.getErrorMessage()); } } while (!cxWSCreateReportResponse.isIsSuccesfull() && retryAttempts > 0); if (!cxWSCreateReportResponse.isIsSuccesfull()) { String message = "Error requesting scan report generation: " + cxWSCreateReportResponse.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSCreateReportResponse; } public void retrieveScanReport(long reportId, File reportFile, CxWSReportType reportType) throws AbortException, InterruptedException { // Wait for the report to become ready while (true) { CxWSReportStatusResponse cxWSReportStatusResponse = cxJenkinsWebServiceSoap.getScanReportStatus(sessionId, reportId); if (!cxWSReportStatusResponse.isIsSuccesfull()) { String message = "Error retrieving scan report status: " + cxWSReportStatusResponse.getErrorMessage(); logger.error(message); throw new AbortException(message); } if (cxWSReportStatusResponse.isIsFailed()) { String message = "Failed to create scan report"; logger.error("Web method getScanReportStatus returned status response with isFailed field set to true"); logger.error(message); throw new AbortException(message); } if (cxWSReportStatusResponse.isIsReady()) { logger.info("Scan report generated on Checkmarx server"); break; } logger.info(reportType.toString().toUpperCase() + " Report generation in progress"); Thread.sleep(5L * 1000); } CxWSResponseScanResults cxWSResponseScanResults = cxJenkinsWebServiceSoap.getScanReport(sessionId, reportId); if (!cxWSResponseScanResults.isIsSuccesfull()) { String message = "Error retrieving scan report: " + cxWSResponseScanResults.getErrorMessage(); logger.error(message); throw new AbortException(message); } // Save results on disk try { FileOutputStream fileOutputStream = new FileOutputStream(reportFile); IOUtils.write(cxWSResponseScanResults.getScanResults(), fileOutputStream); fileOutputStream.close(); } catch (IOException e) { logger.debug(e); String message = "Can't create report file: " + reportFile.getAbsolutePath(); logger.info(message); throw new AbortException(message); } logger.info("Scan report written to: " + reportFile.getAbsolutePath()); } public List<ProjectDisplayData> getProjectsDisplayData() throws AbortException { assert sessionId != null : "Trying to retrieve projects display data before login"; CxWSResponseProjectsDisplayData cxWSResponseProjectsDisplayData = this.cxJenkinsWebServiceSoap .getProjectsDisplayData(this.sessionId); if (!cxWSResponseProjectsDisplayData.isIsSuccesfull()) { String message = "Error retrieving projects display data from server: " + cxWSResponseProjectsDisplayData.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseProjectsDisplayData.getProjectList().getProjectDisplayData(); } public List<Preset> getPresets() throws AbortException { assert sessionId != null : "Trying to retrieve presetes before login"; CxWSResponsePresetList cxWSResponsePresetList = this.cxJenkinsWebServiceSoap.getPresetList(this.sessionId); if (!cxWSResponsePresetList.isIsSuccesfull()) { String message = "Error retrieving presets from server: " + cxWSResponsePresetList.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponsePresetList.getPresetList().getPreset(); } // Source encoding is called "configuration" in server terms public List<ConfigurationSet> getSourceEncodings() throws AbortException { assert sessionId != null : "Trying to retrieve configurations before login"; CxWSResponseConfigSetList cxWSResponseConfigSetList = this.cxJenkinsWebServiceSoap .getConfigurationSetList(sessionId); if (!cxWSResponseConfigSetList.isIsSuccesfull()) { String message = "Error retrieving configurations from server: " + cxWSResponseConfigSetList.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseConfigSetList.getConfigSetList().getConfigurationSet(); } public CxWSBasicRepsonse validateProjectName(String cxProjectName, String groupId) { assert sessionId != null : "Trying to validate project name before login"; return this.cxJenkinsWebServiceSoap.isValidProjectName(sessionId, cxProjectName, groupId); } private Pair<byte[], byte[]> createScanSoapMessage(Object request, Class inputType, ProjectSettings projectSettings, LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan) { final String soapMessageHead = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http: + "xmlns:xsd=\"http: + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n"; final String soapMessageTail = "\n </soap:Body>\n</soap:Envelope>"; final String zippedFileOpenTag = "<ZippedFile>"; final String zippedFileCloseTag = "</ZippedFile>"; try { final JAXBContext context = JAXBContext.newInstance(inputType); final Marshaller marshaller = context.createMarshaller(); StringWriter scanMessage = new StringWriter(); scanMessage.write(soapMessageHead); // Nullify the zippedFile field, and save its old value for // restoring later final byte[] oldZippedFileValue = localCodeContainer.getZippedFile(); localCodeContainer.setZippedFile(new byte[] {}); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(request, scanMessage); localCodeContainer.setZippedFile(oldZippedFileValue); // Restore the // old value scanMessage.write(soapMessageTail); // Here we split the message around <ZippedFile></ZippedFile> // substring. We know that the opening // and closing tag are adjacent because the zippedFile property was // set to empty byte array final String[] parts = scanMessage.toString().split(zippedFileOpenTag + zippedFileCloseTag); assert parts.length == 2; final String startPart = parts[0] + zippedFileOpenTag; final String endPart = zippedFileCloseTag + parts[1]; return Pair.of(startPart.getBytes("UTF-8"), endPart.getBytes("UTF-8")); } catch (JAXBException | UnsupportedEncodingException e) { // Getting here indicates a bug logger.error(e.getMessage(), e); throw new RuntimeException("Eror creating SOAP message", e); } } public List<Group> getAssociatedGroups() throws AbortException { assert sessionId != null : "Trying to retrieve teams before login"; final CxWSResponseGroupList associatedGroupsList = this.cxJenkinsWebServiceSoap .getAssociatedGroupsList(sessionId); if (!associatedGroupsList.isIsSuccesfull()) { String message = "Error retrieving associated groups (teams) from server: " + associatedGroupsList.getErrorMessage(); logger.error(message); throw new AbortException(message); } return associatedGroupsList.getGroupList().getGroup(); } public CxWSResponseRunID runScanAndAddToProject(ProjectSettings projectSettings, LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan, final FilePath base64ZipFile) throws AbortException { assert sessionId != null; RunScanAndAddToProject scan = new RunScanAndAddToProject(); scan.setLocalCodeContainer(localCodeContainer); scan.setSessionId(sessionId); scan.setProjectSettings(projectSettings); scan.setVisibleToUtherUsers(visibleToOtherUsers); scan.setIsPublicScan(isPublicScan); Pair<byte[], byte[]> soapMeassage = createScanSoapMessage(scan, RunScanAndAddToProject.class, projectSettings, localCodeContainer, visibleToOtherUsers, isPublicScan); return scan(localCodeContainer, visibleToOtherUsers, isPublicScan, base64ZipFile, "RunScanAndAddToProject", soapMeassage, new RunScanAndAddToProjectXmlResponseParser()); } public CxWSResponseRunID runIncrementalScan(ProjectSettings projectSettings, LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan, final FilePath base64ZipFile) throws AbortException { assert sessionId != null; RunIncrementalScan scan = new RunIncrementalScan(); scan.setLocalCodeContainer(localCodeContainer); scan.setSessionId(sessionId); scan.setProjectSettings(projectSettings); scan.setVisibleToUtherUsers(visibleToOtherUsers); scan.setIsPublicScan(isPublicScan); Pair<byte[], byte[]> soapMeassage = createScanSoapMessage(scan, RunIncrementalScan.class, projectSettings, localCodeContainer, visibleToOtherUsers, isPublicScan); return scan(localCodeContainer, visibleToOtherUsers, isPublicScan, base64ZipFile, "RunIncrementalScan", soapMeassage, new RunIncrementalScanXmlResponseParser()); } public CxWSResponseRunID createAndRunProject(ProjectSettings projectSettings, LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan, final FilePath base64ZipFile) throws AbortException { assert sessionId != null; CreateAndRunProject scan = new CreateAndRunProject(); scan.setLocalCodeContainer(localCodeContainer); scan.setSessionID(sessionId); scan.setProjectSettings(projectSettings); scan.setVisibleToOtherUsers(visibleToOtherUsers); scan.setIsPublicScan(isPublicScan); Pair<byte[], byte[]> soapMessage = createScanSoapMessage(scan, CreateAndRunProject.class, projectSettings, localCodeContainer, visibleToOtherUsers, isPublicScan); return scan(localCodeContainer, visibleToOtherUsers, isPublicScan, base64ZipFile, "CreateAndRunProject", soapMessage, new CreateAndRunProjectXmlResponseParser()); } public long getProjectId(ProjectSettings projectSettings) throws AbortException { CxWSResponseProjectsDisplayData projects = cxJenkinsWebServiceSoap.getProjectsDisplayData(sessionId); final String groupId = projectSettings.getAssociatedGroupID(); final List<Group> groups = getAssociatedGroups(); final List<Group> selected = filter(having(on(Group.class).getID(), Matchers.equalTo(groupId)), groups); if (selected.isEmpty()) { final String message = "Could not translate group (team) id: " + groupId + " to group name\n" + "Open the Job configuration page, and select a team.\n"; logger.error(message); throw new AbortException(message); } else if (selected.size() > 1) { logger.warn("Server returned more than one group with id: " + groupId); for (Group g : selected) { logger.warn("Group Id: " + g.getID() + " groupName: " + g.getGroupName()); } } long projectId = 0; if (projects != null && projects.isIsSuccesfull()) { for (ProjectDisplayData projectDisplayData : projects.getProjectList().getProjectDisplayData()) { if (projectDisplayData.getProjectName().equals(projectSettings.getProjectName()) && projectDisplayData.getGroup().equals(selected.get(0).getGroupName())) { projectId = projectDisplayData.getProjectID(); break; } } } if (projectId == 0) { throw new AbortException("Can't find exsiting project to scan"); } return projectId; } /** * Same as "scan" method, but works by streaming the * LocalCodeContainer.zippedFile contents. NOTE: The attribute * LocalCodeContainer.zippedFile inside args is REPLACED by empty byte * array, and base64ZipFile temp file is used instead. * * @param base64ZipFile * - Temp file used instead of LocalCodeContainer.zippedFile * attribute, should contain zipped sources encoded with base 64 * encoding * @return object which is similar to the return value of scan web service * method * @throws AbortException */ private CxWSResponseRunID scan(LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan, final FilePath base64ZipFile, String soapActionName, Pair<byte[], byte[]> soapMessage, XmlResponseParser xmlResponseParser) throws AbortException { assert sessionId != null; int retryAttemptsLeft = CxConfig.getServerCallRetryNumber(); while (true) { try { return sendScanRequest(base64ZipFile, soapActionName, soapMessage, xmlResponseParser); } catch (AbortException abort) { if (retryAttemptsLeft > 0) { retryAttemptsLeft } else { throw abort; } } } } private CxWSResponseRunID sendScanRequest(final FilePath base64ZipFile, String soapActionName, Pair<byte[], byte[]> soapMessage, XmlResponseParser xmlResponseParser) throws AbortException { try { // Create HTTP connection final HttpURLConnection streamingUrlConnection = (HttpURLConnection) webServiceUrl.openConnection(); streamingUrlConnection.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); streamingUrlConnection.addRequestProperty("SOAPAction", String.format("\"http://Checkmarx.com/v7/%s\"", soapActionName)); streamingUrlConnection.setDoOutput(true); // Calculate the length of the soap message final long length = soapMessage.getLeft().length + soapMessage.getRight().length + base64ZipFile.length(); streamingUrlConnection.setFixedLengthStreamingMode((int) length); streamingUrlConnection.connect(); final OutputStream os = streamingUrlConnection.getOutputStream(); logger.info("Uploading sources to Checkmarx server"); os.write(soapMessage.getLeft()); final InputStream fis = base64ZipFile.read(); org.apache.commons.io.IOUtils.copyLarge(fis, os); os.write(soapMessage.getRight()); os.close(); fis.close(); logger.info("Finished uploading sources to Checkmarx server"); CxWSResponseRunID cxWSResponseRunID = xmlResponseParser.parse(streamingUrlConnection.getInputStream()); if (!cxWSResponseRunID.isIsSuccesfull()) { String message = "Submission of sources for scan failed: \n" + cxWSResponseRunID.getErrorMessage(); throw new AbortException(message); } return cxWSResponseRunID; } catch (HttpRetryException e) { String consoleMessage = "\nCheckmarx plugin for Jenkins does not support Single sign-on authentication." + "\nPlease, configure Checkmarx server to work in Anonymous authentication mode.\n"; logger.error(consoleMessage); throw new AbortException(e.getMessage()); } catch (IOException | JAXBException | XMLStreamException | InterruptedException e) { logger.error(e.getMessage(), e); throw new AbortException(e.getMessage()); } } /** * Cancel scan on Checkmarx server * * @param runId * run ID of the scan * @return server response */ public CxWSBasicRepsonse cancelScan(String runId) { return cxJenkinsWebServiceSoap.cancelScan(sessionId, runId); } /** * Cancel report generation on Checkmarx server * * @param reportId * ID of the report * @return server response */ public CxWSBasicRepsonse cancelScanReport(long reportId) { return cxJenkinsWebServiceSoap.cancelScanReport(sessionId, reportId); } }
package com.checkmarx.jenkins; import com.checkmarx.ws.CxCLIWebService.*; import com.checkmarx.ws.CxWSResolver.*; import com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException; import hudson.AbortException; import hudson.model.BuildListener; import hudson.util.IOUtils; import org.apache.log4j.Logger; import javax.xml.namespace.QName; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class CxWebService { private final static Logger logger = Logger.getLogger(CxWebService.class); private final static QName CXWSRESOLVER_QNAME = new QName("http://Checkmarx.com", "CxWSResolver"); private final static QName CXCLIWEBSERVICE_QNAME = new QName("http://Checkmarx.com/v7", "CxCLIWebService"); private final static int WEBSERVICE_API_VERSION = 7; private final static String CXWSRESOLVER_PATH = "/cxwebinterface/cxwsresolver.asmx"; private final static int LCID = 1033; // English private String sessionId; private CxCLIWebServiceSoap cxCLIWebServiceSoap; public CxWebService(String serverUrl) throws MalformedURLException, AbortException { logger.info("Establishing connection with Checkmarx server at: " + serverUrl); URL serverUrlUrl = new URL(serverUrl); if (serverUrlUrl.getPath().length() > 0) { String message = "Checkmarx server url must not contain path: " + serverUrl; logger.debug(message); throw new AbortException(message); } URL resolverUrl = new URL(serverUrl + CXWSRESOLVER_PATH); logger.debug("Resolver url: " + resolverUrl); CxWSResolver cxWSResolver; try { cxWSResolver = new CxWSResolver(resolverUrl,CXWSRESOLVER_QNAME); } catch (InaccessibleWSDLException e){ logger.error("Failed to resolve Checkmarx webservice url with resolver at: " + resolverUrl); logger.error(e); throw new AbortException("Checkmarx server was not found on url: " + serverUrl); } CxWSResolverSoap cxWSResolverSoap = cxWSResolver.getCxWSResolverSoap(); CxWSResponseDiscovery cxWSResponseDiscovery = cxWSResolverSoap.getWebServiceUrl(CxClientType.CLI,WEBSERVICE_API_VERSION); // TODO: Replace CLI with Jenkins if (!cxWSResponseDiscovery.isIsSuccesfull()) { String message = "Failed to resolve Checkmarx webservice url: \n" + cxWSResponseDiscovery.getErrorMessage(); logger.error(message); throw new AbortException(message); } URL webServiceUrl = new URL(cxWSResponseDiscovery.getServiceURL()); logger.debug("Webservice url: " + webServiceUrl); CxCLIWebService cxCLIWebService = new CxCLIWebService(webServiceUrl,CXCLIWEBSERVICE_QNAME); cxCLIWebServiceSoap = cxCLIWebService.getCxCLIWebServiceSoap(); } public void login(String username, String password) throws AbortException { sessionId=null; Credentials credentials = new Credentials(); credentials.setUser(username); credentials.setPass(password); CxWSResponseLoginData cxWSResponseLoginData = cxCLIWebServiceSoap.login(credentials,LCID); if (!cxWSResponseLoginData.isIsSuccesfull()) { logger.error("Login to Checkmarx server failed:"); logger.error(cxWSResponseLoginData.getErrorMessage()); throw new AbortException(cxWSResponseLoginData.getErrorMessage()); } sessionId = cxWSResponseLoginData.getSessionId(); logger.debug("Login successful, sessionId: " + sessionId); } public CxWSResponseRunID scan(CliScanArgs args) throws AbortException { assert sessionId!=null : "Trying to scan before login"; CxWSResponseRunID cxWSResponseRunID = cxCLIWebServiceSoap.scan(sessionId,args); if (!cxWSResponseRunID.isIsSuccesfull()) { String message = "Submission of sources for scan failed: \n" + cxWSResponseRunID.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseRunID; } private CxWSResponseScanStatus getScanStatus(CxWSResponseRunID cxWSResponseRunID) throws AbortException { assert sessionId!=null : "Trying to get scan status before login"; CxWSResponseScanStatus cxWSResponseScanStatus = cxCLIWebServiceSoap.getStatusOfSingleScan(sessionId,cxWSResponseRunID.getRunId()); if (!cxWSResponseScanStatus.isIsSuccesfull()) { String message = "Error communicating with Checkmarx server: \n" + cxWSResponseScanStatus.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseScanStatus; } public long trackScanProgress(CxWSResponseRunID cxWSResponseRunID) throws AbortException { assert sessionId!=null : "Trying to track scan progress before login"; boolean locReported = false; while (true) { CxWSResponseScanStatus status = this.getScanStatus(cxWSResponseRunID); switch (status.getCurrentStatus()) { // In progress states case WAITING_TO_PROCESS: logger.info("Scan job waiting for processing"); break ; case QUEUED: if (!locReported) { logger.info("Source contains: " + status.getLOC() + " lines of code."); locReported = true; } logger.info("Scan job queued at position: " + status.getQueuePosition()); break ; case UNZIPPING: logger.info("Unzipping: " + status.getCurrentStagePercent() + "% finished"); logger.info("LOC: " + status.getLOC()); logger.info("StageMessage: " + status.getStageMessage()); logger.info("StepMessage: " + status.getStepMessage()); logger.info("StepDetails: " + status.getStepDetails()); break ; case WORKING: logger.info("Scanning: " + status.getStageMessage() + " " + status.getStepDetails() + " (stage: " + status.getCurrentStagePercent() + "%, total: "+ status.getTotalPercent() + "%)"); break ; // End of progress states case FINISHED: logger.info("Scan Finished Successfully - RunID: " + status.getRunId() + " ScanID:" + status.getScanId()); return status.getScanId(); case FAILED: case DELETED: case UNKNOWN: case CANCELED: String message = "Scan " + status.getStageName() + " - RunID: " + status.getRunId() + " ScanID:" + status.getScanId(); logger.info(message); logger.info("Stage Message" + status.getStageMessage()); throw new AbortException(message); } try { Thread.sleep(10*1000); } catch (InterruptedException e) { String err = "Process interrupted while waiting for scan results"; logger.error(err); logger.error(e); throw new AbortException(err); } } } public void retrieveScanReport(long scanId, File reportFile) throws AbortException { assert sessionId!=null : "Trying to retrieve scan report before login"; CxWSReportRequest cxWSReportRequest = new CxWSReportRequest(); cxWSReportRequest.setScanID(scanId); cxWSReportRequest.setType(CxWSReportType.XML); logger.info("Requesting Scan Report Generation"); CxWSCreateReportResponse cxWSCreateReportResponse = cxCLIWebServiceSoap.createScanReport(sessionId,cxWSReportRequest); if (!cxWSCreateReportResponse.isIsSuccesfull()) { String message = "Error requesting scan report generation: " + cxWSCreateReportResponse.getErrorMessage(); logger.error(message); throw new AbortException(message); } // Wait for the report to become ready while (true) { CxWSReportStatusResponse cxWSReportStatusResponse = cxCLIWebServiceSoap.getScanReportStatus(sessionId,cxWSCreateReportResponse.getID()); if (!cxWSReportStatusResponse.isIsSuccesfull()) { String message = "Error retrieving scan report status: " + cxWSReportStatusResponse.getErrorMessage(); logger.error(message); throw new AbortException(message); } if (cxWSReportStatusResponse.isIsFailed()) { String message = "Failed to create scan report"; logger.error("Web method getScanReportStatus returned status response with isFailed field set to true"); logger.error(message); throw new AbortException(message); } if (cxWSReportStatusResponse.isIsReady()) { logger.info("Scan report generated on Checkmarx server"); break; } logger.info("Report generation in progress"); try { Thread.sleep(5*1000); } catch (InterruptedException e) { String err = "Process interrupted while waiting for scan results"; logger.error(err); logger.error(e); throw new AbortException(err); } } CxWSResponseScanResults cxWSResponseScanResults = cxCLIWebServiceSoap.getScanReport(sessionId,cxWSCreateReportResponse.getID()); if (!cxWSResponseScanResults.isIsSuccesfull()) { String message = "Error retrieving scan report: " + cxWSResponseScanResults.getErrorMessage(); logger.error(message); throw new AbortException(message); } // Save results on disk try { FileOutputStream fileOutputStream = new FileOutputStream(reportFile); IOUtils.write(cxWSResponseScanResults.getScanResults(),fileOutputStream); fileOutputStream.close(); } catch (IOException e) { logger.debug(e); String message = "Can't create report file: " + reportFile.getAbsolutePath(); logger.info(message); throw new AbortException(message); } logger.info("Scan report written to: " + reportFile.getAbsolutePath()); } public List<ProjectDisplayData> getProjectsDisplayData() throws AbortException { assert sessionId!=null : "Trying to retrieve projects display data before login"; CxWSResponseProjectsDisplayData cxWSResponseProjectsDisplayData = this.cxCLIWebServiceSoap.getProjectsDisplayData(this.sessionId); if (!cxWSResponseProjectsDisplayData.isIsSuccesfull()) { String message = "Error retrieving projects display data from server: " + cxWSResponseProjectsDisplayData.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseProjectsDisplayData.getProjectList().getProjectDisplayData(); } public List<Preset> getPresets() throws AbortException { assert sessionId!=null : "Trying to retrieve presetes before login"; CxWSResponsePresetList cxWSResponsePresetList = this.cxCLIWebServiceSoap.getPresetList(this.sessionId); if (!cxWSResponsePresetList.isIsSuccesfull()) { String message = "Error retrieving presets from server: " + cxWSResponsePresetList.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponsePresetList.getPresetList().getPreset(); } // Source encoding is called "configuration" in server terms public List<ConfigurationSet> getSourceEncodings() throws AbortException { assert sessionId!=null : "Trying to retrieve configurations before login"; CxWSResponseConfigSetList cxWSResponseConfigSetList = this.cxCLIWebServiceSoap.getConfigurationSetList(sessionId); if (!cxWSResponseConfigSetList.isIsSuccesfull()) { String message = "Error retrieving configurations from server: " + cxWSResponseConfigSetList.getErrorMessage(); logger.error(message); throw new AbortException(message); } return cxWSResponseConfigSetList.getConfigSetList().getConfigurationSet(); } public boolean isLoggedIn() { return this.sessionId!=null; } }
package com.codepine.api.testrail; import com.codepine.api.testrail.internal.BooleanToIntSerializer; import com.codepine.api.testrail.internal.ListToCsvSerializer; import com.codepine.api.testrail.model.Case; import com.codepine.api.testrail.model.CaseField; import com.codepine.api.testrail.model.CaseType; import com.codepine.api.testrail.model.Configuration; import com.codepine.api.testrail.model.Milestone; import com.codepine.api.testrail.model.Plan; import com.codepine.api.testrail.model.Priority; import com.codepine.api.testrail.model.Project; import com.codepine.api.testrail.model.Result; import com.codepine.api.testrail.model.ResultField; import com.codepine.api.testrail.model.Run; import com.codepine.api.testrail.model.Section; import com.codepine.api.testrail.model.Status; import com.codepine.api.testrail.model.Suite; import com.codepine.api.testrail.model.Test; import com.codepine.api.testrail.model.User; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; import static com.google.common.base.Preconditions.checkArgument; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) @Accessors(fluent = true) public class TestRail { @Getter(value = AccessLevel.MODULE) @Accessors(fluent = false) private final TestRailConfig config; public static Builder builder(@NonNull final String endPoint, @NonNull final String username, @NonNull final String password) { return new Builder(endPoint, username, password); } /** * An accessor for creating requests for "Projects". * * @return a request factory */ public Projects projects() { return new Projects(); } /** * An accessor for creating requests for "Cases". * * @return a request factory */ public Cases cases() { return new Cases(); } /** * An accessor for creating requests for "Case Fields". * * @return a request factory */ public CaseFields caseFields() { return new CaseFields(); } /** * An accessor for creating requests for "Case Types". * * @return a request factory */ public CaseTypes caseTypes() { return new CaseTypes(); } /** * An accessor for creating requests for "Configurations". * * @return a request factory */ public Configurations configurations() { return new Configurations(); } /** * An accessor for creating requests for "Sections". * * @return a request factory */ public Sections sections() { return new Sections(); } /** * An accessor for creating requests for "Suites". * * @return a request factory */ public Suites suites() { return new Suites(); } /** * An accessor for creating requests for "Milestones". * * @return a request factory */ public Milestones milestones() { return new Milestones(); } /** * An accessor for creating requests for "Priorities". * * @return a request factory */ public Priorities priorities() { return new Priorities(); } /** * An accessor for creating requests for "Result Fields". * * @return a request factory */ public ResultFields resultFields() { return new ResultFields(); } /** * An accessor for creating requests for "Tests". * * @return a request factory */ public Tests tests() { return new Tests(); } /** * An accessor for creating requests for "Users". * * @return a request factory */ public Users users() { return new Users(); } /** * An accessor for creating requests for "Statuses". * * @return a request factory */ public Statuses statuses() { return new Statuses(); } /** * An accessor for creating requests for "Runs". * * @return a request factory */ public Runs runs() { return new Runs(); } /** * An accessor for creating requests for "Plans". * * @return a request factory */ public Plans plans() { return new Plans(); } /** * An accessor for creating requests for "Results". * * @return a request factory */ public Results results() { return new Results(); } /** * Builder for {@code TestRail}. */ public static class Builder { private static final String DEFAULT_BASE_API_PATH = "index.php?/api/v2/"; private final String endPoint; private final String username; private final String password; private String apiPath; private String applicationName; private Builder(final String endPoint, final String username, final String password) { String sanitizedEndPoint = endPoint.trim(); if (!sanitizedEndPoint.endsWith("/")) { sanitizedEndPoint = sanitizedEndPoint + "/"; } this.endPoint = sanitizedEndPoint; this.username = username; this.password = password; apiPath = DEFAULT_BASE_API_PATH; } /** * Set the URL path of your TestRail API. Useful to override the default API path of standard TestRail deployments. * * @param apiPath the URL path of your TestRail API * @return this for chaining * @throws NullPointerException if apiPath is null */ public Builder apiPath(@NonNull final String apiPath) { String sanitizedApiPath = apiPath.trim(); if (sanitizedApiPath.startsWith("/")) { sanitizedApiPath = sanitizedApiPath.substring(1); } if (!sanitizedApiPath.endsWith("/")) { sanitizedApiPath = sanitizedApiPath + "/"; } this.apiPath = sanitizedApiPath; return this; } /** * Set the name of the application which will communicate with TestRail. * * @param applicationName name of the application * @return this for chaining * @throws NullPointerException if applicationName is null */ public Builder applicationName(@NonNull final String applicationName) { this.applicationName = applicationName; return this; } /** * Build an instance of {@code TestRail}. * * @return a new instance */ public TestRail build() { return new TestRail(new TestRailConfig(endPoint + apiPath, username, password, applicationName)); } } /** * Request factories for "Projects". */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class Projects { public Get get(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new Get(projectId); } /** * Returns the list of available projects. * * @return the request */ public List list() { return new List(); } /** * Creates a new project. * * @param project the project to be added * @return the request * @throws java.lang.NullPointerException if project is null */ public Add add(@NonNull Project project) { return new Add(project); } /** * Updates an existing project. Partial updates are supported, i.e. you can set and update specific fields only. * * @param project the project to be updated * @return the request * @throws java.lang.NullPointerException if project is null */ public Update update(@NonNull Project project) { return new Update(project); } public Delete delete(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new Delete(projectId); } public class Get extends Request<Project> { private static final String REST_PATH = "get_project/"; private Get(int projectId) { super(config, Method.GET, REST_PATH + projectId, Project.class); } } @Getter @Setter public class List extends Request<java.util.List<Project>> { private static final String REST_PATH = "get_projects"; @JsonView(List.class) @JsonSerialize(using = BooleanToIntSerializer.class) private Boolean isCompleted; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<Project>>() { }); } } public class Add extends Request<Project> { private static final String REST_PATH = "add_project"; private final Project project; private Add(@NonNull Project project) { super(config, Method.POST, REST_PATH, Project.class); this.project = project; } @Override protected Object getContent() { return project; } } public class Update extends Request<Project> { private static final String REST_PATH = "update_project/"; private final Project project; private Update(@NonNull Project project) { super(config, Method.POST, REST_PATH + project.getId(), Project.class); this.project = project; } @Override protected Object getContent() { return project; } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_project/"; private Delete(int projectId) { super(config, Method.POST, REST_PATH + projectId, Void.class); } } } /** * Request factories for "Cases". */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class Cases { public Get get(final int testCaseId, @NonNull java.util.List<CaseField> caseFields) { checkArgument(testCaseId > 0, "testCaseId should be positive"); return new Get(testCaseId, caseFields); } public List list(final int projectId, @NonNull java.util.List<CaseField> caseFields) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId, caseFields); } public List list(final int projectId, final int suiteId, @NonNull java.util.List<CaseField> caseFields) { checkArgument(projectId > 0, "projectId should be positive"); checkArgument(suiteId > 0, "suiteId should be positive"); return new List(projectId, suiteId, caseFields); } public Add add(final int sectionId, @NonNull Case testCase, @NonNull java.util.List<CaseField> caseFields) { checkArgument(sectionId > 0, "projectId should be positive"); return new Add(sectionId, testCase, caseFields); } /** * Updates an existing test case. Partial updates are supported, i.e. you can set and update specific fields only. * <p>The custom case fields configured in TestRail can be fetched using {@link CaseFields#list()} request. * The reason for not fetching this during execution of this request is to allow you to cache the list on your end to prevent an extra call on every execution.</p> * * @param testCase the test case to be updated * @param caseFields the custom case fields configured in TestRail to get type information for custom fields in the test case returned * @return the request * @throws java.lang.NullPointerException if any argument is null */ public Update update(@NonNull Case testCase, @NonNull java.util.List<CaseField> caseFields) { return new Update(testCase, caseFields); } public Delete delete(final int testCaseId) { checkArgument(testCaseId > 0, "testCaseId should be positive"); return new Delete(testCaseId); } public class Get extends Request<Case> { private static final String REST_PATH = "get_case/"; private final java.util.List<CaseField> caseFields; private Get(int testCaseId, java.util.List<CaseField> caseFields) { super(config, Method.GET, REST_PATH + testCaseId, Case.class); this.caseFields = caseFields; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Case>> { private static final String REST_PATH = "get_cases/%s&suite_id=%s"; private final java.util.List<CaseField> caseFields; @JsonView(List.class) private Integer sectionId; @JsonView(List.class) private Date createdAfter; @JsonView(List.class) private Date createdBefore; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> createdBy; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> milestoneId; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> priorityId; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> typeId; @JsonView(List.class) private Date updatedAfter; @JsonView(List.class) private Date updatedBefore; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> updatedBy; private List(int projectId, java.util.List<CaseField> caseFields) { super(config, Method.GET, String.format(REST_PATH, projectId, ""), new TypeReference<java.util.List<Case>>() { }); this.caseFields = caseFields; } private List(int projectId, int suiteId, java.util.List<CaseField> caseFields) { super(config, Method.GET, String.format(REST_PATH, projectId, suiteId), new TypeReference<java.util.List<Case>>() { }); this.caseFields = caseFields; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } public class Add extends Request<Case> { private static final String REST_PATH = "add_case/"; private final Case testCase; private final java.util.List<CaseField> caseFields; private Add(int sectionId, Case testCase, java.util.List<CaseField> caseFields) { super(config, Method.POST, REST_PATH + sectionId, Case.class); this.testCase = testCase; this.caseFields = caseFields; } @Override protected Object getContent() { return testCase; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } public class Update extends Request<Case> { private static final String REST_PATH = "update_case/"; private final Case testCase; private final java.util.List<CaseField> caseFields; private Update(Case testCase, java.util.List<CaseField> caseFields) { super(config, Method.POST, REST_PATH + testCase.getId(), Case.class); this.testCase = testCase; this.caseFields = caseFields; } @Override protected Object getContent() { return testCase; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_case/"; private Delete(int testCaseId) { super(config, Method.POST, REST_PATH + testCaseId, Void.class); } } } /** * Request factories for "Case Fields". */ @NoArgsConstructor public class CaseFields { /** * Returns a list of available test case custom fields. * * @return the request */ public List list() { return new List(); } public class List extends Request<java.util.List<CaseField>> { private static final String REST_PATH = "get_case_fields"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<CaseField>>() { }); } } } /** * Request factories for "Case Types". */ @NoArgsConstructor public class CaseTypes { /** * Returns a list of available case types. * * @return the request */ public List list() { return new List(); } public class List extends Request<java.util.List<CaseType>> { private static final String REST_PATH = "get_case_types"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<CaseType>>() { }); } } } /** * Request factories for "Configurations". */ @NoArgsConstructor public class Configurations { public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public class List extends Request<java.util.List<Configuration>> { private static final String REST_PATH = "get_configs/"; private List(int projectId) { super(config, Method.GET, REST_PATH + projectId, new TypeReference<java.util.List<Configuration>>() { }); } } } /** * Request factories for "Milestones". */ @NoArgsConstructor public class Milestones { public Get get(final int milestoneId) { checkArgument(milestoneId > 0, "milestoneId should be positive"); return new Get(milestoneId); } public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public Add add(final int projectId, @NonNull Milestone milestone) { checkArgument(projectId > 0, "projectId should be positive"); return new Add(projectId, milestone); } /** * Updates an existing milestone. Partial updates are supported, i.e. you can set and update specific fields only. * * @param milestone the milestone to be updated * @return the request * @throws java.lang.NullPointerException if milestone is null */ public Update update(@NonNull Milestone milestone) { return new Update(milestone); } public Delete delete(final int milestoneId) { checkArgument(milestoneId > 0, "milestoneId should be positive"); return new Delete(milestoneId); } public class Get extends Request<Milestone> { private static final String REST_PATH = "get_milestone/"; private Get(int milestoneId) { super(config, Method.GET, REST_PATH + milestoneId, Milestone.class); } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Milestone>> { private static final String REST_PATH = "get_milestones/"; @JsonView(List.class) @JsonSerialize(using = BooleanToIntSerializer.class) private Boolean isCompleted; private List(int projectId) { super(config, Method.GET, REST_PATH + projectId, new TypeReference<java.util.List<Milestone>>() { }); } } public class Add extends Request<Milestone> { private static final String REST_PATH = "add_milestone/"; private final Milestone milestone; private Add(int projectId, Milestone milestone) { super(config, Method.POST, REST_PATH + projectId, Milestone.class); this.milestone = milestone; } @Override protected Object getContent() { return milestone; } } public class Update extends Request<Milestone> { private static final String REST_PATH = "update_milestone/"; private final Milestone milestone; private Update(Milestone milestone) { super(config, Method.POST, REST_PATH + milestone.getId(), Milestone.class); this.milestone = milestone; } @Override protected Object getContent() { return milestone; } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_milestone/"; private Delete(int milestoneId) { super(config, Method.POST, REST_PATH + milestoneId, Void.class); } } } /** * Request factories for "Priorities". */ @NoArgsConstructor public class Priorities { /** * Returns a list of available priorities. * * @return the request */ public List list() { return new List(); } public class List extends Request<java.util.List<Priority>> { private static final String REST_PATH = "get_priorities"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<Priority>>() { }); } } } /** * Request factories for "Plans". */ @NoArgsConstructor public class Plans { public Get get(final int planId) { checkArgument(planId > 0, "planId should be positive"); return new Get(planId); } public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public Add add(final int projectId, @NonNull Plan plan) { checkArgument(projectId > 0, "projectId should be positive"); return new Add(projectId, plan); } /** * Updates an existing test plan. Partial updates are supported, i.e. you can set and update specific fields only. * * @param plan the test plan to be updated * @return the request * @throws java.lang.NullPointerException if plan is null */ public Update update(@NonNull Plan plan) { return new Update(plan); } public Close close(final int planId) { checkArgument(planId > 0, "planId should be positive"); return new Close(planId); } public Delete delete(final int planId) { checkArgument(planId > 0, "planId should be positive"); return new Delete(planId); } public AddEntry addEntry(final int planId, @NonNull Plan.Entry entry) { checkArgument(planId > 0, "planId should be positive"); return new AddEntry(planId, entry); } public UpdateEntry updateEntry(final int planId, @NonNull Plan.Entry entry) { checkArgument(planId > 0, "planId should be positive"); return new UpdateEntry(planId, entry); } public DeleteEntry deleteEntry(final int planId, @NonNull final String entryId) { checkArgument(planId > 0, "planId should be positive"); return new DeleteEntry(planId, entryId); } public class Get extends Request<Plan> { private static final String REST_PATH = "get_plan/"; private Get(int planId) { super(config, Method.GET, REST_PATH + planId, Plan.class); } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Plan>> { private static final String REST_PATH = "get_plans/"; @JsonView(List.class) private Date createdAfter; @JsonView(List.class) private Date createdBefore; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> createdBy; @JsonView(List.class) @JsonSerialize(using = BooleanToIntSerializer.class) private Boolean isCompleted; @JsonView(List.class) private Integer limit; @JsonView(List.class) private Integer offset; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> milestoneId; private List(int projectId) { super(config, Method.GET, REST_PATH + projectId, new TypeReference<java.util.List<Plan>>() { }); } } public class Add extends Request<Plan> { private static final String REST_PATH = "add_plan/"; private final Plan plan; private Add(int projectId, Plan plan) { super(config, Method.POST, REST_PATH + projectId, Plan.class); this.plan = plan; } @Override protected Object getContent() { return plan; } } public class AddEntry extends Request<Plan.Entry> { private static final String REST_PATH = "add_plan_entry/"; private final Plan.Entry entry; private AddEntry(int planId, Plan.Entry entry) { super(config, Method.POST, REST_PATH + planId, Plan.Entry.class); this.entry = entry; } @Override protected Object getContent() { return entry; } } public class Update extends Request<Plan> { private static final String REST_PATH = "update_plan/"; private final Plan plan; private Update(Plan plan) { super(config, Method.POST, REST_PATH + plan.getId(), Plan.class); this.plan = plan; } @Override protected Object getContent() { return plan; } } public class UpdateEntry extends Request<Plan.Entry> { private static final String REST_PATH = "update_plan_entry/%s/%s"; private final Plan.Entry entry; private UpdateEntry(int planId, Plan.Entry entry) { super(config, Method.POST, String.format(REST_PATH, planId, entry.getId()), Plan.Entry.class); this.entry = entry; } @Override protected Object getContent() { return entry; } } public class Close extends Request<Plan> { private static final String REST_PATH = "close_plan/"; private Close(int planId) { super(config, Method.POST, REST_PATH + planId, Plan.class); } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_plan/"; private Delete(int planId) { super(config, Method.POST, REST_PATH + planId, Void.class); } } public class DeleteEntry extends Request<Void> { private static final String REST_PATH = "delete_plan_entry/%s/%s"; private DeleteEntry(int planId, String entryId) { super(config, Method.POST, String.format(REST_PATH, planId, entryId), Void.class); } } } /** * Request factories for "Results". */ @NoArgsConstructor public class Results { public List list(final int testId, @NonNull java.util.List<ResultField> resultFields) { checkArgument(testId > 0, "testId should be positive"); return new List(testId, resultFields); } public ListForCase listForCase(final int runId, final int testCaseId, @NonNull java.util.List<ResultField> resultFields) { checkArgument(runId > 0, "runId should be positive"); checkArgument(testCaseId > 0, "testCaseId should be positive"); return new ListForCase(runId, testCaseId, resultFields); } public ListForRun listForRun(final int runId, @NonNull java.util.List<ResultField> resultFields) { checkArgument(runId > 0, "runId should be positive"); return new ListForRun(runId, resultFields); } public Add add(final int testId, @NonNull Result result, @NonNull java.util.List<ResultField> resultFields) { checkArgument(testId > 0, "testId should be positive"); return new Add(testId, result, resultFields); } public AddForCase addForCase(final int runId, final int testCaseId, @NonNull Result result, @NonNull java.util.List<ResultField> resultFields) { checkArgument(runId > 0, "runId should be positive"); checkArgument(testCaseId > 0, "testCaseId should be positive"); return new AddForCase(runId, testCaseId, result, resultFields); } public AddList add(final int runId, @NonNull java.util.List<Result> results, @NonNull java.util.List<ResultField> resultFields) { checkArgument(runId > 0, "runId should be positive"); checkArgument(!results.isEmpty(), "results cannot be empty"); return new AddList(runId, results, resultFields); } public AddListForCases addForCases(final int runId, @NonNull java.util.List<Result> results, @NonNull java.util.List<ResultField> resultFields) { checkArgument(runId > 0, "runId should be positive"); checkArgument(!results.isEmpty(), "results cannot be empty"); return new AddListForCases(runId, results, resultFields); } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Result>> { private static final String REST_PATH = "get_results/"; private final java.util.List<ResultField> resultFields; @JsonView(List.class) private Integer limit; @JsonView(List.class) private Integer offset; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> statusId; private List(int testId, java.util.List<ResultField> resultFields) { super(config, Method.GET, REST_PATH + testId, new TypeReference<java.util.List<Result>>() { }); this.resultFields = resultFields; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } @Getter @Setter @Accessors(fluent = true) public class ListForRun extends Request<java.util.List<Result>> { private static final String REST_PATH = "get_results_for_run/"; private final java.util.List<ResultField> resultFields; @JsonView(ListForRun.class) private Date createdAfter; @JsonView(ListForRun.class) private Date createdBefore; @JsonView(ListForRun.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> createdBy; @JsonView(ListForRun.class) private Integer limit; @JsonView(ListForRun.class) private Integer offset; @JsonView(ListForRun.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> statusId; private ListForRun(int runId, java.util.List<ResultField> resultFields) { super(config, Method.GET, REST_PATH + runId, new TypeReference<java.util.List<Result>>() { }); this.resultFields = resultFields; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } @Getter @Setter @Accessors(fluent = true) public class ListForCase extends Request<java.util.List<Result>> { private static final String REST_PATH = "get_results_for_case/"; private final java.util.List<ResultField> resultFields; @JsonView(ListForCase.class) private Integer limit; @JsonView(ListForCase.class) private Integer offset; @JsonView(ListForCase.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> statusId; private ListForCase(int runId, int testCaseId, java.util.List<ResultField> resultFields) { super(config, Method.GET, REST_PATH + runId + "/" + testCaseId, new TypeReference<java.util.List<Result>>() { }); this.resultFields = resultFields; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } public class Add extends Request<Result> { private static final String REST_PATH = "add_result/"; private final Result result; private final java.util.List<ResultField> resultFields; private Add(int testId, Result result, java.util.List<ResultField> resultFields) { super(config, Method.POST, REST_PATH + testId, Result.class); this.result = result; this.resultFields = resultFields; } @Override protected Object getContent() { return result; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } public class AddForCase extends Request<Result> { private static final String REST_PATH = "add_result_for_case/"; private final Result result; private final java.util.List<ResultField> resultFields; private AddForCase(int runId, int testCaseId, Result result, java.util.List<ResultField> resultFields) { super(config, Method.POST, REST_PATH + runId + "/" + testCaseId, Result.class); this.result = result; this.resultFields = resultFields; } @Override protected Object getContent() { return result; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } public class AddList extends Request<java.util.List<Result>> { private static final String REST_PATH = "add_results/"; private final Result.List results; private final java.util.List<ResultField> resultFields; private AddList(final int runId, java.util.List<Result> results, java.util.List<ResultField> resultFields) { super(config, Method.POST, REST_PATH + runId, new TypeReference<java.util.List<Result>>() { }); this.results = new Result.List(results); this.resultFields = resultFields; } @Override protected Object getContent() { return results; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } public class AddListForCases extends Request<java.util.List<Result>> { private static final String REST_PATH = "add_results_for_cases/"; private final Result.List results; private final java.util.List<ResultField> resultFields; private AddListForCases(int runId, java.util.List<Result> results, java.util.List<ResultField> resultFields) { super(config, Method.POST, REST_PATH + runId, new TypeReference<java.util.List<Result>>() { }); this.results = new Result.List(results); this.resultFields = resultFields; } @Override protected Object getContent() { return results; } @Override protected Object getSupplementForDeserialization() { return resultFields; } } } /** * Request factories for "Result Fields". */ @NoArgsConstructor public class ResultFields { /** * Returns a list of available test result custom fields. * * @return the request */ public List list() { return new List(); } public class List extends Request<java.util.List<ResultField>> { private static final String REST_PATH = "get_result_fields"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<ResultField>>() { }); } } } /** * Request factories for "Runs". */ @NoArgsConstructor public class Runs { public Get get(final int runId) { checkArgument(runId > 0, "runId should be positive"); return new Get(runId); } public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public Add add(final int projectId, @NonNull Run run) { checkArgument(projectId > 0, "projectId should be positive"); return new Add(projectId, run); } /** * Updates an existing test run. Partial updates are supported, i.e. you can set and update specific fields only. * * @param run the test run to be updated * @return the request * @throws java.lang.NullPointerException if run is null */ public Update update(@NonNull Run run) { return new Update(run); } public Close close(final int runId) { checkArgument(runId > 0, "runId should be positive"); return new Close(runId); } public Delete delete(final int runId) { checkArgument(runId > 0, "runId should be positive"); return new Delete(runId); } public class Get extends Request<Run> { private static final String REST_PATH = "get_run/"; private Get(int runId) { super(config, Method.GET, REST_PATH + runId, Run.class); } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Run>> { private static final String REST_PATH = "get_runs/"; @JsonView(List.class) private Date createdAfter; @JsonView(List.class) private Date createdBefore; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> createdBy; @JsonView(List.class) @JsonSerialize(using = BooleanToIntSerializer.class) private Boolean isCompleted; @JsonView(List.class) private Integer limit; @JsonView(List.class) private Integer offset; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> milestoneId; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> suiteId; private List(int projectId) { super(config, Method.GET, REST_PATH + projectId, new TypeReference<java.util.List<Run>>() { }); } } public class Add extends Request<Run> { private static final String REST_PATH = "add_run/"; private final Run run; private Add(int projectId, Run run) { super(config, Method.POST, REST_PATH + projectId, Run.class); this.run = run; } @Override protected Object getContent() { return run; } } public class Update extends Request<Run> { private static final String REST_PATH = "update_run/"; private final Run run; private Update(Run run) { super(config, Method.POST, REST_PATH + run.getId(), Run.class); this.run = run; } @Override protected Object getContent() { return run; } } public class Close extends Request<Run> { private static final String REST_PATH = "close_run/"; private Close(int runId) { super(config, Method.POST, REST_PATH + runId, Run.class); } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_run/"; private Delete(int runId) { super(config, Method.POST, REST_PATH + runId, Void.class); } } } /** * Request factories for "Sections". */ @NoArgsConstructor public class Sections { public Get get(final int sectionId) { checkArgument(sectionId > 0, "sectionId should be positive"); return new Get(sectionId); } public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public List list(final int projectId, final int suiteId) { checkArgument(projectId > 0, "projectId should be positive"); checkArgument(suiteId > 0, "suiteId should be positive"); return new List(projectId, suiteId); } /** * Creates a new section. * * @param projectId the ID of the project to add the section to * @param section the section to be added * @return the request * @throws java.lang.NullPointerException if section is null */ public Add add(final int projectId, @NonNull Section section) { checkArgument(projectId > 0, "projectId should be positive"); return new Add(projectId, section); } /** * Updates an existing section. Partial updates are supported, i.e. you can set and update specific fields only. * * @param section the section to be updated * @return the request * @throws java.lang.NullPointerException if section is null */ public Update update(@NonNull Section section) { return new Update(section); } public Delete delete(final int sectionId) { checkArgument(sectionId > 0, "sectionId should be positive"); return new Delete(sectionId); } public class Get extends Request<Section> { private static final String REST_PATH = "get_section/"; private Get(int sectionId) { super(config, Method.GET, REST_PATH + sectionId, Section.class); } } public class List extends Request<java.util.List<Section>> { private static final String REST_PATH = "get_sections/%s&suite_id=%s"; private List(int projectId) { super(config, Method.GET, String.format(REST_PATH, projectId, ""), new TypeReference<java.util.List<Section>>() { }); } private List(int projectId, int suiteId) { super(config, Method.GET, String.format(REST_PATH, projectId, suiteId), new TypeReference<java.util.List<Section>>() { }); } } public class Add extends Request<Section> { private static final String REST_PATH = "add_section/"; private final Section section; private Add(int projectId, Section section) { super(config, Method.POST, REST_PATH + projectId, Section.class); this.section = section; } @Override protected Object getContent() { return section; } } public class Update extends Request<Section> { private static final String REST_PATH = "update_section/"; private final Section section; private Update(Section section) { super(config, Method.POST, REST_PATH + section.getId(), Section.class); this.section = section; } @Override protected Object getContent() { return section; } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_section/"; private Delete(int sectionId) { super(config, Method.POST, REST_PATH + sectionId, Void.class); } } } /** * Request factories for "Statuses". */ @NoArgsConstructor public class Statuses { /** * Returns a list of available test statuses. * * @return the request */ public List list() { return new List(); } public class List extends Request<java.util.List<Status>> { private static final String REST_PATH = "get_statuses"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<Status>>() { }); } } } /** * Request factories for "Suites". */ @NoArgsConstructor public class Suites { public Get get(final int suiteId) { checkArgument(suiteId > 0, "suiteId should be positive"); return new Get(suiteId); } public List list(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new List(projectId); } public Add add(final int projectId, @NonNull Suite suite) { checkArgument(projectId > 0, "projectId should be positive"); return new Add(projectId, suite); } /** * Updates an existing test suite. Partial updates are supported, i.e. you can set and update specific fields only. * * @param suite the test suite to be updated * @return the request * @throws java.lang.NullPointerException if suite is null */ public Update update(@NonNull Suite suite) { return new Update(suite); } public Delete delete(final int suiteId) { checkArgument(suiteId > 0, "suiteId should be positive"); return new Delete(suiteId); } public class Get extends Request<Suite> { private static final String REST_PATH = "get_suite/"; private Get(int suiteId) { super(config, Method.GET, REST_PATH + suiteId, Suite.class); } } public class List extends Request<java.util.List<Suite>> { private static final String REST_PATH = "get_suites/"; private List(int projectId) { super(config, Method.GET, REST_PATH + projectId, new TypeReference<java.util.List<Suite>>() { }); } } public class Add extends Request<Suite> { private static final String REST_PATH = "add_suite/"; private final Suite suite; private Add(final int projectId, Suite suite) { super(config, Method.POST, REST_PATH + projectId, Suite.class); this.suite = suite; } @Override protected Object getContent() { return suite; } } public class Update extends Request<Suite> { private static final String REST_PATH = "update_suite/"; private final Suite suite; private Update(Suite suite) { super(config, Method.POST, REST_PATH + suite.getId(), Suite.class); this.suite = suite; } @Override protected Object getContent() { return suite; } } public class Delete extends Request<Void> { private static final String REST_PATH = "delete_suite/"; private Delete(int suiteId) { super(config, Method.POST, REST_PATH + suiteId, Void.class); } } } /** * Request factories for "Tests". */ @NoArgsConstructor public class Tests { public Get get(final int testId) { checkArgument(testId > 0, "testId should be positive"); return new Get(testId); } public List list(final int runId) { checkArgument(runId > 0, "runId should be positive"); return new List(runId); } public class Get extends Request<Test> { private static final String REST_PATH = "get_test/"; private Get(int testId) { super(config, Method.GET, REST_PATH + testId, Test.class); } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Test>> { private static final String REST_PATH = "get_tests/"; @JsonView(List.class) @JsonSerialize(using = ListToCsvSerializer.class) private java.util.List<Integer> statusId; private List(int runId) { super(config, Method.GET, REST_PATH + runId, new TypeReference<java.util.List<Test>>() { }); } } } /** * Request factories for "Users". */ @NoArgsConstructor public class Users { public Get get(final int userId) { checkArgument(userId > 0, "userId should be positive"); return new Get(userId); } public GetByEmail getByEmail(@NonNull String email) { email = email.trim(); checkArgument(!email.isEmpty(), "email cannot be empty"); return new GetByEmail(email); } /** * Returns a list of users. * * @return the request */ public List list() { return new List(); } public class Get extends Request<User> { private static final String REST_PATH = "get_user/"; private Get(int userId) { super(config, Method.GET, REST_PATH + userId, User.class); } } public class GetByEmail extends Request<User> { private static final String REST_PATH = "get_user_by_email&email="; private GetByEmail(String email) { super(config, Method.GET, REST_PATH + email, User.class); } } public class List extends Request<java.util.List<User>> { private static final String REST_PATH = "get_users"; private List() { super(config, Method.GET, REST_PATH, new TypeReference<java.util.List<User>>() { }); } } } }
package com.conveyal.gtfs.loader; import com.conveyal.gtfs.storage.StorageException; import java.sql.JDBCType; import java.sql.PreparedStatement; import java.sql.SQLType; /** * A GTFS date in the numeric format YYYYMMDD */ public class DateField extends Field { public DateField (String name, Requirement requirement) { super(name, requirement); } private int validate (String string) { if (string.length() != 8) { throw new StorageException("Date field should be exactly 8 characters long."); } int year = Integer.parseInt(string.substring(0, 4)); int month = Integer.parseInt(string.substring(4, 6)); int day = Integer.parseInt(string.substring(6, 8)); if (year < 2000 || year > 2100) { throw new StorageException("Date year out of range 2000-2100: " + year); } if (month < 1 || month > 12) { throw new StorageException("Date month out of range 1-12: " + month); } if (day < 1 || day > 31) { throw new StorageException("Date day out of range 1-31: " + day); } return Integer.parseInt(string); } @Override public void setParameter (PreparedStatement preparedStatement, int oneBasedIndex, String string) { try { preparedStatement.setInt(oneBasedIndex, validate(string)); } catch (Exception ex) { throw new StorageException(ex); } } @Override public String validateAndConvert (String string) { return Integer.toString(validate(string)); } @Override public SQLType getSqlType () { return JDBCType.INTEGER; } }
package com.couchbase.lite.support; import com.couchbase.lite.util.Log; public class Version { public static final String SYNC_PROTOCOL_VERSION = "1.2"; public static final String VERSION; private static final String VERSION_NAME="%VERSION_NAME%"; // replaced during build process private static final String VERSION_CODE="%VERSION_CODE%"; // replaced during build process private static final String COMMIT_HASH="%COMMIT_HASH%"; // replaced during build process static { int versCode = getVersionCode(); if (versCode == -1) { VERSION = String.format("%s-%s", getVersionName(), getVersionCode()); } else{ VERSION = String.format("%s", getVersionName()); } } public static String getVersionName() { if (VERSION_NAME.contains("VERSION_NAME")) { return "devbuild"; } return VERSION_NAME; } public static int getVersionCode() { if (VERSION_CODE.contains("VERSION_CODE")) { return 0; } // VERSION_CODE should be empty string if it is release build if(VERSION_CODE == null || VERSION_CODE.isEmpty()) { return 0; } try { Integer.parseInt(VERSION_CODE); } catch (NumberFormatException e) { Log.w(Log.TAG, "Cannot parse version code: %s", VERSION_CODE); return 0; } return -1; } public static String getVersion() { return VERSION; } public static String getCommitHash(){ if (COMMIT_HASH.contains("COMMIT_HASH")) { return "devbuild"; } return COMMIT_HASH; } }
package com.ctci.treesandgraphs; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; /** * You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second * project is dependent on the first project). All of a project's dependencies must be built before the project is. Find * a build order that will allow the projects to be built. If there is no valid build order, return an error. * EXAMPLE * Input: projects: a, b, c, d, e, f and dependencies: (a, d), (f, b), (b, d), (f, a), (d, c) * Output: f, e, a, b, d, c * * @author rampatra * @since 2019-02-21 */ public class BuildOrder { private class Project { String name; Set<Project> dependencies = new HashSet<>(); Project(String name) { this.name = name; } @Override public String toString() { return name; } } private final Map<String, Project> projects = new HashMap<>(); private void addProjects(Stream<String> projectNames) { projectNames.forEach(name -> projects.put(name, new Project(name))); } /** * Adds a directed edge from {@code projectName2} to {@code ProjectName1}. This means {@code projectName2} is * dependent on {@code projectName1}, i.e, {@code projectName1} has to be built before {@code projectName2}. * * @param projectName1 name of project 1 * @param projectName2 name of project 2 */ private void addDependency(String projectName1, String projectName2) { Project p1 = projects.get(projectName1); Project p2 = projects.get(projectName2); if (p1 == null) { p1 = new Project(projectName1); projects.put(projectName1, p1); } if (p2 == null) { p2 = new Project(projectName2); projects.put(projectName2, p2); } p2.dependencies.add(p1); } /** * Determines the order in which the projects need to be built. * Time complexity: TODO * * @return a list of projects in the order they should be built, the first project should be built first and so on. */ private List<Project> getBuildOrder() { Map<String, Project> projectsBuilt = new LinkedHashMap<>(); // linked hashmap is needed to maintain the insertion order while (projectsBuilt.size() != projects.size()) { // find the projects which are not dependent on any project Set<Project> nextProjectsToBuild = getProjectsWithNoDependencies(projectsBuilt); // if there are no further independent projects to build, then we can't proceed further if (nextProjectsToBuild.size() == 0) { throw new IllegalStateException("Error: Projects can't be built."); } nextProjectsToBuild.forEach(p -> projectsBuilt.put(p.name, p)); // once a project is built, remove the dependencies from all other projects dependent on this removeDependency(nextProjectsToBuild); } return new ArrayList<>(projectsBuilt.values()); } private Set<Project> getProjectsWithNoDependencies(Map<String, Project> alreadyBuildProjects) { Set<Project> unBuiltProjectsWithZeroDependencies = new HashSet<>(); for (Map.Entry<String, Project> entry : projects.entrySet()) { if (entry.getValue().dependencies.size() == 0 && alreadyBuildProjects.get(entry.getKey()) == null) { unBuiltProjectsWithZeroDependencies.add(entry.getValue()); } } return unBuiltProjectsWithZeroDependencies; } private void removeDependency(Set<Project> newlyBuiltProjects) { projects.forEach((n, p) -> p.dependencies.removeAll(newlyBuiltProjects)); } public static void main(String[] args) { BuildOrder buildOrder = new BuildOrder(); buildOrder.addProjects(Stream.of("a", "b", "c", "d", "e", "f")); buildOrder.addDependency("a", "d"); buildOrder.addDependency("f", "b"); buildOrder.addDependency("b", "d"); buildOrder.addDependency("f", "a"); buildOrder.addDependency("d", "c"); System.out.println(buildOrder.getBuildOrder()); // test case 2 buildOrder = new BuildOrder(); buildOrder.addProjects(Stream.of("a", "b", "c", "d", "e", "f", "g")); buildOrder.addDependency("d", "g"); buildOrder.addDependency("f", "b"); buildOrder.addDependency("f", "c"); buildOrder.addDependency("f", "a"); buildOrder.addDependency("c", "a"); buildOrder.addDependency("b", "a"); buildOrder.addDependency("b", "e"); buildOrder.addDependency("a", "e"); System.out.println(buildOrder.getBuildOrder()); } }
package com.dteoh.treasuremap; import java.util.LinkedList; import java.util.List; import org.jdesktop.application.ResourceMap; /** * Convenience class for creating {@link ResourceMap}s. * * @author Douglas Teoh * */ public final class ResourceMaps { /** * Creates a {@link ResourceMap} containing all resources for the given * class. * * Equivalent to calling: * <p> * <code>new ResourceMap(null, c.getClassLoader(), c.getPackage().getName() * + ".resources." + c.getSimpleName());</code> * </p> * * @param c * Class to create the ResourceMap for. * @return The newly created ResourceMap. */ public static ResourceMap create(final Class<?> c) { if (c == null) { throw new NullPointerException("Class cannot be null."); } ResourceMap rmap = new ResourceMap(null, c.getClassLoader(), c .getPackage().getName() + ".resources." + c.getSimpleName()); return rmap; } /** * Creates a {@link ResourceMap} containing all resources for the given * class as well as the parent resource map. * * Equivalent to calling: * <p> * <code>new ResourceMap(parent, c.getClassLoader(), c.getPackage().getName() * + ".resources." + c.getSimpleName());</code> * </p> * * @param parent * Parent resource map. * @param c * Class to create the ResourceMap for. * @return The newly created ResourceMap. */ public static ResourceMap create(final ResourceMap parent, final Class<?> c) { if (c == null) { throw new NullPointerException("Class cannot be null."); } ResourceMap rmap = new ResourceMap(parent, c.getClassLoader(), c .getPackage().getName() + ".resources." + c.getSimpleName()); return rmap; } /** * Create a ResourceMap that includes all resources for the given classes. * * @param c * Classes to create the ResourceMap for. * @return The newly created ResourceMap. */ public static ResourceMap createMulti(final Class<?>... c) { return createMulti(null, c); } /** * Create a ResourceMap that includes all resources for the given classes as * well as the parent resource map. * * @param parent * Parent resource map. * @param c * Classes to create the ResourceMap for. * @return The newly created ResourceMap. */ public static ResourceMap createMulti(final ResourceMap parent, final Class<?>... c) { if (c == null || c.length == 0) { throw new NullPointerException("Classes cannot be null."); } ClassLoader loader = null; List<String> bundleNames = new LinkedList<String>(); for (Class<?> bundle : c) { if (c == null) { continue; } loader = bundle.getClassLoader(); bundleNames.add(bundle.getPackage().getName() + ".resources." + bundle.getSimpleName()); } ResourceMap rmap = new ResourceMap(parent, loader, bundleNames); return rmap; } }
package com.edify.config; import com.jolbox.bonecp.BoneCPDataSource; import liquibase.integration.spring.SpringLiquibase; import org.hibernate.ejb.HibernatePersistence; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.orm.jpa.JpaDialect; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author jarias * @since 9/2/12 11:25 AM */ @Configuration @ComponentScan(basePackages = "com.edify", excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class)) @ImportResource({"classpath:META-INF/spring/applicationContext-security.xml", "classpath:META-INF/spring/applicationContext-repositories.xml"}) @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) public class ApplicationConfig { @Value("${DATABASE_URL}") private String databaseUrl; @Value("${DATABASE_DRIVER_CLASSNAME}") private String databaseDriverClassname; @Value("${DATABASE_USERNAME}") private String databaseUsername; @Value("${DATABASE_PASSWORD}") private String databasePassword; @Value("${HIBERNATE_DIALECT}") private String hibernateDialect; //DataSource properties @Value("${DATASOURCE_BONECP_IDLE_CONNECTION_TEST_PERIOD_IN_MINUTES}") private Integer idleConnectionTestPeriodInMinutes; @Value("${DATASOURCE_BONECP_IDLE_MAX_AGE_IN_MINUTES}") private Integer idleMaxAgeInMinutes; @Value("${DATASOURCE_BONECP_MAX_CONNECTIONS_PER_PARTITION}") private Integer maxConnectionsPerPartition; @Value("${DATASOURCE_BONECP_MIN_CONNECTIONS_PER_PARTITION}") private Integer minConnectionsPerPartition; @Value("${DATASOURCE_BONECP_PARTITION_COUNT}") private Integer partitionCount; @Value("${DATASOURCE_BONECP_ACQUIREINCREMENT}") private Integer acquireIncrement; @Value("${DATASOURCE_BONECP_STATEMENTS_CACHE_SIZE}") private Integer statementsCacheSize; @Value("${DATASOURCE_BONECP_RELEASE_HELPER_THREADS}") private Integer releaseHelperThreads; @Value("${MAIL_SMTP_HOST}") private String mailSMTPHost; @Value("${MAIL_SMTP_PORT}") private Integer mailSMTPPort; @Value("${MAIL_SMTP_AUTH}") private Boolean mailSMTPAuth; @Value("${MAIL_SMTP_USERNAME}") private String mailSMTPUsername; @Value("${MAIL_SMTP_PASSWORD}") private String mailSMTPPassword; @Bean static public PropertySourcesPlaceholderConfigurer placeholderConfigurer() throws IOException { PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer(); PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); p.setIgnoreResourceNotFound(true); List<Resource> resourceLocations = new ArrayList<Resource>(); //Read from class path properties first
package com.elmakers.mine.bukkit.wand; import java.util.*; import java.util.regex.Matcher; import com.elmakers.mine.bukkit.api.effect.ParticleType; import com.elmakers.mine.bukkit.api.spell.CastingCost; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.spell.BrushSpell; import com.elmakers.mine.bukkit.spell.UndoableSpell; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.Messages; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.bukkit.*; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; public class Wand implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public static Plugin metadataProvider; public final static int INVENTORY_SIZE = 27; public final static int HOTBAR_SIZE = 9; public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public final static float DEFAULT_WAND_COLOR_MIX_WEIGHT = 1.0f; // REMEMBER! Each of these MUST have a corresponding class in .traders, else traders will // destroy the corresponding data. public final static String[] PROPERTY_KEYS = { "active_spell", "active_material", "path", "xp", "xp_regeneration", "xp_max", "bound", "uses", "upgrade", "indestructible", "cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color", "effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval", "effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume", "haste", "health_regeneration", "hunger_regeneration", "icon", "mode", "keep", "locked", "quiet", "force", "randomize", "rename", "power", "overrides", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "materials", "spells" }; public final static String[] HIDDEN_PROPERTY_KEYS = { "id", "owner", "owner_id", "name", "description", "template", "organize", "fill" }; public final static String[] ALL_PROPERTY_KEYS = (String[])ArrayUtils.addAll(PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS); protected ItemStack item; protected MagicController controller; protected Mage mage; // Cached state private String id = ""; private Inventory hotbar; private List<Inventory> inventories; private String activeSpell = ""; private String activeMaterial = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String ownerId = ""; private String template = ""; private String path = ""; private boolean bound = false; private boolean indestructible = false; private boolean keep = false; private boolean autoOrganize = false; private boolean autoFill = false; private boolean isUpgrade = false; private boolean randomize = false; private boolean rename = false; private MaterialAndData icon = null; private float costReduction = 0; private float cooldownReduction = 0; private float damageReduction = 0; private float damageReductionPhysical = 0; private float damageReductionProjectiles = 0; private float damageReductionFalling = 0; private float damageReductionFire = 0; private float damageReductionExplosions = 0; private float power = 0; private boolean hasInventory = false; private boolean locked = false; private boolean forceUpgrade = false; private int uses = 0; private int xp = 0; private int xpRegeneration = 0; private int xpMax = 0; private float healthRegeneration = 0; private PotionEffect healthRegenEffect = null; private float hungerRegeneration = 0; private PotionEffect hungerRegenEffect = null; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private float effectColorMixWeight = DEFAULT_WAND_COLOR_MIX_WEIGHT; private ParticleType effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private int effectParticleCounter = 0; private boolean effectBubbles = false; private EffectRing effectPlayer = null; private Sound effectSound = null; private int effectSoundInterval = 0; private int effectSoundCounter = 0; private float effectSoundVolume = 0; private float effectSoundPitch = 0; private float speedIncrease = 0; private PotionEffect hasteEffect = null; private int quietLevel = 0; private String[] castParameters = null; private int storedXpLevel = 0; private int storedXp = 0; private float storedXpProgress = 0; // Inventory functionality private WandMode mode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private Inventory displayInventory = null; // Kinda of a hacky initialization optimization :\ private boolean suspendSave = false; // Wand configurations protected static Map<String, ConfigurationSection> wandTemplates = new HashMap<String, ConfigurationSection>(); public static boolean displayManaAsBar = true; public static boolean retainLevelDisplay = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean EnableGlow = true; public Wand(MagicController controller, ItemStack itemStack) { this.controller = controller; hotbar = CompatibilityUtils.createInventory(null, 9, "Wand"); this.icon = new MaterialAndData(itemStack.getType(), (byte)itemStack.getDurability()); inventories = new ArrayList<Inventory>(); item = itemStack; indestructible = controller.getIndestructibleWands(); loadState(); } public Wand(MagicController controller) { this(controller, DefaultWandMaterial, (short)0); } protected Wand(MagicController controller, String templateName) throws IllegalArgumentException { this(controller); suspendSave = true; String wandName = Messages.get("wand.default_name"); String wandDescription = ""; // Check for default wand if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default")) { templateName = "default"; } // See if there is a template with this key if (templateName != null && templateName.length() > 0) { // Check for randomized/pre-enchanted wands int level = 0; if (templateName.contains("(")) { String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); try { level = Integer.parseInt(levelString); } catch (Exception ex) { throw new IllegalArgumentException(ex); } templateName = templateName.substring(0, templateName.indexOf('(')); } if (!wandTemplates.containsKey(templateName)) { throw new IllegalArgumentException("No template named " + templateName); } ConfigurationSection wandConfig = wandTemplates.get(templateName); // Default to template names, override with localizations wandName = wandConfig.getString("name", wandName); wandName = Messages.get("wands." + templateName + ".name", wandName); wandDescription = wandConfig.getString("description", wandDescription); wandDescription = Messages.get("wands." + templateName + ".description", wandDescription); // Load all properties loadProperties(wandConfig); // Enchant, if an enchanting level was provided if (level > 0) { // Account for randomized locked wands boolean wasLocked = locked; locked = false; randomize(level, false); locked = wasLocked; } } setDescription(wandDescription); setName(wandName); // Don't randomize now if set to randomize later // Otherwise, do this here so the description updates if (!randomize) { randomize(); } setTemplate(templateName); suspendSave = false; saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData))); wandName = Messages.get("wand.default_name"); updateName(); saveState(); } public void unenchant() { item = new ItemStack(item.getType(), 1, (short)item.getDurability()); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); } public void setIcon(MaterialAndData materialData) { icon = materialData; if (icon != null) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } } public void makeUpgrade() { if (!isUpgrade) { isUpgrade = true; String oldName = wandName; wandName = Messages.get("wand.upgrade_name"); wandName = wandName.replace("$name", oldName); description = Messages.get("wand.upgrade_default_description"); if (template != null && template.length() > 0) { description = Messages.get("wands." + template + ".upgrade_description", description); } setIcon(DefaultUpgradeMaterial, (byte) 0); saveState(); updateName(true); updateLore(); } } protected void activateBrush(String materialKey) { setActiveBrush(materialKey); if (materialKey != null) { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush != null) { brush.activate(mage.getLocation(), materialKey); } } } public void activateBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; activateBrush(getBrush(itemStack)); } public String getLostId() { return id; } public void clearLostId() { if (id != null) { id = null; saveState(); } } public int getXpRegeneration() { return xpRegeneration; } public int getXpMax() { return xpMax; } public int getExperience() { return xp; } public void removeExperience(int amount) { xp = Math.max(0, xp - amount); updateMana(); } public float getHealthRegeneration() { return healthRegeneration; } public float getHungerRegeneration() { return hungerRegeneration; } public boolean isModifiable() { return !locked; } public boolean isIndestructible() { return indestructible; } public boolean isUpgrade() { return isUpgrade; } public boolean usesMana() { return xpMax > 0 && xpRegeneration > 0 && !isCostFree(); } public float getCooldownReduction() { return controller.getCooldownReduction() + cooldownReduction * WandLevel.maxCooldownReduction; } public float getCostReduction() { if (isCostFree()) return 1.0f; return controller.getCostReduction() + costReduction * WandLevel.maxCostReduction; } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; } public boolean getHasInventory() { return hasInventory; } public float getPower() { return power; } public boolean isSuperProtected() { return damageReduction > 1; } public boolean isSuperPowered() { return power > 1; } public boolean isCostFree() { return costReduction > 1; } public boolean isCooldownFree() { return cooldownReduction > 1; } public float getDamageReduction() { return damageReduction * WandLevel.maxDamageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical * WandLevel.maxDamageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles * WandLevel.maxDamageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling * WandLevel.maxDamageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire * WandLevel.maxDamageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions * WandLevel.maxDamageReductionExplosions; } public int getUses() { return uses; } public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } public long getWorth() { long worth = 0; // TODO: Item properties, brushes, etc Set<String> spells = getSpells(); for (String spellKey : spells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { worth += spell.getWorth(); } } return worth; } public void setName(String name) { wandName = ChatColor.stripColor(name); updateName(); } public void setTemplate(String templateName) { this.template = templateName; } public String getTemplate() { return this.template; } public WandUpgradePath getPath() { String pathKey = path; if (pathKey == null || pathKey.length() == 0) { pathKey = controller.getDefaultWandPath(); } return WandUpgradePath.getPath(pathKey); } public boolean hasPath() { return path != null && path.length() > 0; } public void setDescription(String description) { this.description = description; updateLore(); } public void tryToOwn(Player player) { if (ownerId == null || ownerId.length() == 0) { // Backwards-compatibility, don't overwrite unless the // name matches if (owner != null && !owner.equals(player.getName())) { return; } takeOwnership(player); } } protected void takeOwnership(Player player) { takeOwnership(player, controller != null && controller.bindWands(), controller != null && controller.keepWands()); } public void takeOwnership(Player player, boolean setBound, boolean setKeep) { owner = player.getName(); ownerId = player.getUniqueId().toString(); if (setBound) { bound = true; } if (setKeep) { keep = true; } updateLore(); } public ItemStack getItem() { return item; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); return allInventories; } public Set<String> getSpells() { return getSpells(false); } protected Set<String> getSpells(boolean includePositions) { Set<String> spellNames = new TreeSet<String>(); List<Inventory> allInventories = getAllInventories(); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && isSpell(items[i])) { String spellName = getSpell(items[i]); if (includePositions) { spellName += "@" + index; } spellNames.add(spellName); } index++; } } return spellNames; } protected String getSpellString() { return StringUtils.join(getSpells(true), ","); } public Set<String> getBrushes() { return getMaterialKeys(false); } protected Set<String> getMaterialKeys(boolean includePositions) { Set<String> materialNames = new TreeSet<String>(); List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && isBrush(items[i])) { String materialKey = getBrush(items[i]); if (materialKey != null) { if (includePositions) { materialKey += "@" + index; } materialNames.add(materialKey); } } index++; } } return materialNames; } protected String getMaterialString() { return StringUtils.join(getMaterialKeys(true), ","); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 0) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return; } // Set the wand item Integer selectedItem = null; if (getMode() == WandMode.INVENTORY && mage != null && mage.getPlayer() != null) { selectedItem = mage.getPlayer().getInventory().getHeldItemSlot(); // Toss the item back into the wand inventory, it'll find a home somewhere. // We hope this doesn't recurse too badly! :\ ItemStack existingHotbar = hotbar.getItem(selectedItem); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { hotbar.setItem(selectedItem, item); addToInventory(existingHotbar); } hotbar.setItem(selectedItem, item); } List<Inventory> checkInventories = getAllInventories(); boolean added = false; for (Inventory inventory : checkInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } // Restore empty wand slot if (selectedItem != null) { hotbar.setItem(selectedItem, null); } } protected Inventory getDisplayInventory() { if (displayInventory == null) { displayInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE + HOTBAR_SIZE, "Wand"); } return displayInventory; } protected Inventory getInventoryByIndex(int inventoryIndex) { while (inventoryIndex >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(inventoryIndex); } protected Inventory getInventory(Integer slot) { Inventory inventory = hotbar; if (slot >= HOTBAR_SIZE) { int inventoryIndex = (slot - HOTBAR_SIZE) / INVENTORY_SIZE; inventory = getInventoryByIndex(inventoryIndex); } return inventory; } protected int getInventorySlot(Integer slot) { if (slot < HOTBAR_SIZE) { return slot; } return ((slot - HOTBAR_SIZE) % INVENTORY_SIZE); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { hotbar.clear(); inventories.clear(); // Support YML-List-As-String format and |-delimited format spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, "|,"); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); String spellKey = pieces[0].trim(); ItemStack itemStack = createSpellIcon(spellKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for key " + spellKey); continue; } if (activeSpell == null || activeSpell.length() == 0) activeSpell = spellKey; addToInventory(itemStack, slot); } materialString = materialString.replaceAll("[\\]\\[]", ""); String[] materialNames = StringUtils.split(materialString, "|,"); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey); continue; } if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey; addToInventory(itemStack, slot); } hasInventory = spellNames.length + materialNames.length > 1; } @SuppressWarnings("deprecation") public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell == null) return null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } ItemStack itemStack = null; ItemStack originalItemStack = null; try { originalItemStack = new ItemStack(icon.getMaterial(), 1, (short)0, (byte)icon.getData()); itemStack = InventoryUtils.makeReal(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spellKey + " with material " + icon.getMaterial().name()); return originalItemStack; } updateSpellItem(itemStack, spell, wand, wand == null ? null : wand.activeMaterial, isItem); return itemStack; } protected ItemStack createSpellIcon(String spellKey) { return createSpellItem(spellKey, controller, this, false); } private String getActiveWandName(String materialKey) { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell, materialKey); } protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } @SuppressWarnings("deprecation") public static ItemStack createBrushItem(String materialKey, MagicController controller, Wand wand, boolean isItem) { MaterialAndData brushData = MaterialBrush.parseMaterialKey(materialKey, false); if (brushData == null) return null; Material material = brushData.getMaterial(); if (material == null || material == Material.AIR) { return null; } byte dataId = brushData.getData(); ItemStack originalItemStack = new ItemStack(material, 1, (short)0, (byte)dataId); ItemStack itemStack = InventoryUtils.makeReal(originalItemStack); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for " + material.name() + ": " + materialKey); return null; } ItemMeta meta = itemStack.getItemMeta(); List<String> lore = new ArrayList<String>(); if (material != null) { lore.add(ChatColor.GRAY + Messages.get("wand.building_material_info").replace("$material", MaterialBrush.getMaterialName(materialKey))); if (material == MaterialBrush.EraseMaterial) { lore.add(Messages.get("wand.erase_material_description")); } else if (material == MaterialBrush.CopyMaterial) { lore.add(Messages.get("wand.copy_material_description")); } else if (material == MaterialBrush.CloneMaterial) { lore.add(Messages.get("wand.clone_material_description")); } else if (material == MaterialBrush.ReplicateMaterial) { lore.add(Messages.get("wand.replicate_material_description")); } else if (material == MaterialBrush.MapMaterial) { lore.add(Messages.get("wand.map_material_description")); } else if (material == MaterialBrush.SchematicMaterial) { lore.add(Messages.get("wand.schematic_material_description").replace("$schematic", brushData.getCustomName())); } else { lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description")); } } if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.brush_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); updateBrushItem(itemStack, materialKey, wand); return itemStack; } protected void saveState() { if (suspendSave || item == null) return; ConfigurationSection stateNode = new MemoryConfiguration(); saveProperties(stateNode); // Save legacy data as well until migration is settled Object wandNode = InventoryUtils.createNode(item, "wand"); if (wandNode == null) { controller.getLogger().warning("Failed to save legacy wand state for wand id " + id + " to : " + item + " of class " + item.getClass()); } else { InventoryUtils.saveTagsToNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); } // TODO: Re-implement using Metadata API in 4.0 Object magicNode = CompatibilityUtils.createMetadataNode(item, metadataProvider, isUpgrade ? "upgrade" : "wand"); if (magicNode == null) { controller.getLogger().warning("Failed to save wand state for wand id " + id + " to : " + item + " of class " + item.getClass()); return; } // Clean up any extra data that might be on here if (isUpgrade) { CompatibilityUtils.removeMetadata(item, metadataProvider, "wand"); } else { CompatibilityUtils.removeMetadata(item, metadataProvider, "upgrade"); } CompatibilityUtils.removeMetadata(item, metadataProvider, "spell"); CompatibilityUtils.removeMetadata(item, metadataProvider, "brush"); InventoryUtils.saveTagsToNBT(stateNode, magicNode, ALL_PROPERTY_KEYS); } protected void loadState() { if (item == null) return; boolean isWand = CompatibilityUtils.hasMetadata(item, metadataProvider, "wand"); boolean isUpgrade = !isWand && CompatibilityUtils.hasMetadata(item, metadataProvider, "upgrade"); if (isWand || isUpgrade) { // TODO: Re-implement using Metadata API in 4.0 Object magicNode = CompatibilityUtils.getMetadataNode(item, metadataProvider, isUpgrade ? "upgrade" : "wand"); if (magicNode == null) { return; } ConfigurationSection stateNode = new MemoryConfiguration(); InventoryUtils.loadTagsFromNBT(stateNode, magicNode, ALL_PROPERTY_KEYS); loadProperties(stateNode); } else { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { return; } ConfigurationSection stateNode = new MemoryConfiguration(); InventoryUtils.loadTagsFromNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); loadProperties(stateNode); } } public void saveProperties(ConfigurationSection node) { node.set("id", id); node.set("materials", getMaterialString()); node.set("spells", getSpellString()); node.set("active_spell", activeSpell); node.set("active_material", activeMaterial); node.set("name", wandName); node.set("description", description); node.set("owner", owner); node.set("owner_id", ownerId); node.set("cost_reduction", costReduction); node.set("cooldown_reduction", cooldownReduction); node.set("power", power); node.set("protection", damageReduction); node.set("protection_physical", damageReductionPhysical); node.set("protection_projectiles", damageReductionProjectiles); node.set("protection_falling", damageReductionFalling); node.set("protection_fire", damageReductionFire); node.set("protection_explosions", damageReductionExplosions); node.set("haste", speedIncrease); node.set("xp", xp); node.set("xp_regeneration", xpRegeneration); node.set("xp_max", xpMax); node.set("health_regeneration", healthRegeneration); node.set("hunger_regeneration", hungerRegeneration); node.set("uses", uses); node.set("locked", locked); node.set("effect_color", effectColor == null ? "none" : effectColor.toString()); node.set("effect_bubbles", effectBubbles); node.set("effect_particle_data", Float.toString(effectParticleData)); node.set("effect_particle_count", effectParticleCount); node.set("effect_particle_interval", effectParticleInterval); node.set("effect_sound_interval", effectSoundInterval); node.set("effect_sound_volume", Float.toString(effectSoundVolume)); node.set("effect_sound_pitch", Float.toString(effectSoundPitch)); node.set("quiet", quietLevel); node.set("keep", keep); node.set("randomize", randomize); node.set("rename", rename); node.set("bound", bound); node.set("force", forceUpgrade); node.set("indestructible", indestructible); node.set("fill", autoFill); node.set("upgrade", isUpgrade); node.set("organize", autoOrganize); if (castParameters != null && castParameters.length > 0) { node.set("overrides", StringUtils.join(castParameters, ' ')); } else { node.set("overrides", null); } if (effectSound != null) { node.set("effect_sound", effectSound.name()); } else { node.set("effectSound", null); } if (effectParticle != null) { node.set("effect_particle", effectParticle.name()); } else { node.set("effect_particle", null); } if (mode != null) { node.set("mode", mode.name()); } else { node.set("mode", null); } if (icon != null) { String iconKey = MaterialBrush.getMaterialKey(icon); if (iconKey != null && iconKey.length() > 0) { node.set("icon", iconKey); } else { node.set("icon", null); } } else { node.set("icon", null); } if (template != null && template.length() > 0) { node.set("template", template); } else { node.set("template", null); } if (path != null && path.length() > 0) { node.set("path", path); } else { node.set("path", null); } } public void loadProperties(ConfigurationSection wandConfig) { loadProperties(wandConfig, false); } public void setEffectColor(String hexColor) { // Annoying config conversion issue :\ if (hexColor.contains(".")) { hexColor = hexColor.substring(0, hexColor.indexOf('.')); } if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); } public void loadProperties(ConfigurationSection wandConfig, boolean safe) { locked = (boolean)wandConfig.getBoolean("locked", locked); float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction); costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction; float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction); cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction; float _power = (float)wandConfig.getDouble("power", power); power = safe ? Math.max(_power, power) : _power; float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction); damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction; float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical); damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical; float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles); damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles; float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling); damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling; float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire); damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire; float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions); damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions; int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration); xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration; int _xpMax = wandConfig.getInt("xp_max", xpMax); xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax; int _xp = wandConfig.getInt("xp", xp); xp = safe ? Math.max(_xp, xp) : _xp; float _healthRegeneration = (float)wandConfig.getDouble("health_regeneration", healthRegeneration); healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration; float _hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", hungerRegeneration); hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration; int _uses = wandConfig.getInt("uses", uses); uses = safe ? Math.max(_uses, uses) : _uses; float _speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease); speedIncrease = safe ? Math.max(_speedIncrease, speedIncrease) : _speedIncrease; if (wandConfig.contains("effect_color") && !safe) { setEffectColor(wandConfig.getString("effect_color")); } // Don't change any of this stuff in safe mode if (!safe) { id = wandConfig.getString("id", id); isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade); quietLevel = wandConfig.getInt("quiet", quietLevel); effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles); keep = wandConfig.getBoolean("keep", keep); indestructible = wandConfig.getBoolean("indestructible", indestructible); bound = wandConfig.getBoolean("bound", bound); forceUpgrade = wandConfig.getBoolean("force", forceUpgrade); autoOrganize = wandConfig.getBoolean("organize", autoOrganize); autoFill = wandConfig.getBoolean("fill", autoFill); randomize = wandConfig.getBoolean("randomize", randomize); rename = wandConfig.getBoolean("rename", rename); if (wandConfig.contains("effect_particle")) { parseParticleEffect(wandConfig.getString("effect_particle")); effectParticleData = 0; } if (wandConfig.contains("effect_sound")) { parseSoundEffect(wandConfig.getString("effect_sound")); } effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData); effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount); effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval); effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval); effectSoundVolume = (float)wandConfig.getDouble("effect_sound_volume", effectSoundVolume); effectSoundPitch = (float)wandConfig.getDouble("effect_sound_pitch", effectSoundPitch); setMode(parseWandMode(wandConfig.getString("mode"), mode)); owner = wandConfig.getString("owner", owner); ownerId = wandConfig.getString("owner_id", ownerId); wandName = wandConfig.getString("name", wandName); description = wandConfig.getString("description", description); template = wandConfig.getString("template", template); path = wandConfig.getString("path", path); activeSpell = wandConfig.getString("active_spell", activeSpell); activeMaterial = wandConfig.getString("active_material", activeMaterial); String wandMaterials = wandConfig.getString("materials", ""); String wandSpells = wandConfig.getString("spells", ""); if (wandMaterials.length() > 0 || wandSpells.length() > 0) { wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials; wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells; parseInventoryStrings(wandSpells, wandMaterials); } if (wandConfig.contains("randomize_icon")) { setIcon(ConfigurationUtils.toMaterialAndData(wandConfig.getString("randomize_icon"))); randomize = true; } else if (!randomize && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); } castParameters = null; String overrides = wandConfig.getString("overrides", null); if (overrides != null && !overrides.isEmpty()) { castParameters = StringUtils.split(overrides, ' '); } } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; effectSoundVolume = 0; effectSoundPitch = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; effectSoundVolume = (effectSoundVolume < 0.01f) ? 0.8f : effectSoundVolume; effectSoundPitch = (effectSoundPitch < 0.01f) ? 1.1f : effectSoundPitch; } if (effectParticle == null) { effectParticleInterval = 0; } else { effectParticleInterval = (effectParticleInterval == 0) ? 2 : effectParticleInterval; effectParticleCount = (effectParticleCount == 0) ? 1 : effectParticleCount; } if (xpRegeneration <= 0 || xpMax <= 0 || costReduction >= 1) { xpMax = 0; xpRegeneration = 0; xp = 0; } checkActiveMaterial(); updateName(); updateLore(); } protected void parseSoundEffect(String effectSoundName) { if (effectSoundName.length() > 0) { String testName = effectSoundName.toUpperCase().replace("_", ""); try { for (Sound testType : Sound.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectSound = testType; break; } } } catch (Exception ex) { effectSound = null; } } else { effectSound = null; } } protected void parseParticleEffect(String effectParticleName) { if (effectParticleName.length() > 0) { String testName = effectParticleName.toUpperCase().replace("_", ""); try { for (ParticleType testType : ParticleType.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectParticle = testType; break; } } } catch (Exception ex) { effectParticle = null; } } else { effectParticle = null; } } public void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } for (String key : PROPERTY_KEYS) { String value = InventoryUtils.getMeta(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } private static String getBrushDisplayName(String materialKey) { String materialName = MaterialBrush.getMaterialName(materialKey); if (materialName == null) { materialName = "none"; } return ChatColor.GRAY + materialName; } private static String getSpellDisplayName(SpellTemplate spell, String materialKey) { String name = ""; if (spell != null) { if (materialKey != null && (spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { name = ChatColor.GOLD + spell.getName() + " " + getBrushDisplayName(materialKey) + ChatColor.WHITE; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, String materialKey) { // Build wand name int remaining = getRemainingUses(); ChatColor wandColor = remaining > 0 ? ChatColor.DARK_RED : isModifiable() ? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : ChatColor.GOLD; String name = wandColor + getDisplayName(); if (randomize) return name; Set<String> spells = getSpells(); // Add active spell to description if (spell != null && (spells.size() > 1 || hasPath())) { name = getSpellDisplayName(spell, materialKey) + " (" + name + ChatColor.WHITE + ")"; } if (remaining > 0) { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); name = name + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, activeMaterial); } private String getActiveWandName() { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } protected String getDisplayName() { return randomize ? Messages.get("wand.randomized_name") : wandName; } public void updateName(boolean isActive) { CompatibilityUtils.setDisplayName(item, isActive && !isUpgrade ? getActiveWandName() : ChatColor.GOLD + getDisplayName()); // Reset Enchantment glow if (EnableGlow) { CompatibilityUtils.addGlow(item); } // Make indestructible CompatibilityUtils.makeUnbreakable(item); } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<String>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected List<String> getLore() { return getLore(getSpells().size(), getBrushes().size()); } protected void addPropertyLore(List<String> lore) { if (usesMana()) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cost_reduction", costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cooldown_reduction", cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString("wand.power", power)); if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString("wand.haste", speedIncrease)); if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection", damageReduction, WandLevel.maxDamageReduction)); if (damageReduction < 1) { if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_physical", damageReductionPhysical, WandLevel.maxDamageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_projectile", damageReductionProjectiles, WandLevel.maxDamageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fall", damageReductionFalling, WandLevel.maxDamageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fire", damageReductionFire, WandLevel.maxDamageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_blast", damageReductionExplosions, WandLevel.maxDamageReductionExplosions)); } if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.health_regeneration", healthRegeneration)); if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.hunger_regeneration", hungerRegeneration)); } private String getLevelString(String templateName, float amount) { return getLevelString(templateName, amount, 1); } private static String getLevelString(String templateName, float amount, float max) { String templateString = Messages.get(templateName); if (templateString.contains("$roman")) { templateString = templateString.replace("$roman", getRomanString(amount)); } return templateString.replace("$amount", Integer.toString((int)amount)); } private static String getRomanString(float amount) { String roman = ""; if (amount > 1) { roman = Messages.get("wand.enchantment_level_max"); } else if (amount > 0.8) { roman = Messages.get("wand.enchantment_level_5"); } else if (amount > 0.6) { roman = Messages.get("wand.enchantment_level_4"); } else if (amount > 0.4) { roman = Messages.get("wand.enchantment_level_3"); } else if (amount > 0.2) { roman = Messages.get("wand.enchantment_level_2"); } else { roman = Messages.get("wand.enchantment_level_1"); } return roman; } protected List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<String>(); if (description.length() > 0) { if (description.contains("$")) { String randomDescription = Messages.get("wand.randomized_lore"); if (randomDescription.length() > 0) { lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + randomDescription); } } else { lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } } if (randomize) { return lore; } SpellTemplate spell = controller.getSpellTemplate(activeSpell); // This is here specifically for a wand that only has // one spell now, but may get more later. Since you // can't open the inventory in this state, you can not // otherwise see the spell lore. if (spell != null && spellCount == 1 && !hasInventory && !isUpgrade && hasPath()) { lore.add(getSpellDisplayName(spell, null)); addSpellLore(spell, lore, this); } if (materialCount == 1 && activeMaterial != null && activeMaterial.length() > 0) { lore.add(getBrushDisplayName(activeMaterial)); } if (!isUpgrade) { if (owner.length() > 0) { if (bound) { String ownerDescription = Messages.get("wand.bound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } else { String ownerDescription = Messages.get("wand.owner_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription); } } } if (spellCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.upgrade_spell_count").replace("$count", ((Integer)spellCount).toString())); } else if (spellCount > 1) { lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString())); } } if (materialCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.upgrade_material_count").replace("$count", ((Integer)materialCount).toString())); } else if (materialCount > 1) { lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString())); } } int remaining = getRemainingUses(); if (remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? Messages.get("wand.upgrade_uses_singular") : Messages.get("wand.upgrade_uses"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } else { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } } addPropertyLore(lore); if (isUpgrade) { lore.add(ChatColor.YELLOW + Messages.get("wand.upgrade_item_description")); } return lore; } protected void updateLore() { CompatibilityUtils.setLore(item, getLore()); if (EnableGlow) { CompatibilityUtils.addGlow(item); } } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable"); if (!enchantableMaterials.contains(item.getType())) { item.setType(EnchantableWandMaterial); item.setDurability((short)0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public static Wand getActiveWand(MagicController spells, Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); if (isWand(activeItem)) { return new Wand(spells, activeItem); } return null; } public static boolean isWand(ItemStack item) { return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "wand") || isLegacyWand(item)); } public static boolean isLegacyWand(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "wand") && !isLegacyUpgrade(item); } public static boolean isLegacyUpgrade(ItemStack item) { if (item == null) return false; Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) return false; String upgradeData = InventoryUtils.getMeta(wandNode, "upgrade"); return upgradeData != null && upgradeData.equals("true"); } public static boolean isUpgrade(ItemStack item) { if (item == null) return false; if (isLegacyUpgrade(item)) return true; return item != null && CompatibilityUtils.hasMetadata(item, metadataProvider, "upgrade"); } public static boolean isLegacySpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isSpell(ItemStack item) { return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "spell") || isLegacySpell(item)); } public static boolean isLegacyBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } public static boolean isBrush(ItemStack item) { return item != null && (CompatibilityUtils.hasMetadata(item, metadataProvider, "brush") || isLegacyBrush(item)); } public static String getLegacySpell(ItemStack item) { if (!isLegacySpell(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); return InventoryUtils.getMeta(spellNode, "key"); } public static String getSpell(ItemStack item) { if (!isSpell(item)) { if (isLegacySpell(item)) { return getLegacySpell(item); } return null; } return CompatibilityUtils.getMetadata(item, metadataProvider, "spell"); } public static String getLegacyBrush(ItemStack item) { if (!isLegacyBrush(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); return InventoryUtils.getMeta(brushNode, "key"); } public static String getBrush(ItemStack item) { if (!isBrush(item)) { if (isLegacyBrush(item)) { return getLegacyBrush(item); } return null; } return CompatibilityUtils.getMetadata(item, metadataProvider, "brush"); } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellItem(item, spell, activeName ? this : null, activeMaterial, false); } } else if (isBrush(item)) { updateBrushItem(item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial, boolean isItem) { ItemMeta meta = itemStack.getItemMeta(); String displayName; if (wand != null) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(spell, activeMaterial); } meta.setDisplayName(displayName); List<String> lore = new ArrayList<String>(); addSpellLore(spell, lore, wand); if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.spell_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); CompatibilityUtils.addGlow(itemStack); CompatibilityUtils.setMetadata(itemStack, metadataProvider, "spell", spell.getKey()); } public static void updateBrushItem(ItemStack itemStack, String materialKey, Wand wand) { ItemMeta meta = itemStack.getItemMeta(); String displayName = null; if (wand != null) { displayName = wand.getActiveWandName(materialKey); } else { displayName = MaterialBrush.getMaterialName(materialKey); } meta.setDisplayName(displayName); itemStack.setItemMeta(meta); CompatibilityUtils.setMetadata(itemStack, metadataProvider, "brush", materialKey); } public void updateHotbar() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; if (!mage.hasStoredInventory()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { PlayerInventory inventory = player.getInventory(); updateHotbar(inventory); player.updateInventory(); } } @SuppressWarnings("deprecation") private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!mage.hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); inventory.clear(); updateHotbar(inventory); updateInventory(inventory, HOTBAR_SIZE, false); updateName(); player.updateInventory(); } else if (wandMode == WandMode.CHEST) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory, 0, true); player.updateInventory(); } } private void updateHotbar(PlayerInventory playerInventory) { // Check for an item already in the player's held slot, which // we are about to replace with the wand. int currentSlot = playerInventory.getHeldItemSlot(); ItemStack existingHotbar = hotbar.getItem(currentSlot); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { // Toss the item back into the wand inventory, it'll find a home somewhere. hotbar.setItem(currentSlot, item); addToInventory(existingHotbar); hotbar.setItem(currentSlot, null); } // Put the wand in the player's active slot. playerInventory.setItem(currentSlot, item); // Set hotbar items from remaining list for (int hotbarSlot = 0; hotbarSlot < HOTBAR_SIZE; hotbarSlot++) { if (hotbarSlot != currentSlot) { ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot, hotbarItem); } } } private void updateInventory(Inventory targetInventory, int startOffset, boolean addHotbar) { // Set inventory from current page int currentOffset = startOffset; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } if (addHotbar) { for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack inventoryItem = hotbar.getItem(i); updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset++, inventoryItem); } } } protected static void addSpellLore(SpellTemplate spell, List<String> lore, CostReducer reducer) { String description = spell.getDescription(); String usage = spell.getUsage(); if (description != null && description.length() > 0) { lore.add(description); } if (usage != null && usage.length() > 0) { lore.add(usage); } Collection<CastingCost> costs = spell.getCosts(); if (costs != null) { for (CastingCost cost : costs) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(reducer))); } } } Collection<CastingCost> activeCosts = spell.getActiveCosts(); if (activeCosts != null) { for (CastingCost cost : activeCosts) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(reducer))); } } } long duration = spell.getDuration(); if (duration > 0) { long seconds = duration / 1000; if (seconds > 60 * 60 ) { long hours = seconds / (60 * 60); lore.add(Messages.get("duration.lasts_hours").replace("$hours", ((Long)hours).toString())); } else if (seconds > 60) { long minutes = seconds / 60; lore.add(Messages.get("duration.lasts_minutes").replace("$minutes", ((Long)minutes).toString())); } else { lore.add(Messages.get("duration.lasts_seconds").replace("$seconds", ((Long)seconds).toString())); } } if ((spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { lore.add(ChatColor.GOLD + Messages.get("spell.brush")); } if (spell instanceof UndoableSpell && ((UndoableSpell)spell).isUndoable()) { lore.add(ChatColor.GRAY + Messages.get("spell.undoable")); } } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (mage == null) return; if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!mage.hasStoredInventory()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { playerItem = null; } hotbar.setItem(i, playerItem); } // Fill in the active inventory page Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { openInventory.setItem(i, playerInventory.getItem(i + HOTBAR_SIZE)); } saveState(); } public static boolean isActive(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public boolean enchant(int totalLevels) { return randomize(totalLevels, true); } protected boolean randomize(int totalLevels, boolean additive) { WandUpgradePath path = getPath(); if (path == null) return false; int maxLevel = path.getMaxLevel(); // Just a hard-coded sanity check totalLevels = Math.min(totalLevels, maxLevel * 50); int addLevels = Math.min(totalLevels, maxLevel); boolean modified = true; while (addLevels > 0 && modified) { WandLevel level = path.getLevel(addLevels); modified = level.randomizeWand(this, additive); totalLevels -= maxLevel; addLevels = Math.min(totalLevels, maxLevel); additive = true; } return modified; } public static ItemStack createItem(MagicController controller, String templateName) { ItemStack item = createSpellItem(templateName, controller, null, true); if (item == null) { item = createBrushItem(templateName, controller, null, true); if (item == null) { Wand wand = createWand(controller, templateName); if (wand != null) { item = wand.getItem(); } } } return item; } public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (IllegalArgumentException ignore) { // the Wand constructor throws an exception on an unknown tempalte } catch (Exception ex) { ex.printStackTrace(); } return wand; } protected void sendAddMessage(String messageKey, String nameParam) { if (mage == null) return; String message = Messages.get(messageKey).replace("$name", nameParam); mage.sendMessage(message); } public boolean add(Wand other) { if (!isModifiable() || !other.isModifiable()) return false; boolean modified = false; if (other.isForcedUpgrade() || other.costReduction > costReduction) { costReduction = other.costReduction; modified = true; if (costReduction > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.cost_reduction", costReduction)); } if (other.isForcedUpgrade() || other.power > power) { power = other.power; modified = true; if (power > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.power", power)); } if (other.isForcedUpgrade() || other.damageReduction > damageReduction) { damageReduction = other.damageReduction; modified = true; if (damageReduction > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection", damageReduction)); } if (other.isForcedUpgrade() || other.damageReductionPhysical > damageReductionPhysical) { damageReductionPhysical = other.damageReductionPhysical; modified = true; if (damageReductionPhysical > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_physical", damageReductionPhysical)); } if (other.isForcedUpgrade() || other.damageReductionProjectiles > damageReductionProjectiles) { damageReductionProjectiles = other.damageReductionProjectiles; modified = true; if (damageReductionProjectiles > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_projectile", damageReductionProjectiles)); } if (other.isForcedUpgrade() || other.damageReductionFalling > damageReductionFalling) { damageReductionFalling = other.damageReductionFalling; modified = true; if (damageReductionFalling > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_falling", damageReductionFalling)); } if (other.isForcedUpgrade() || other.damageReductionFire > damageReductionFire) { damageReductionFire = other.damageReductionFire; modified = true; if (damageReductionFire > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_fire", damageReductionFire)); } if (other.isForcedUpgrade() || other.damageReductionExplosions > damageReductionExplosions) { damageReductionExplosions = other.damageReductionExplosions; modified = true; if (damageReductionExplosions > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_explosions", damageReductionExplosions)); } if (other.isForcedUpgrade() || other.healthRegeneration > healthRegeneration) { healthRegeneration = other.healthRegeneration; modified = true; if (healthRegeneration > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.health_regeneration", healthRegeneration)); } if (other.isForcedUpgrade() || other.hungerRegeneration > hungerRegeneration) { hungerRegeneration = other.hungerRegeneration; modified = true; if (hungerRegeneration > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.hunger_regeneration", hungerRegeneration)); } if (other.isForcedUpgrade() || other.speedIncrease > speedIncrease) { speedIncrease = other.speedIncrease; modified = true; if (speedIncrease > 0) sendAddMessage("wand.upgraded_property", getLevelString("wand.haste", speedIncrease)); } // Mix colors if (other.effectColor != null) { if (this.effectColor == null || (other.isUpgrade() && other.effectColor != null)) { this.effectColor = other.effectColor; } else { this.effectColor = this.effectColor.mixColor(other.effectColor, other.effectColorMixWeight); } modified = true; } if (other.rename && other.template != null && other.template.length() > 0) { ConfigurationSection template = wandTemplates.get(other.template); wandName = template.getString("name", wandName); wandName = Messages.get("wands." + other.template + ".name", wandName); updateName(); } modified = modified | (!keep && other.keep); modified = modified | (!bound && other.bound); modified = modified | (!effectBubbles && other.effectBubbles); keep = keep || other.keep; bound = bound || other.bound; effectBubbles = effectBubbles || other.effectBubbles; if (other.effectParticle != null && (other.isUpgrade || effectParticle == null)) { modified = modified | (effectParticle != other.effectParticle); effectParticle = other.effectParticle; modified = modified | (effectParticleData != other.effectParticleData); effectParticleData = other.effectParticleData; modified = modified | (effectParticleCount != other.effectParticleCount); effectParticleCount = other.effectParticleCount; modified = modified | (effectParticleInterval != other.effectParticleInterval); effectParticleInterval = other.effectParticleInterval; } if (other.effectSound != null && (other.isUpgrade || effectSound == null)) { modified = modified | (effectSound != other.effectSound); effectSound = other.effectSound; modified = modified | (effectSoundInterval != other.effectSoundInterval); effectSoundInterval = other.effectSoundInterval; modified = modified | (effectSoundVolume != other.effectSoundVolume); effectSoundVolume = other.effectSoundVolume; modified = modified | (effectSoundPitch != other.effectSoundPitch); effectSoundPitch = other.effectSoundPitch; } if ((template == null || template.length() == 0) && (other.template != null && other.template.length() > 0)) { modified = true; template = other.template; } if (other.isUpgrade && other.mode != null) { modified = modified | (mode != other.mode); setMode(other.mode); } // Don't need mana if cost-free if (isCostFree()) { xpRegeneration = 0; xpMax = 0; xp = 0; } else { if (other.isForcedUpgrade() || other.xpRegeneration > xpRegeneration) { xpRegeneration = other.xpRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (other.isForcedUpgrade() || other.xpMax > xpMax) { xpMax = other.xpMax; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); } if (other.isForcedUpgrade() || other.xp > xp) { xp = other.xp; modified = true; } } // Eliminate limited-use wands if (uses == 0 || other.uses == 0) { modified = modified | (uses != 0); uses = 0; } else { // Otherwise add them modified = modified | (other.uses != 0); uses = uses + other.uses; } // Add spells Set<String> spells = other.getSpells(); for (String spellKey : spells) { if (addSpell(spellKey)) { modified = true; String spellName = spellKey; SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) spellName = spell.getName(); if (mage != null) mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spellName)); } } // Add materials Set<String> materials = other.getBrushes(); for (String materialKey : materials) { if (addBrush(materialKey)) { modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); } } Player player = (mage == null) ? null : mage.getPlayer(); if (other.autoFill && player != null) { this.fill(player); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.filled")); } if (other.autoOrganize && mage != null) { this.organizeInventory(mage); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.reorganized")); } saveState(); updateName(); updateLore(); return modified; } public boolean isForcedUpgrade() { return isUpgrade && forceUpgrade; } public boolean keepOnDeath() { return keep; } public static void loadTemplates(ConfigurationSection properties) { wandTemplates.clear(); Set<String> wandKeys = properties.getKeys(false); for (String key : wandKeys) { ConfigurationSection wandNode = properties.getConfigurationSection(key); wandNode.set("key", key); ConfigurationSection existing = wandTemplates.get(key); if (existing != null) { Set<String> overrideKeys = existing.getKeys(false); for (String propertyKey : overrideKeys) { existing.set(propertyKey, existing.get(key)); } } else { wandTemplates.put(key, wandNode); } if (!wandNode.getBoolean("enabled", true)) { wandTemplates.remove(key); } } } public static Collection<String> getWandKeys() { return wandTemplates.keySet(); } public static Collection<ConfigurationSection> getWandTemplates() { return wandTemplates.values(); } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { for (WandMode testMode : WandMode.values()) { if (testMode.name().equalsIgnoreCase(modeString)) { return testMode; } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeMaterial == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeMaterial); } } public void toggleInventory() { if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { Set<String> spells = getSpells(); // Sanity check, so it'll switch to inventory next time if (spells.size() > 1) hasInventory = true; if (spells.size() > 0) { activeSpell = spells.iterator().next(); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } @SuppressWarnings("deprecation") public void cycleInventory() { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + 1) % inventoryCount; updateInventory(); if (mage != null && inventories.size() > 1) { mage.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") private void openInventory() { if (mage == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (mage.hasStoredInventory()) return; if (mage.storeInventory()) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") public void closeInventory() { if (!isInventoryOpen()) return; saveInventory(); inventoryIsOpen = false; if (mage != null) { mage.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f); if (getMode() == WandMode.INVENTORY) { mage.restoreInventory(); Player player = mage.getPlayer(); player.setItemInHand(item); player.updateInventory(); } else { mage.getPlayer().closeInventory(); } } } public boolean fill(Player player) { Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); for (SpellTemplate spell : allSpells) { if (spell.hasCastPermission(player) && spell.getIcon().getMaterial() != Material.AIR) { addSpell(spell.getKey()); } } autoFill = false; saveState(); return true; } public void activate(Mage mage, ItemStack wandItem) { if (mage == null || wandItem == null) return; if (this.isUpgrade) { controller.getLogger().warning("Activated an upgrade item- this shouldn't happen"); return; } // Update held item, it may have been copied since this wand was created. this.item = wandItem; this.mage = mage; // Check for spell or other special icons in the player's inventory Player player = mage.getPlayer(); boolean modified = false; ItemStack[] items = player.getInventory().getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { modified = true; items[i] = null; } } if (modified) { player.getInventory().setContents(items); } // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { if (getSpells().size() == 0) { fill(mage.getPlayer()); } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); } // Check for auto-bind // Don't do this for op'd players, effectively, so // they can create and give unbound wands. if (bound && (ownerId == null || ownerId.length() == 0) && !controller.hasPermission(player, "Magic.wand.override_bind", false)) { // Backwards-compatibility, don't overrwrite unless the // name matches if (owner == null || owner.length() == 0 || owner.equals(player.getName())) { takeOwnership(mage.getPlayer()); saveState(); } } // Check for randomized wands if (randomize) { randomize(); } checkActiveMaterial(); mage.setActiveWand(this); if (usesMana()) { storedXpLevel = player.getLevel(); storedXpProgress = player.getExp(); storedXp = 0; updateMana(); } updateActiveMaterial(); updateName(); updateLore(); updateEffects(); } protected void randomize() { boolean modified = randomize; if (description.contains("$")) { Matcher matcher = Messages.PARAMETER_PATTERN.matcher(description); while(matcher.find()) { String key = matcher.group(1); if (key != null) { modified = true; description = description.replace("$" + key, Messages.getRandomized(key)); updateLore(); } } } if (template != null && template.length() > 0) { ConfigurationSection wandConfig = wandTemplates.get(template); if (wandConfig != null && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); modified = true; } } randomize = false; if (modified) { saveState(); } } protected void checkActiveMaterial() { if (activeMaterial == null || activeMaterial.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeMaterial = materials.iterator().next(); } } } public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isSpell(item)) { String spellKey = getSpell(item); Set<String> spells = getSpells(); if (!spells.contains(spellKey) && addSpell(spellKey)) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spell.getName())); return true; } } } else if (isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); return true; } } else if (isUpgrade(item)) { Wand wand = new Wand(controller, item); return this.add(wand); } return false; } protected void updateEffects() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles) { CompatibilityUtils.addPotionEffect(player, effectColor.getColor()); } Location location = mage.getLocation(); if (effectParticle != null && location != null) { if ((effectParticleCounter++ % effectParticleInterval) == 0) { if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(2); effectPlayer.setIterations(2); effectPlayer.setRadius(2); effectPlayer.setSize(5); effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setParticleCount(effectParticleCount); effectPlayer.start(player.getEyeLocation(), null); } } if (effectSound != null && location != null && controller.soundsEnabled()) { if ((effectSoundCounter++ % effectSoundInterval) == 0) { mage.getLocation().getWorld().playSound(location, effectSound, effectSoundVolume, effectSoundPitch); } } } protected void updateMana() { if (mage != null && xpMax > 0 && xpRegeneration > 0) { Player player = mage.getPlayer(); if (displayManaAsBar) { if (!retainLevelDisplay) { player.setLevel(0); } player.setExp((float)xp / (float)xpMax); } else { player.setLevel(xp); player.setExp(0); } } } public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } public void deactivate() { if (mage == null) return; Player player = mage.getPlayer(); if (effectBubbles && player != null) { CompatibilityUtils.removePotionEffect(player); } // This is a tying wands together with other spells, potentially // But with the way the mana system works, this seems like the safest route. mage.deactivateAllSpells(); if (isInventoryOpen()) { closeInventory(); } // Extra just-in-case mage.restoreInventory(); if (usesMana() && player != null) { player.setExp(storedXpProgress); player.setLevel(storedXpLevel); player.giveExp(storedXp); storedXp = 0; storedXpProgress = 0; storedXpLevel = 0; } mage.setActiveWand(null); mage = null; saveState(); } public Spell getActiveSpell() { if (mage == null || activeSpell == null || activeSpell.length() == 0) return null; return mage.getSpell(activeSpell); } public String getActiveSpellKey() { return activeSpell; } public String getActiveBrushKey() { return activeMaterial; } public boolean cast() { Spell spell = getActiveSpell(); if (spell != null) { if (spell.cast(castParameters)) { Color spellColor = spell.getColor(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } use(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (mage == null) return; if (uses > 0) { uses if (uses <= 0) { Player player = mage.getPlayer(); mage.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f); PlayerInventory playerInventory = player.getInventory(); playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); player.updateInventory(); deactivate(); } else { updateName(); updateLore(); saveState(); } } } public void onPlayerExpChange(PlayerExpChangeEvent event) { if (mage == null) return; if (addExperience(event.getAmount())) { event.setAmount(0); } } public boolean addExperience(int xp) { if (usesMana()) { storedXp += xp; return true; } return false; } public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; if (speedIncrease > 0) { int hasteLevel = (int)(speedIncrease * WandLevel.maxHasteLevel); if (hasteEffect == null || hasteEffect.getAmplifier() != hasteLevel) { hasteEffect = new PotionEffect(PotionEffectType.SPEED, 80, hasteLevel, true); } CompatibilityUtils.applyPotionEffect(player, hasteEffect); } if (healthRegeneration > 0) { int regenLevel = (int)(healthRegeneration * WandLevel.maxHealthRegeneration); if (healthRegenEffect == null || healthRegenEffect.getAmplifier() != regenLevel) { healthRegenEffect = new PotionEffect(PotionEffectType.REGENERATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, healthRegenEffect); } if (hungerRegeneration > 0) { int regenLevel = (int)(hungerRegeneration * WandLevel.maxHungerRegeneration); if (hungerRegenEffect == null || hungerRegenEffect.getAmplifier() != regenLevel) { hungerRegenEffect = new PotionEffect(PotionEffectType.SATURATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, hungerRegenEffect); } if (usesMana()) { xp = Math.min(xpMax, xp + xpRegeneration); updateMana(); } if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } updateEffects(); } public MagicController getMaster() { return controller; } public void cycleSpells(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> spellsSet = getSpells(); ArrayList<String> spells = new ArrayList<String>(spellsSet); if (spells.size() == 0) return; if (activeSpell == null) { activeSpell = spells.get(0).split("@")[0]; return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + 1) % spells.size(); setActiveSpell(spells.get(spellIndex).split("@")[0]); } public void cycleMaterials(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<String>(materialsSet); if (materials.size() == 0) return; if (activeMaterial == null) { activeMaterial = materials.get(0).split("@")[0]; return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (materials.get(i).split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + 1) % materials.size(); activateBrush(materials.get(materialIndex).split("@")[0]); } public boolean hasExperience() { return xpRegeneration > 0; } public Mage getActivePlayer() { return mage; } protected void clearInventories() { inventories.clear(); hotbar.clear(); } public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public Inventory getHotbar() { return hotbar; } public WandMode getMode() { return mode != null ? mode : controller.getDefaultWandMode(); } public void setMode(WandMode mode) { this.mode = mode; } public boolean showCastMessages() { return quietLevel == 0; } public boolean showMessages() { return quietLevel < 2; } /* * Public API Implementation */ @Override public boolean isLost() { return this.id != null; } @Override public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) { return this.id != null && this.id.equals(lostWand.getId()); } @Override public LostWand makeLost(Location location) { if (id == null || id.length() == 0) { id = UUID.randomUUID().toString(); saveState(); } return new LostWand(this, location); } @Override public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { Player player = mage.getPlayer(); if (!Wand.hasActiveWand(player)) { controller.getLogger().warning("Wand activated without holding a wand!"); try { throw new Exception("Wand activated without holding a wand!"); } catch (Exception ex) { ex.printStackTrace(); } return; } if (!canUse(player)) { mage.sendMessage(Messages.get("wand.bound").replace("$name", owner)); player.setItemInHand(null); Location location = player.getLocation(); location.setY(location.getY() + 1); controller.addLostWand(makeLost(location)); saveState(); Item droppedItem = player.getWorld().dropItemNaturally(location, item); Vector velocity = droppedItem.getVelocity(); velocity.setY(velocity.getY() * 2 + 1); droppedItem.setVelocity(velocity); return; } id = null; if (mage instanceof Mage) { activate((Mage)mage, player.getItemInHand()); } } @Override public void organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); organizer.organize(); openInventoryPage = 0; autoOrganize = false; saveState(); } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = new Wand(controller, newItem); newWand.saveState(); return newWand; } @Override public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), false); saveState(); return true; } @Override public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), true); saveState(); return true; } @Override public boolean isLocked() { return this.locked; } @Override public void unlock() { locked = false; } @Override public boolean canUse(Player player) { if (!bound || owner == null || owner.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; // Backwards-compatibility if (ownerId == null || ownerId.length() == 0) { return owner.equalsIgnoreCase(player.getName()); } return ownerId.equalsIgnoreCase(player.getUniqueId().toString()); } public boolean addSpell(String spellName) { if (!isModifiable()) return false; if (hasSpell(spellName)) return false; if (isInventoryOpen()) { saveInventory(); } ItemStack spellItem = createSpellIcon(spellName); if (spellItem == null) { controller.getPlugin().getLogger().warning("Unknown spell: " + spellName); return false; } addToInventory(spellItem); updateInventory(); hasInventory = getSpells().size() + getBrushes().size() > 1; updateLore(); saveState(); return true; } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } @Override public boolean hasBrush(String materialKey) { return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return getSpells().contains(spellName); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (hasBrush(materialKey)) return false; if (isInventoryOpen()) { saveInventory(); } ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; addToInventory(itemStack); if (activeMaterial == null || activeMaterial.length() == 0) { setActiveBrush(materialKey); } else { updateInventory(); } updateLore(); hasInventory = getSpells().size() + getBrushes().size() > 1; saveState(); return true; } @Override public void setActiveBrush(String materialKey) { this.activeMaterial = materialKey; updateName(); updateActiveMaterial(); updateHotbar(); saveState(); } @Override public void setActiveSpell(String activeSpell) { this.activeSpell = activeSpell; updateName(); updateHotbar(); saveState(); } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; if (isInventoryOpen()) { saveInventory(); } if (materialKey.equals(activeMaterial)) { activeMaterial = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && isBrush(itemStack)) { String itemKey = getBrush(itemStack); if (itemKey.equals(materialKey)) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = materialKey; } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventory(); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; if (isInventoryOpen()) { saveInventory(); } if (spellName.equals(activeSpell)) { activeSpell = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { activeSpell = getSpell(itemStack); } if (found && activeSpell != null) { break; } } } } updateName(); updateLore(); saveState(); updateInventory(); return found; } }
package fitnesse.responders.run; import fitnesse.FitNesseContext; import fitnesse.FitNesseVersion; import fitnesse.authentication.SecureOperation; import fitnesse.authentication.SecureResponder; import fitnesse.authentication.SecureTestOperation; import fitnesse.http.MockRequest; import fitnesse.http.MockResponseSender; import fitnesse.http.Response; import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.assertCounts; import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.getXmlDocumentFromResults; import fitnesse.responders.run.formatters.XmlFormatter; import fitnesse.testutil.FitNesseUtil; import fitnesse.testutil.FitSocketReceiver; import fitnesse.wiki.*; import fitnesse.wikitext.Utils; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import util.Clock; import util.DateAlteringClock; import util.DateTimeUtil; import util.FileUtil; import static util.RegexTestCase.*; import util.XmlUtil; import static util.XmlUtil.getElementByTagName; import java.io.File; import java.io.FileInputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestResponderTest { private static final String TEST_TIME = "12/5/2008 01:19:00"; private WikiPage root; private MockRequest request; private TestResponder responder; private FitNesseContext context; private Response response; private MockResponseSender sender; private WikiPage testPage; private String results; private FitSocketReceiver receiver; private WikiPage errorLogsParentPage; private PageCrawler crawler; private File xmlResultsFile; private XmlChecker xmlChecker = new XmlChecker(); private DateAlteringClock clock; @Before public void setUp() throws Exception { File testDir = new File("TestDir"); testDir.mkdir(); root = InMemoryPage.makeRoot("RooT"); crawler = root.getPageCrawler(); errorLogsParentPage = crawler.addPage(root, PathParser.parse("ErrorLogs")); request = new MockRequest(); responder = new TestResponder(); responder.setFastTest(true); context = FitNesseUtil.makeTestContext(root); receiver = new FitSocketReceiver(0, context.socketDealer); context.port = receiver.receiveSocket(); clock = new DateAlteringClock(DateTimeUtil.getDateFromString(TEST_TIME)).advanceMillisOnEachQuery(); } @After public void tearDown() throws Exception { receiver.close(); FitNesseUtil.destroyTestContext(); Clock.restoreDefaultClock(); } @Test public void testSimpleRun() throws Exception { doSimpleRun(passFixtureTable()); assertSubString(testPage.getName(), results); assertSubString("Test Results", results); assertSubString("class", results); assertNotSubString("ClassNotFoundException", results); } private void doSimpleRun(String fixtureTable) throws Exception { doSimpleRunWithTags(fixtureTable, null); } private void doSimpleRunWithTags(String fixtureTable, String tags) throws Exception { String simpleRunPageName = "TestPage"; testPage = crawler.addPage(root, PathParser.parse(simpleRunPageName), classpathWidgets() + fixtureTable); if (tags != null) { PageData pageData = testPage.getData(); pageData.setAttribute(PageData.PropertySUITES, tags); testPage.commit(pageData); } request.setResource(testPage.getName()); responder.turnOffChunking(); response = responder.makeResponse(context, request); sender = new MockResponseSender(); sender.doSending(response); results = sender.sentData(); } @Test public void testEmptyTestPage() throws Exception { PageData data = root.getData(); data.setContent(classpathWidgets()); root.commit(data); testPage = crawler.addPage(root, PathParser.parse("EmptyTestPage")); request.setResource(testPage.getName()); response = responder.makeResponse(context, request); sender = new MockResponseSender(); sender.doSending(response); sender.sentData(); WikiPagePath errorLogPath = PathParser.parse("ErrorLogs.EmptyTestPage"); WikiPage errorLogPage = crawler.getPage(root, errorLogPath); String errorLogContent = errorLogPage.getData().getContent(); assertNotSubString("Exception", errorLogContent); } @Test public void testFitSocketGetsClosed() throws Exception { doSimpleRun(passFixtureTable()); assertTrue(receiver.socket.isClosed()); } @Test public void testStandardOutput() throws Exception { responder.setFastTest(false); String content = classpathWidgets() + outputWritingTable("output1") + outputWritingTable("output2") + outputWritingTable("output3"); String errorLogContent = doRunAndGetErrorLog(content); assertHasRegexp("output1", errorLogContent); assertHasRegexp("output2", errorLogContent); assertHasRegexp("output3", errorLogContent); } @Test public void testErrorOutput() throws Exception { responder.setFastTest(false); String content = classpathWidgets() + errorWritingTable("error1") + errorWritingTable("error2") + errorWritingTable("error3"); String errorLogContent = doRunAndGetErrorLog(content); assertHasRegexp("error1", errorLogContent); assertHasRegexp("error2", errorLogContent); assertHasRegexp("error3", errorLogContent); } private String doRunAndGetErrorLog(String content) throws Exception { WikiPage testPage = crawler.addPage(root, PathParser.parse("TestPage"), content); request.setResource(testPage.getName()); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); String results = sender.sentData(); assertHasRegexp("ErrorLog", results); WikiPage errorLog = errorLogsParentPage.getChildPage(testPage.getName()); return errorLog.getData().getContent(); } @Test public void testHasExitValueHeader() throws Exception { WikiPage testPage = crawler.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + passFixtureTable()); request.setResource(testPage.getName()); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); String results = sender.sentData(); assertSubString("Exit-Code: 0", results); } @Test public void exitCodeIsCountOfErrors() throws Exception { doSimpleRun(failFixtureTable()); assertSubString("Exit-Code: 1", results); } @Test public void pageHistoryLinkIsIncluded() throws Exception { doSimpleRun(passFixtureTable()); assertSubString("href=\"TestPage?pageHistory\">", results); assertSubString("[history]", results); } @Test public void testFixtureThatCrashes() throws Exception { responder.setFastTest(false); WikiPage testPage = crawler.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + crashFixtureTable()); request.setResource(testPage.getName()); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); String results = sender.sentData(); assertSubString("ErrorLog", results); } @Test public void testResultsIncludeActions() throws Exception { doSimpleRun(passFixtureTable()); assertSubString("<div class=\"actions\">", results); } @Test public void testResultsHaveHeaderAndFooter() throws Exception { crawler.addPage(root, PathParser.parse("PageHeader"), "HEADER"); crawler.addPage(root, PathParser.parse("PageFooter"), "FOOTER"); doSimpleRun(passFixtureTable()); assertSubString("HEADER", results); assertSubString("FOOTER", results); } @Test public void testExecutionStatusAppears() throws Exception { doSimpleRun(passFixtureTable()); assertHasRegexp("<div id=\"execution-status\">.*?</div>", results); } @Test public void simpleXmlFormat() throws Exception { request.addInput("format", "xml"); doSimpleRun(passFixtureTable()); xmlChecker.assertFitPassFixtureXmlReportIsCorrect(); } @Test public void noHistory_skipsHistoryFormatter() throws Exception{ ensureXmlResultFileDoesNotExist(new TestSummary(2, 0, 0, 0)); request.addInput("nohistory", "true"); doSimpleRun(simpleSlimDecisionTable()); assertFalse(xmlResultsFile.exists()); } private String slimDecisionTable() { return "!define TEST_SYSTEM {slim}\n" + "|!-DT:fitnesse.slim.test.TestSlim-!|\n" + "|string|get string arg?|\n" + "|right|wrong|\n" + "|wow|wow|\n"; } @Test public void slimXmlFormat() throws Exception { request.addInput("format", "xml"); ensureXmlResultFileDoesNotExist(new TestSummary(1, 1, 0, 0)); doSimpleRunWithTags(slimDecisionTable(), "zoo"); Document xmlFromFile = getXmlFromFileAndDeleteFile(); xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect(); xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile); xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect(); assertSubString("Exit-Code: 1", results); } private void ensureXmlResultFileDoesNotExist(TestSummary counts) { String resultsFileName = String.format("%s/TestPage/20081205011900_%d_%d_%d_%d.xml", context.getTestHistoryDirectory(), counts.getRight(), counts.getWrong(), counts.getIgnores(), counts.getExceptions()); xmlResultsFile = new File(resultsFileName); if (xmlResultsFile.exists()) FileUtil.deleteFile(xmlResultsFile); } private Document getXmlFromFileAndDeleteFile() throws Exception { assertTrue(xmlResultsFile.getAbsolutePath(), xmlResultsFile.exists()); FileInputStream xmlResultsStream = new FileInputStream(xmlResultsFile); Document xmlDoc = XmlUtil.newDocument(xmlResultsStream); xmlResultsStream.close(); FileUtil.deleteFile(xmlResultsFile); return xmlDoc; } @Test public void slimScenarioXmlFormat() throws Exception { request.addInput("format", "xml"); doSimpleRun(XmlChecker.slimScenarioTable); xmlChecker.assertXmlReportOfSlimScenarioTableIsCorrect(); } @Test public void simpleTextFormatForPassingTest() throws Exception { request.addInput("format", "text"); doSimpleRun(passFixtureTable()); assertEquals("text/text", response.getContentType()); assertTrue(results.indexOf("\n. ") != -1); assertTrue(results.indexOf("R:1 W:0 I:0 E:0 TestPage\t(TestPage)") != -1); assertTrue(results.indexOf("1 Tests,\t0 Failures") != -1); } @Test public void simpleTextFormatForFailingTest() throws Exception { request.addInput("format", "text"); doSimpleRun(failFixtureTable()); assertEquals("text/text", response.getContentType()); assertTrue(results.indexOf("\nF ") != -1); assertTrue(results.indexOf("R:0 W:1 I:0 E:0 TestPage\t(TestPage)") != -1); assertTrue(results.indexOf("1 Tests,\t1 Failures") != -1); } @Test public void simpleTextFormatForErrorTest() throws Exception { request.addInput("format", "text"); doSimpleRun(errorFixtureTable()); assertEquals("text/text", response.getContentType()); assertTrue(results.indexOf("\nX ") != -1); assertTrue(results.indexOf("R:0 W:0 I:0 E:1 TestPage\t(TestPage)") != -1); assertTrue(results.indexOf("1 Tests,\t1 Failures") != -1); } private String getExecutionStatusMessage() throws Exception { Pattern pattern = Pattern.compile("<div id=\"execution-status\">.*?<a href=\"ErrorLogs\\.[^\"]*\">([^<>]*?)</a>.*?</div>", Pattern.DOTALL); Matcher matcher = pattern.matcher(results); matcher.find(); return matcher.group(1); } private String getExecutionStatusIconFilename() { Pattern pattern = Pattern.compile("<div id=\"execution-status\">.*?<img.*?src=\"(?:[^/]*/)*([^/]*\\.gif)\".*?/>.*?</div>", Pattern.DOTALL); Matcher matcher = pattern.matcher(results); matcher.find(); return matcher.group(1); } @Test public void testExecutionStatusOk() throws Exception { doSimpleRun(passFixtureTable()); assertEquals("Tests Executed OK", getExecutionStatusMessage()); assertEquals("ok.gif", getExecutionStatusIconFilename()); } @Test public void debugTest() throws Exception { responder.setFastTest(false); request.addInput("debug", ""); doSimpleRun(passFixtureTable()); assertEquals("Tests Executed OK", getExecutionStatusMessage()); assertEquals("ok.gif", getExecutionStatusIconFilename()); assertTrue("should be fast test", responder.isFastTest()); } @Test public void testExecutionStatusOutputCaptured() throws Exception { responder.setFastTest(false); doSimpleRun(outputWritingTable("blah")); assertEquals("Output Captured", getExecutionStatusMessage()); assertEquals("output.gif", getExecutionStatusIconFilename()); } @Test public void testExecutionStatusError() throws Exception { responder.setFastTest(false); doSimpleRun(crashFixtureTable()); assertEquals("Errors Occurred", getExecutionStatusMessage()); assertEquals("error.gif", getExecutionStatusIconFilename()); } @Test public void testExecutionStatusErrorHasPriority() throws Exception { responder.setFastTest(false); doSimpleRun(errorWritingTable("blah") + crashFixtureTable()); assertEquals("Errors Occurred", getExecutionStatusMessage()); } @Test public void testTestSummaryAppears() throws Exception { doSimpleRun(passFixtureTable()); assertHasRegexp(divWithIdAndContent("test-summary", ".*?"), results); } @Test public void testTestSummaryInformationAppears() throws Exception { doSimpleRun(passFixtureTable()); assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.innerHTML = \".*?Assertions:.*?\";.*?</script>", results); assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \".*?\";.*?</script>", results); } @Test public void testTestSummaryHasRightClass() throws Exception { doSimpleRun(passFixtureTable()); assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \"pass\";.*?</script>", results); } @Test public void testTestHasStopped() throws Exception { String semaphoreName = "testTestHasStopped.semaphore"; File semaphore = new File(semaphoreName); if (semaphore.exists()) semaphore.delete(); new Thread(makeStopTestsRunnable(semaphore)).start(); doSimpleRun(createAndWaitFixture(semaphoreName)); assertHasRegexp("Testing was interupted", results); semaphore.delete(); } private String createAndWaitFixture(String semaphoreName) { return "!define TEST_SYSTEM {slim}\n" + "!|fitnesse.testutil.CreateFileAndWaitFixture|" + semaphoreName + "|\n"; } private Runnable makeStopTestsRunnable(File semaphore) { return new WaitForSemaphoreThenStopProcesses(semaphore); } private class WaitForSemaphoreThenStopProcesses implements Runnable { private File semaphore; public WaitForSemaphoreThenStopProcesses(File semaphore) { this.semaphore = semaphore; } public void run() { waitForSemaphore(); context.runningTestingTracker.stopAllProcesses(); } private void waitForSemaphore() { try { int i = 1000; while (!semaphore.exists()) { if (--i <= 0) break; Thread.sleep(5); } } catch (InterruptedException e) { } } } @Test public void testAuthentication_RequiresTestPermission() throws Exception { assertTrue(responder instanceof SecureResponder); SecureOperation operation = responder.getSecureOperation(); assertEquals(SecureTestOperation.class, operation.getClass()); } @Test public void testNotifyListeners() throws Exception { MockTestEventListener listener1 = new MockTestEventListener(); MockTestEventListener listener2 = new MockTestEventListener(); TestResponder.registerListener(listener1); TestResponder.registerListener(listener2); doSimpleRun(passFixtureTable()); assertEquals(true, listener1.gotPreTestNotification); assertEquals(true, listener2.gotPreTestNotification); } @Test public void testSuiteSetUpAndTearDownIsCalledIfSingleTestIsRun() throws Exception { responder.setFastTest(false); WikiPage suitePage = crawler.addPage(root, PathParser.parse("TestSuite"), classpathWidgets()); WikiPage testPage = crawler.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown")); WikiPagePath testPagePath = crawler.getFullPath(testPage); String resource = PathParser.render(testPagePath); request.setResource(resource); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); results = sender.sentData(); assertEquals("Output Captured", getExecutionStatusMessage()); assertHasRegexp("ErrorLog", results); WikiPage errorLog = crawler.getPage(errorLogsParentPage, testPagePath); String errorLogContent = errorLog.getData().getContent(); assertHasRegexp("Output of SuiteSetUp", errorLogContent); assertHasRegexp("Output of TestPage", errorLogContent); assertHasRegexp("Output of SuiteTearDown", errorLogContent); } @Test public void testSuiteSetUpDoesNotIncludeSetUp() throws Exception { responder.setFastTest(false); WikiPage suitePage = crawler.addPage(root, PathParser.parse("TestSuite"), classpathWidgets()); WikiPage testPage = crawler.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp")); crawler.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp")); WikiPagePath testPagePath = crawler.getFullPath(testPage); String resource = PathParser.render(testPagePath); request.setResource(resource); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); results = sender.sentData(); WikiPage errorLog = crawler.getPage(errorLogsParentPage, testPagePath); String errorLogContent = errorLog.getData().getContent(); assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage"); assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp"); } @Test public void testSuiteTearDownDoesNotIncludeTearDown() throws Exception { responder.setFastTest(false); WikiPage suitePage = crawler.addPage(root, PathParser.parse("TestSuite"), classpathWidgets()); WikiPage testPage = crawler.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown")); crawler.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown")); WikiPagePath testPagePath = crawler.getFullPath(testPage); String resource = PathParser.render(testPagePath); request.setResource(resource); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); results = sender.sentData(); WikiPage errorLog = crawler.getPage(errorLogsParentPage, testPagePath); String errorLogContent = errorLog.getData().getContent(); assertMessagesOccurInOrder(errorLogContent, "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown"); assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of TearDown"); } @Test public void testSuiteSetUpAndSuiteTearDownWithSetUpAndTearDown() throws Exception { responder.setFastTest(false); WikiPage suitePage = crawler.addPage(root, PathParser.parse("TestSuite"), classpathWidgets()); WikiPage testPage = crawler.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp")); crawler.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp")); crawler.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown")); crawler.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown")); WikiPagePath testPagePath = crawler.getFullPath(testPage); String resource = PathParser.render(testPagePath); request.setResource(resource); Response response = responder.makeResponse(context, request); MockResponseSender sender = new MockResponseSender(); sender.doSending(response); results = sender.sentData(); WikiPage errorLog = crawler.getPage(errorLogsParentPage, testPagePath); String errorLogContent = errorLog.getData().getContent(); assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown"); assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp"); } private void assertMessageHasJustOneOccurrenceOf(String output, String regexp) { Matcher match = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL).matcher(output); match.find(); boolean found = match.find(); if (found) fail("The regexp <" + regexp + "> was more than once in: " + output + "."); } private void assertMessagesOccurInOrder(String errorLogContent, String... messages) { int previousIndex = 0, currentIndex = 0; String previousMsg = ""; for (String msg: messages) { currentIndex = errorLogContent.indexOf(msg); assertTrue(String.format("\"%s\" should occur not before \"%s\", but did in \"%s\"", msg, previousMsg, errorLogContent), currentIndex > previousIndex); previousIndex = currentIndex; previousMsg = msg; } } private String simpleSlimDecisionTable() { return "!define TEST_SYSTEM {slim}\n" + "|!-DT:fitnesse.slim.test.TestSlim-!|\n" + "|string|get string arg?|\n" + "|wow|wow|\n"; } @Test public void checkHistoryForSimpleSlimTable() throws Exception { ensureXmlResultFileDoesNotExist(new TestSummary(1, 0, 0, 0)); doSimpleRun(simpleSlimDecisionTable()); Document xmlFromFile = getXmlFromFileAndDeleteFile(); xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile); assertHasRegexp("<td><span class=\"pass\">wow</span></td>", Utils.unescapeHTML(results)); } private String errorWritingTable(String message) { return "\n|!-fitnesse.testutil.ErrorWritingFixture-!|\n" + "|" + message + "|\n\n"; } private String outputWritingTable(String message) { return "\n|!-fitnesse.testutil.OutputWritingFixture-!|\n" + "|" + message + "|\n\n"; } private String classpathWidgets() { return "!path classes\n"; } private String crashFixtureTable() { return "|!-fitnesse.testutil.CrashFixture-!|\n"; } private String passFixtureTable() { return "|!-fitnesse.testutil.PassFixture-!|\n"; } private String failFixtureTable() { return "|!-fitnesse.testutil.FailFixture-!|\n"; } private String errorFixtureTable() { return "|!-fitnesse.testutil.ErrorFixture-!|\n"; } class XmlChecker { private Element testResultsElement; public void assertXmlHeaderIsCorrect(Document testResultsDocument) throws Exception { testResultsElement = testResultsDocument.getDocumentElement(); assertEquals("testResults", testResultsElement.getNodeName()); String version = XmlUtil.getTextValue(testResultsElement, "FitNesseVersion"); assertEquals(new FitNesseVersion().toString(), version); } public void assertFitPassFixtureXmlReportIsCorrect() throws Exception { assertHeaderOfXmlDocumentsInResponseIsCorrect(); Element result = getElementByTagName(testResultsElement, "result"); Element counts = getElementByTagName(result, "counts"); assertCounts(counts, "1", "0", "0", "0"); String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis"); assertThat(Long.parseLong(runTimeInMillis), is(not(0L))); Element tags = getElementByTagName(result, "tags"); assertNull(tags); String content = XmlUtil.getTextValue(result, "content"); assertSubString("PassFixture", content); String relativePageName = XmlUtil.getTextValue(result, "relativePageName"); assertEquals("TestPage", relativePageName); } public void assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect() throws Exception { String instructionContents[] = {"make", "table", "beginTable", "reset", "setString", "execute", "getStringArg", "reset", "setString", "execute", "getStringArg", "endTable"}; String instructionResults[] = {"OK", "EXCEPTION", "EXCEPTION", "EXCEPTION", "VOID", "VOID", "right", "EXCEPTION", "VOID", "VOID", "wow", "EXCEPTION"}; assertHeaderOfXmlDocumentsInResponseIsCorrect(); Element result = getElementByTagName(testResultsElement, "result"); Element counts = getElementByTagName(result, "counts"); assertCounts(counts, "1", "1", "0", "0"); String tags = XmlUtil.getTextValue(result, "tags"); assertEquals("zoo", tags); Element tables = getElementByTagName(result, "tables"); assertNotNull(tables); NodeList tableList = tables.getElementsByTagName("table"); assertNotNull(tableList); assertEquals(1, tableList.getLength()); Element tableElement = (Element) tableList.item(0); String tableName = XmlUtil.getTextValue(tableElement, "name"); assertNotNull(tableName); assertEquals("decisionTable_0", tableName); assertEquals("[[pass(DT:fitnesse.slim.test.TestSlim)],[string,get string arg?],[right,[right] fail(expected [wrong])],[wow,pass(wow)]]", tableElementToString(tableElement)); Element instructions = getElementByTagName(result, "instructions"); NodeList instructionList = instructions.getElementsByTagName("instructionResult"); assertEquals(instructionContents.length, instructionList.getLength()); for (int i = 0; i < instructionContents.length; i++) { Element instructionElement = (Element) instructionList.item(i); assertInstructionHas(instructionElement, instructionContents[i]); } for (int i = 0; i < instructionResults.length; i++) { Element instructionElement = (Element) instructionList.item(i); assertResultHas(instructionElement, instructionResults[i]); } checkExpectation(instructionList, 0, "decisionTable_0_0", "0", "0", "right", "ConstructionExpectation", "OK", "DT:fitnesse.slim.test.TestSlim", "pass(DT:fitnesse.slim.test.TestSlim)"); checkExpectation(instructionList, 4, "decisionTable_0_4", "0", "2", "ignored", "VoidReturnExpectation", "/__VOID__/", "right", "right"); checkExpectation(instructionList, 6, "decisionTable_0_6", "1", "2", "wrong", "ReturnedValueExpectation", "right", "wrong", "[right] fail(expected [wrong])"); checkExpectation(instructionList, 8, "decisionTable_0_8", "0", "3", "ignored", "VoidReturnExpectation", "/__VOID__/", "wow", "wow"); checkExpectation(instructionList, 10, "decisionTable_0_10", "1", "3", "right", "ReturnedValueExpectation", "wow", "wow", "pass(wow)"); } private String tableElementToString(Element tableElement) { StringBuilder result = new StringBuilder(); result.append("["); rowsToString(tableElement, result); result.append("]"); return result.toString(); } private void rowsToString(Element tableElement, StringBuilder result) { NodeList rows = tableElement.getElementsByTagName("row"); for (int row = 0; row < rows.getLength(); row++) { result.append("["); Element rowElement = (Element) rows.item(row); colsToString(result, rowElement); result.append("],"); } result.deleteCharAt(result.length() - 1); } private void colsToString(StringBuilder result, Element rowElement) { NodeList cols = rowElement.getElementsByTagName("col"); for (int col = 0; col < cols.getLength(); col++) { Element colElement = (Element) cols.item(col); result.append(colElement.getFirstChild().getNodeValue()); result.append(","); } result.deleteCharAt(result.length() - 1); } public final static String slimScenarioTable = "!define TEST_SYSTEM {slim}\n" + "\n" + "!|scenario|f|a|\n" + "|check|echo int|@a|@a|\n" + "\n" + "!|script|fitnesse.slim.test.TestSlim|\n" + "\n" + "!|f|\n" + "|a|\n" + "|1|\n" + "|2|\n"; public void assertXmlReportOfSlimScenarioTableIsCorrect() throws Exception { assertHeaderOfXmlDocumentsInResponseIsCorrect(); Element result = getElementByTagName(testResultsElement, "result"); Element counts = getElementByTagName(result, "counts"); assertCounts(counts, "2", "0", "0", "0"); String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis"); assertThat(Long.parseLong(runTimeInMillis), is(not(0L))); assertTablesInSlimScenarioAreCorrect(result); assertInstructionsOfSlimScenarioTableAreCorrect(result); } private void assertInstructionsOfSlimScenarioTableAreCorrect(Element result) throws Exception { Element instructions = getElementByTagName(result, "instructions"); NodeList instructionList = instructions.getElementsByTagName("instructionResult"); assertInstructionContentsOfSlimScenarioAreCorrect(instructionList); assertInstructionResultsOfSlimScenarioAreCorrect(instructionList); assertExpectationsOfSlimScenarioAreCorrect(instructionList); } private void assertExpectationsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception { checkExpectation(instructionList, 0, "scriptTable_1_0", "1", "0", "right", "ConstructionExpectation", "OK", "fitnesse.slim.test.TestSlim", "pass(fitnesse.slim.test.TestSlim)"); checkExpectation(instructionList, 1, "decisionTable_2_0/scriptTable_0_0", "3", "1", "right", "ReturnedValueExpectation", "1", "1", "pass(1)"); checkExpectation(instructionList, 2, "decisionTable_2_1/scriptTable_0_0", "3", "1", "right", "ReturnedValueExpectation", "2", "2", "pass(2)"); } private void assertInstructionResultsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception { String instructionResults[] = {"OK", "1", "2"}; for (int i = 0; i < instructionResults.length; i++) { Element instructionElement = (Element) instructionList.item(i); assertResultHas(instructionElement, instructionResults[i]); } } private void assertInstructionContentsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception { String instructionContents[] = {"make", "call", "call"}; assertEquals(instructionContents.length, instructionList.getLength()); for (int i = 0; i < instructionContents.length; i++) { Element instructionElement = (Element) instructionList.item(i); assertInstructionHas(instructionElement, instructionContents[i]); } } private void assertTablesInSlimScenarioAreCorrect(Element result) throws Exception { Element tables = getElementByTagName(result, "tables"); NodeList tableList = tables.getElementsByTagName("table"); assertEquals(5, tableList.getLength()); String tableNames[] = {"scenarioTable_0", "scriptTable_1", "decisionTable_2", "decisionTable_2_0/scriptTable_0", "decisionTable_2_1/scriptTable_0"}; String tableValues[][][] = { { {"scenario", "f", "a"}, {"check", "echo int", "@a", "@a"} }, { {"script", "pass(fitnesse.slim.test.TestSlim)"} }, { {"f"}, {"a"}, {"1", "pass(scenario:decisionTable_2_0/scriptTable_0)"}, {"2", "pass(scenario:decisionTable_2_1/scriptTable_0)"} }, { {"scenario", "f", "a"}, {"check", "echo int", "1", "pass(1)"} }, { {"scenario", "f", "a"}, {"check", "echo int", "2", "pass(2)"} } }; for (int tableIndex = 0; tableIndex < tableList.getLength(); tableIndex++) { assertEquals(tableNames[tableIndex], XmlUtil.getTextValue((Element) tableList.item(tableIndex), "name")); Element tableElement = (Element) tableList.item(tableIndex); NodeList rowList = tableElement.getElementsByTagName("row"); for (int rowIndex = 0; rowIndex < rowList.getLength(); rowIndex++) { NodeList colList = ((Element) rowList.item(rowIndex)).getElementsByTagName("col"); for (int colIndex = 0; colIndex < colList.getLength(); colIndex++) assertEquals(tableValues[tableIndex][rowIndex][colIndex], XmlUtil.getElementText((Element) colList.item(colIndex))); } } } private void checkExpectation(NodeList instructionList, int index, String id, String col, String row, String status, String type, String actual, String expected, String message) throws Exception { Element instructionElement = (Element) instructionList.item(index); Element expectation = getElementByTagName(instructionElement, "expectation"); assertEquals(id, XmlUtil.getTextValue(expectation, "instructionId")); assertEquals(status, XmlUtil.getTextValue(expectation, "status")); assertEquals(type, XmlUtil.getTextValue(expectation, "type")); assertEquals(col, XmlUtil.getTextValue(expectation, "col")); assertEquals(row, XmlUtil.getTextValue(expectation, "row")); assertEquals(actual, XmlUtil.getTextValue(expectation, "actual")); assertEquals(expected, XmlUtil.getTextValue(expectation, "expected")); assertEquals(message, XmlUtil.getTextValue(expectation, "evaluationMessage")); } private void assertInstructionHas(Element instructionElement, String content) throws Exception { String instruction = XmlUtil.getTextValue(instructionElement, "instruction"); assertTrue(String.format("instruction %s should contain: %s", instruction, content), instruction.indexOf(content) != -1); } private void assertResultHas(Element instructionElement, String content) throws Exception { String result = XmlUtil.getTextValue(instructionElement, "slimResult"); assertTrue(String.format("result %s should contain: %s", result, content), result.indexOf(content) != -1); } private void assertHeaderOfXmlDocumentsInResponseIsCorrect() throws Exception { assertEquals("text/xml", response.getContentType()); Document testResultsDocument = getXmlDocumentFromResults(results); xmlChecker.assertXmlHeaderIsCorrect(testResultsDocument); } } public static class XmlTestUtilities { public static Document getXmlDocumentFromResults(String results) throws Exception { String endOfXml = "</testResults>"; String startOfXml = "<?xml"; int xmlStartIndex = results.indexOf(startOfXml); int xmlEndIndex = results.indexOf(endOfXml) + endOfXml.length(); String xmlString = results.substring(xmlStartIndex, xmlEndIndex); return XmlUtil.newDocument(xmlString); } public static void assertCounts(Element counts, String right, String wrong, String ignores, String exceptions) throws Exception { assertEquals(right, XmlUtil.getTextValue(counts, "right")); assertEquals(wrong, XmlUtil.getTextValue(counts, "wrong")); assertEquals(ignores, XmlUtil.getTextValue(counts, "ignores")); assertEquals(exceptions, XmlUtil.getTextValue(counts, "exceptions")); } } }
package com.enderio.core.common.util; import javax.annotation.concurrent.Immutable; import lombok.Value; import lombok.experimental.Wither; /** * An object to represent a bounds limit on a property. * * @param <T> * The type of the bound. */ @Immutable @Value //@AllArgsConstructor(staticName = "of") // Broken with javac 1.8... public class Bound<T extends Number & Comparable<T>> { public static final Bound<Double> MAX_BOUND = Bound.of(Double.MIN_VALUE, Double.MAX_VALUE); @Wither public T min, max; public static <T extends Number & Comparable<T>> Bound<T> of(T min, T max) { return new Bound<T>(min, max); } public T clamp(T val) { return val.compareTo(min) < 0 ? min : val.compareTo(max) > 0 ? max : val; } }
package it.unimi.dsi.sux4j.mph; import it.unimi.dsi.fastutil.booleans.BooleanArrays; import it.unimi.dsi.fastutil.ints.IntArrays; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.mg4j.io.FastBufferedReader; import it.unimi.dsi.mg4j.io.FileLinesCollection; import it.unimi.dsi.mg4j.io.LineIterator; import it.unimi.dsi.mg4j.util.MutableString; import it.unimi.dsi.mg4j.util.ProgressLogger; import it.unimi.dsi.sux4j.bits.BitVector; import it.unimi.dsi.sux4j.bits.Fast; import it.unimi.dsi.sux4j.bits.LongArrayBitVector; import it.unimi.dsi.sux4j.bits.LongBigList; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.zip.GZIPInputStream; import org.apache.log4j.Logger; import cern.colt.GenericPermuting; import cern.colt.GenericSorting; import cern.colt.Swapper; import cern.colt.function.IntComparator; import cern.jet.random.engine.MersenneTwister; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; /** Minimal perfect hash. * * <P>Given a list of terms without duplicates, * the constructors of this class finds a perfect hash function for * the list. Subsequent calls to the {@link #getNumber(CharSequence)} method will return the ordinal position of * the provided character sequence (if it appeared in the list; otherwise, the result is a random position). The class * can then be saved by serialisation and reused later. * * <P>This class is very scalable, and if you have enough memory it will handle * efficiently hundreds of millions of terms: in particular, the * {@linkplain #MinimalPerfectHash(Iterable, int) offline constructor} * can build a map without loading the terms in memory. * * <P>To do its job, the class must store three vectors of weights that are used to compute * certain hash functions. By default, the vectors are long as the longest term, but if * your collection is sorted you can ask (passing {@link #WEIGHT_UNKNOWN_SORTED_TERMS} to a constructor) * for the shortest possible vector length. This optimisation does not change the * memory footprint, but it can improve performance. * * <P>As a commodity, this class provides a main method that reads from * standard input a (possibly <samp>gzip</samp>'d) sequence of newline-separated terms, and * writes a serialised minimal perfect hash table for the given list. You can * specify on the command line the kind of table (e.g., * {@link it.unimi.dsi.mg4j.util.HashCodeSignedMinimalPerfectHash}) and have it fetched by reflection. * As a commodity, all signed classes in MG4J have a main method invoking the {@linkplain #main(Class, String[]) * parameterised main method} of this class, * which accept the default class to be built. In this way, running the main method of * any signed class provides the same features. * * <P>For efficiency, there are also method that access a minimal perfect hash * {@linkplain #getNumber(byte[], int, int) using byte arrays interpreted as ISO-8859-1} characters. * * <h3>Implementation Details</h3> * * <P>An object of this class uses about 1.23<var>n</var> integers between 0 and <var>n</var>-1 inclusive * to hash <var>n</var> terms. This is asymptotically optimal, but for small collections using an integer * wastes a large number of bits in each entry. At construction time, however, about 15<var>n</var> integers * (i.e., 60<var>n</var> bytes) are necessary. * * <P>The technique used here is suggested (but not fully described) in the second edition of <em>Managing * Gigabytes</em>. It is due to Havas, Majewski, Wormald and Czech, and it is fully described in * the monograph by Czech, Havas and Majewski on perfect hashing (&ldquo;Perfect Hashing&rdquo;, * <i>Theoret. Comput. Sci.</i> 182:1&minus;143, 1997). * * <P>First, a triple of intermediate hash functions (generated via universal hashing) define for each * term a 3-hyperedge in a hypergraph with 1.23<var>n</var> vertices. Each intermediate hash function * uses a vector of random weights; the length of the vector is by default the length of the longest * term, but if the collection is sorted it is possible to compute the minimum length of a prefix that will * distinguish any pair of term. * * <P>Then, by successively * stripping hyperedges with one vertex of degree one, we create an ordering on the hyperedges. * Finally, we assign (in reverse order) to each vertex of a hyperedge a number in the range * 0 and <var>n</var>-1 in such a way that the sum of the three numbers modulo <var>n</var> is exactly * the original index of the term corresponding to the hyperedge. This is possible with high probability, * so we try until we succeed. * * <P>Note that the mathematical results guaranteeing that it is possible to find a * function in expected constant time are <em>asymptotic</em>. * Thus, when the number of terms is less than {@link #TERM_THRESHOLD}, an instance * of this class just stores the terms in a vector and scans them linearly. This behaviour, * however, is completely transparent to the user. * * <h3>Rounds and Logging</h3> * * <P>Building a minimal perfect hash map may take hours. As it happens with all probabilistic algorithms, * one can just give estimates of the expected time. * * <P>There are two probabilistic sources of problems: degenerate hyperedges and non-acyclic hypergraphs. * The ratio between the number of vertices and the number of terms guarantee that acyclicity is true with high * probability. However, when generating the hypergraph we use three hash functions, and it must never happen * that the value of two of those functions coincide on a given term. Because of the birthday paradox, the * probability of getting a nondegerate edge is just * <blockquote> * (<var>m</var>-1)(<var>m</var>-2)/<var>m</var><sup>2</sup>, * </blockquote> * where <var>m</var>=1.26<var>n</var>. Since this must happen for <var>n</var> times, we must raise * this probability to <var>n</var>, and as <var>n</var> grows the value quickly (and monotonically) * reaches <i>e</i><sup>-3/1.26</sup>. So the expected number of trials to generate a random 3-hypergraph * would be bounded by <i>e</i><sup>3/1.26</sup>, which is about 11. Note that this bound * <em>does not depend on <var>n</var></em>. * * <p>However, starting from MG4J 1.2 this class will patch deterministically the hash functions so that * degenerate edges are <em>extremely</em> unlikely (in fact, so unlikely they never happen). One round of * generation should be sufficient for generating a valid hypergraph. The fix is performed by adding * {@link #NODE_OVERHEAD} nodes to the graph, and using them to remap the random hash functions in case * of clashes. The fix must be repeated, of course, each time {@link #getNumber(MutableString)} is called, * but in the vaste majority of cases it reduces to two checks for equality with negative result. * * <P>Once the hypergraph has been generated, the stripping procedure may fail. However, the expected number * of trials tends to 1 as <var>n</var> * approaches infinity (Czech, Havas and Majewski, for instance, report that on a set of 50,000 terms * they obtained consistently one trial for more than 5000 experiments). * * <P>To help diagnosing problem with the generation process * class, this class will log at {@link org.apache.log4j.Level#INFO INFO} level * what's happening. In particular, it will signal whenever a degenerate * hyperedge is generated, and the various construction phases. * * <P>Note that if during the generation process the log warns more than once about duplicate hyperedges, you should * suspect that there are duplicates in the term list, as duplicate hyperedges are <em>extremely</em> unlikely. * * @author Sebastiano Vigna * @author Paolo Boldi * @since 0.1 */ public class MinimalPerfectHash implements Serializable { private static final Logger LOGGER = it.unimi.dsi.mg4j.util.Fast.getLogger( MinimalPerfectHash.class ); private static final boolean DEBUG = true; /** The number of nodes the hypergraph will actually have. This value guarantees that the hypergraph will be acyclic with positive probability. */ public static final float ENLARGEMENT_FACTOR = 1.23f; /** The number of bits per block in the rank8 structure. */ private static final int BITS_PER_BLOCK = 512; // TODO: use original deterministic trick /** The minimum number of terms that will trigger the construction of a minimal perfect hash; * overwise, terms are simply stored in a vector. */ public static final int TERM_THRESHOLD = 16; /** A special value denoting that the weight length is unknown, and should be computed using * the maximum length of a term. */ public static final int WEIGHT_UNKNOWN = -1; /** A special value denoting that the weight length is unknown, and should be computed assuming * that the terms appear in lexicographic order. */ public static final int WEIGHT_UNKNOWN_SORTED_TERMS = -2; /** The number of buckets. */ final protected int n; /** The number of vertices of the intermediate hypergraph. */ final protected int m; /** {@link #m} &minus; 1. */ final protected int mMinus1; /** {@link #m} &minus; 2. */ final protected int mMinus2; /** Initialisation values for the intermediate hash functions. */ final protected int init[]; /** Vector of weights to compute the first intermediate hash function. */ final protected int[] weight0; /** Vector of weights to compute the second intermediate hash function. */ final protected int[] weight1; /** Vector of weights to compute the third intermediate hash function. */ final protected int[] weight2; /** The length of the components of the weight vectors (it's faster than asking the length of the vectors). */ final protected int weightLength; /** The final magick&mdash;the list of modulo-3 values that define the output of the minimal hash function. */ protected transient LongBigList bits; /** The bit array supporting {@link #bits}. */ final protected long[] array; /** The support array used for constant-time ranking. */ final protected long rank8[]; /** Four times the number of buckets. */ protected transient long n4; /** If {@link #n} is smaller than {@link #TERM_THRESHOLD}, a vector containing the terms. */ protected transient CharSequence[] t; public static final long serialVersionUID = 1L; /* The following three methods MUST be kept synchronised. The reason why we duplicate code is * that we do not want the overhead of allocating an array when searching for a string. * * Note that we don't use shift-add-xor hash functions (as in BloomFilter). They are significantly * slower, and in this case (in which we certainly have enough weights to disambiguate any pair * of strings) they are not particularly advantageous. */ /** Hashes a given term using the intermediate hash functions. * * @param term a term to hash. * @param h a three-element vector that will be filled with the three intermediate hash values. */ protected void hash( final CharSequence term, final int[] h ) { int h0 = init[ 0 ], h1 = init[ 1 ], h2 = init[ 2 ]; // We need three these values to map correctly the empty string char c; int i = term.length(); if ( weightLength < i ) i = weightLength; while( i c = term.charAt( i ); h0 ^= weight0[ i ] * c; h1 ^= weight1[ i ] * c; h2 ^= weight2[ i ] * c; } h0 = ( h0 & 0x7FFFFFFF ) % m; h1 = h0 + ( h1 & 0x7FFFFFFF ) % mMinus1 + 1; h2 = h0 + ( h2 & 0x7FFFFFFF ) % mMinus2 + 1; if ( h2 >= h1 ) h2++; h1 %= m; h2 %= m; h[ 0 ] = h0; h[ 1 ] = h1; h[ 2 ] = h2; } /** Hashes a given term. * * @param term a term to be hashed. * @return the position of the given term in the generating collection, starting from 0. If the * term was not in the original collection, the result is a random position. * */ public int getNumber( final CharSequence term ) { if ( t != null ) return getFromT( term ); int h0 = init[ 0 ], h1 = init[ 1 ], h2 = init[ 2 ]; // We need three these values to map correctly the empty string char c; int i = term.length(); if ( weightLength < i ) i = weightLength; while( i c = term.charAt( i ); h0 ^= weight0[ i ] * c; h1 ^= weight1[ i ] * c; h2 ^= weight2[ i ] * c; } h0 = ( h0 & 0x7FFFFFFF ) % m; h1 = h0 + ( h1 & 0x7FFFFFFF ) % mMinus1 + 1; h2 = h0 + ( h2 & 0x7FFFFFFF ) % mMinus2 + 1; if ( h2 >= h1 ) h2++; h1 %= m; h2 %= m; i = (int)( ( bits.getLong( h0 ) + bits.getLong( h1 ) + bits.getLong( h2 ) ) % 3 ); return rank( i == 0 ? h0 : i == 1 ? h1 : h2 ); } /** * Hashes a given term. * * @param term * a term to be hashed. * @return the position of the given term in the generating collection, * starting from 0. If the term was not in the original collection, * the result is a random position. */ public int getNumber( final MutableString term ) { if ( t != null ) return getFromT( term ); int h0 = init[ 0 ], h1 = init[ 1 ], h2 = init[ 2 ]; // We need three these values to map correctly the empty string char c; int i = term.length(); final char[] a = term.array(); if ( weightLength < i ) i = weightLength; while( i c = a[ i ]; h0 ^= weight0[ i ] * c; h1 ^= weight1[ i ] * c; h2 ^= weight2[ i ] * c; } h0 = ( h0 & 0x7FFFFFFF ) % m; h1 = h0 + ( h1 & 0x7FFFFFFF ) % mMinus1 + 1; h2 = h0 + ( h2 & 0x7FFFFFFF ) % mMinus2 + 1; if ( h2 >= h1 ) h2++; h1 %= m; h2 %= m; i = (int)( ( bits.getLong( h0 ) + bits.getLong( h1 ) + bits.getLong( h2 ) ) % 3 ); return rank( i == 0 ? h0 : i == 1 ? h1 : h2 ); } /** Hashes a term given as a byte-array fragment interpreted in the ISO-8859-1 charset encoding. * * @param a a byte array. * @param off the first valid byte in <code>a</code>. * @param len the number of bytes composing the term, starting at <code>off</code>. * @return the position of term defined by <code>len</code> bytes starting at <code>off</code> (interpreted * as ISO-8859-1 characters) in the generating collection, starting from 0. If the * term was not in the original collection, the result is a random position. */ public int getNumber( final byte[] a, final int off, final int len ) { if ( t != null ) try { return getFromT( new String( a, off, len, "ISO-8859-1" ) ); } catch ( UnsupportedEncodingException cantHappen ) { throw new RuntimeException( cantHappen ); } int h0 = init[ 0 ], h1 = init[ 1 ], h2 = init[ 2 ]; // We need three these values to map correctly the empty string int c; int i = len; if ( weightLength < i ) i = weightLength; while( i c = a[ off + i ] & 0xFF; h0 ^= weight0[ i ] * c; h1 ^= weight1[ i ] * c; h2 ^= weight2[ i ] * c; } h0 = ( h0 & 0x7FFFFFFF ) % m; h1 = h0 + ( h1 & 0x7FFFFFFF ) % mMinus1 + 1; h2 = h0 + ( h2 & 0x7FFFFFFF ) % mMinus2 + 1; if ( h2 >= h1 ) h2++; h1 %= m; h2 %= m; i = (int)( ( bits.getLong( h0 ) + bits.getLong( h1 ) + bits.getLong( h2 ) ) % 3 ); return rank( i == 0 ? h0 : i == 1 ? h1 : h2 ); } /** Hashes a term given as a byte array interpreted in the ISO-8859-1 charset encoding. * * @param a a byte array. * @return the position of term defined by the bytes in a <code>a</code> (interpreted * as ISO-8859-1 characters) in the generating collection, starting from 0. If the * term was not in the original collection, the result is a random position. */ public int getNumber( final byte[] a ) { return getNumber( a, 0, a.length ); } /** Gets a term out of the stored array {@link #t}. * * <P>Note: This method does not check for {@link #t} being non-<code>null</code>. * * @param term a term. * @return the position of the given term in the generating collection, starting from 0. If the * term was not in the original collection, the result is 0. */ protected int getFromT( final CharSequence term ) { int i = n; /* Note that we invoke equality *on the stored MutableString*. This * is essential due to the known weaknesses in CharSequence's contract. */ while( i-- != 0 ) if ( t[ i ].equals( term ) ) return i; return 0; } /** Returns the length of the weight vectors. * * @return the length of weight vectors used in this table. */ public int weightLength() { return weightLength; } /** Returns the number of terms hashed. * * @return the number of terms hashed. */ public int size() { return n; } public boolean hasTerms() { return false; } /** Creates a new order-preserving minimal perfect hash table for the given * terms, using as many weights as the longest term in the collection. * * <P><strong>Caution:</strong> if the collection contains twice the same * term, this constructor will never return. * * @param terms some terms to hash; it is assumed that there are no duplicates. */ public MinimalPerfectHash( final Iterable<? extends CharSequence> terms ) { this( terms, WEIGHT_UNKNOWN ); } /** Creates a new order-preserving minimal perfect hash table for the * given terms using the given number of weights. * * <P>This constructor can be used to force the use of a reduced number of weights if you are sure that * the first <code>weightLength</code> characters of each term in <code>terms</code> are * distinct. * * <P>If you do not know your weight length in advance, you can pass two * special values as <code>weightLength</code>: {@link #WEIGHT_UNKNOWN} * will force the computation of <code>weightLength</code> as the maximum * length of a term, whereas {@link #WEIGHT_UNKNOWN_SORTED_TERMS} forces * the assumption that terms are sorted: in this case, we search for * the minimum prefix that will disambiguate all terms in the collection * (a shorter prefix yields faster lookups). * * <P><strong>Caution:</strong> if two terms in the collection have a * common prefix of length <code>weightLength</code> this constructor will * never return. * * @param terms some terms to hash; if <code>weightLength</code> * is specified explicitly, it is assumed that there are no terms with a common prefix of * <code>weightLength</code> characters. * @param weightLength the number of weights used generating the * intermediate hash functions, {@link #WEIGHT_UNKNOWN} or {@link #WEIGHT_UNKNOWN_SORTED_TERMS}. * @see #MinimalPerfectHash(Iterable) */ @SuppressWarnings("unused") // TODO: move it to the first for loop when javac has been fixed public MinimalPerfectHash( final Iterable<? extends CharSequence> terms, int weightLength ) { if ( weightLength != WEIGHT_UNKNOWN && weightLength != WEIGHT_UNKNOWN_SORTED_TERMS && weightLength <= 0 ) throw new IllegalArgumentException( "Non-positive weight length: " + weightLength ); // First of all we compute the size, either by size(), if possible, or simply by iterating. if ( terms instanceof Collection) n = ((Collection<? extends CharSequence>)terms).size(); else { int c = 0; // Do not add a suppression annotation--it breaks javac for( CharSequence o: terms ) c++; n = c; } n4 = n * 4; m = ( (int)Math.ceil( n * ENLARGEMENT_FACTOR ) + BITS_PER_BLOCK - 1 ) & -BITS_PER_BLOCK; mMinus1 = m - 1; mMinus2 = m - 2; LongArrayBitVector bitVector = LongArrayBitVector.getInstance( m * 2 ); bits = bitVector.asLongBigList( 2 ); bits.size( m ); array = bitVector.bits(); if ( weightLength < 0 ) { LOGGER.info( "Computing weight length..." ); Iterator<? extends CharSequence> i = terms.iterator(); int maxLength = Integer.MIN_VALUE, minPrefixLength = Integer.MIN_VALUE; if ( i.hasNext() ) { CharSequence currTerm; MutableString prevTerm = new MutableString( i.next() ); // We cannot assume that the string will persist after a call to next(). int k, prevLength = prevTerm.length(), currLength; maxLength = prevLength; while( i.hasNext() ) { currTerm = i.next(); currLength = currTerm.length(); if ( weightLength == WEIGHT_UNKNOWN_SORTED_TERMS ) { for( k = 0; k < prevLength && k < currLength && currTerm.charAt( k ) == prevTerm.charAt( k ); k++ ); if ( k == currLength && k == prevLength ) throw new IllegalArgumentException( "The term list contains a duplicate (" + currTerm + ")" ); minPrefixLength = Math.max( minPrefixLength, k + 1 ); prevTerm.replace( currTerm ); // We cannot assume that the string will persist after a call to next(). prevLength = currLength; } maxLength = Math.max( maxLength, currLength ); } } weightLength = weightLength == WEIGHT_UNKNOWN_SORTED_TERMS ? minPrefixLength : maxLength; LOGGER.info( "Completed [max term length=" + maxLength + "; weight length=" + weightLength + "]." ); } if ( weightLength < 0 ) weightLength = 0; weight0 = new int[ weightLength ]; weight1 = new int[ weightLength ]; weight2 = new int[ weightLength ]; init = new int[ 3 ]; this.weightLength = weightLength; if ( n < TERM_THRESHOLD ) { int j = 0; t = new MutableString[ n ]; for( Iterator<? extends CharSequence> i = terms.iterator(); i.hasNext(); ) t[ j++ ] = new MutableString( i.next() ); } else { t = null; new Visit( terms ); } rank8 = new long[ ( 2 * m / BITS_PER_BLOCK ) * 2 ]; long c = 0, s = 0; for( int i = 0; i < 2 * m / Long.SIZE; i++ ) { if ( ( i & 7 ) == 0 ) rank8[ i / 8 * 2 ] = s = c; else rank8[ i / 8 * 2 + 1 ] |= ( c - s ) << ( i & 7 ) * 8; c += countNonzeroPairs( array[ i ] ); } if ( DEBUG ) { int k = 0; for( int i = 0; i < m; i++ ) { assert rank( i ) == k : "(" + i + ") " + k + " != " + rank( 2 * i ); if ( bits.getLong( i ) != 0 ) k++; } } } public static int countNonzeroPairs( final long x ) { long byteSums = ( x | x >>> 1 ) & 0x5 * Fast.ONES_STEP_4; byteSums = ( byteSums & 3 * Fast.ONES_STEP_4 ) + ( ( byteSums >>> 2 ) & 3 * Fast.ONES_STEP_4 ); byteSums = ( byteSums + ( byteSums >>> 4 ) ) & 0x0f * Fast.ONES_STEP_8; return (int)( byteSums * Fast.ONES_STEP_8 >>> 56 ); } public int rank( long x ) { x = 2 * x; return (int)( rank8[ (int)( ( x / BITS_PER_BLOCK ) * 2 ) ] + ( rank8[ (int)( ( x / BITS_PER_BLOCK ) * 2 + 1 ) ] >> ( x / Long.SIZE & 7 ) * 8 & 0xFF ) + ( x % Long.SIZE == 0 ? 0 : countNonzeroPairs( array[ (int)( x / Long.SIZE ) ] & -1L << Long.SIZE - x % Long.SIZE ) ) ); } /** Creates a new order-preserving minimal perfect hash table for the (possibly <samp>gzip</samp>'d) given file * of terms using the given number of weights. * * @param termFile an file containing one term on each line; it is assumed that * it does not contain terms with a common prefix of * <code>weightLength</code> characters. * @param encoding the encoding of <code>termFile</code>; if <code>null</code>, it * is assumed to be the platform default encoding. * @param weightLength the number of weights used generating the * intermediate hash functions, {@link #WEIGHT_UNKNOWN} or {@link #WEIGHT_UNKNOWN_SORTED_TERMS}. * @param zipped if true, the provided file is zipped and will be opened using a {@link GZIPInputStream}. * @see #MinimalPerfectHash(Iterable, int) */ public MinimalPerfectHash( final String termFile, final String encoding, int weightLength, boolean zipped ) { this( new FileLinesCollection( termFile, encoding, zipped ), weightLength ); } /** Creates a new order-preserving minimal perfect hash table for the (possibly <samp>gzip</samp>'d) given file * of terms. * * @param termFile an file containing one term on each line; it is assumed that * it does not contain terms with a common prefix of * <code>weightLength</code> characters. * @param encoding the encoding of <code>termFile</code>; if <code>null</code>, it * is assumed to be the platform default encoding. * @param zipped if true, the provided file is zipped and will be opened using a {@link GZIPInputStream}. * @see #MinimalPerfectHash(Iterable, int) */ public MinimalPerfectHash( final String termFile, final String encoding, boolean zipped ) { this( termFile, encoding, WEIGHT_UNKNOWN, zipped ); } /** Creates a new order-preserving minimal perfect hash table for the given file * of terms using the given number of weights. * * @param termFile an file containing one term on each line; it is assumed that * it does not contain terms with a common prefix of * <code>weightLength</code> characters. * @param encoding the encoding of <code>termFile</code>; if <code>null</code>, it * is assumed to be the platform default encoding. * @param weightLength the number of weights used generating the * intermediate hash functions, {@link #WEIGHT_UNKNOWN} or {@link #WEIGHT_UNKNOWN_SORTED_TERMS}. * @see #MinimalPerfectHash(Iterable, int) */ public MinimalPerfectHash( final String termFile, final String encoding, int weightLength ) { this( new FileLinesCollection( termFile, encoding ), weightLength ); } /** Creates a new order-preserving minimal perfect hash table for the given file * of terms. * * @param termFile an file containing one term on each line; it is assumed that * it does not contain terms with a common prefix of * <code>weightLength</code> characters. * @param encoding the encoding of <code>termFile</code>; if <code>null</code>, it * is assumed to be the platform default encoding. * @see #MinimalPerfectHash(Iterable, int) */ public MinimalPerfectHash( final String termFile, final String encoding ) { this( termFile, encoding, WEIGHT_UNKNOWN, false ); } /** Creates a new minimal perfect hash by copying a given one; non-transient fields are (shallow) copied. * * @param mph the perfect hash to be copied. */ protected MinimalPerfectHash( final MinimalPerfectHash mph ) { this.n = mph.n; this.m = mph.m; this.mMinus1 = mph.mMinus1; this.mMinus2 = mph.mMinus2; this.weightLength = mph.weightLength; this.weight0 = mph.weight0; this.weight1 = mph.weight1; this.weight2 = mph.weight2; this.init = mph.init; this.bits = mph.bits; this.array = mph.array; this.rank8 = mph.rank8; this.n4 = mph.n4; this.t = mph.t; } /** The internal state of a visit. */ private class Visit { /** An 3&times;n array recording the triple of vertices involved in each hyperedge. It is *reversed* w.r.t. what you would expect to reduce object creation. */ final int[][] edge = new int[ 3 ][ n ]; /** Whether a hyperedge has been already removed. */ final boolean[] removed = new boolean[ n ]; /** For each vertex of the intermediate hypergraph, the vector of incident hyperedges. */ final int[] inc = new int[ m * 3 ]; /** The next position to fill in the respective incidence vector. * Used also to store the hyperedge permutation and speed up permute(). */ final int[] last = new int[ m ]; /** For each vertex of the intermediate hypergraph, the offset into * the vector of incident hyperedges. Used also to speed up permute(). */ final int[] incOffset = new int[ m ]; /** The hyperedge stack. Used also to invert the hyperedge permutation. */ final int[] stack = new int[ n ]; /** The degree of each vertex of the intermediate hypergraph. */ final int[] d = new int[ m ]; /** Initial top of the hyperedge stack. */ int top; public Visit( final Iterable<? extends CharSequence> terms ) { // We cache all variables for faster access final int[][] edge = this.edge; final int[] last = this.last; final int[] inc = this.inc; final int[] incOffset = this.incOffset; final int[] stack = this.stack; final int[] d = this.d; final MersenneTwister r = new MersenneTwister( new Date() ); int i, j, k, s, v = -1; final int[] h = new int[ 3 ]; do { LOGGER.info( "Generating random hypergraph..." ); top = 0; init[ 0 ] = r.nextInt(); init[ 1 ] = r.nextInt(); init[ 2 ] = r.nextInt(); /* We choose the random weights for the three intermediate hash functions. */ for ( i = 0; i < weightLength; i++ ) { weight0[ i ] = r.nextInt(); weight1[ i ] = r.nextInt(); weight2[ i ] = r.nextInt(); } /* We build the hyperedge list, checking that we do not create a degenerate hyperedge. */ i = 0; CharSequence cs = null; IntArrays.fill( d, 0 ); for( Iterator<? extends CharSequence> w = terms.iterator(); w.hasNext(); ) { hash( cs = w.next(), h ); if ( h[ 0 ] == h[ 1 ] || h[ 1 ] == h[ 2 ] || h[ 2 ] == h[ 0 ] ) break; edge[ 0 ][ i ] = h[ 0 ]; edge[ 1 ][ i ] = h[ 1 ]; edge[ 2 ][ i ] = h[ 2 ]; i++; } if ( i < n ) { LOGGER.info( "Hypergraph generation interrupted by degenerate hyperedge " + i + " (string: \"" + cs + "\")." ); continue; } /* We compute the degree of each vertex. */ for( j = 0; j < 3; j++ ) { i = n; while( i-- != 0 ) d[ edge[ j ][ i ] ]++; } LOGGER.info( "Checking for duplicate hyperedges..." ); /* Now we quicksort hyperedges lexicographically, keeping into last their permutation. */ i = n; while( i-- != 0 ) last[ i ] = i; GenericSorting.quickSort( 0, n, new IntComparator() { public int compare( final int x, final int y ) { int r; if ( ( r = edge[ 0 ][ x ] - edge[ 0 ][ y ] ) != 0 ) return r; if ( ( r = edge[ 1 ][ x ] - edge[ 1 ][ y ] ) != 0 ) return r; return edge[ 2 ][ x ] - edge[ 2 ][ y ]; } }, new Swapper() { public void swap( final int x, final int y ) { int e0 = edge[ 0 ][ x ], e1 = edge[ 1 ][ x ], e2 = edge[ 2 ][ x ], p = last[ x ]; edge[ 0 ][ x ] = edge[ 0 ][ y ]; edge[ 1 ][ x ] = edge[ 1 ][ y ]; edge[ 2 ][ x ] = edge[ 2 ][ y ]; edge[ 0 ][ y ] = e0; edge[ 1 ][ y ] = e1; edge[ 2 ][ y ] = e2; last[ x ] = last[ y ]; last[ y ] = p; } } ); i = n - 1; while( i-- != 0 ) if ( edge[ 0 ][ i + 1 ] == edge[ 0 ][ i ] && edge[ 1 ][ i + 1 ] == edge[ 1 ][ i ] && edge[ 2 ][ i + 1 ] == edge[ 2 ][ i ]) break; if ( i != -1 ) { LOGGER.info( "Found double hyperedge for terms " + last[ i + 1 ] + " and " + last[ i ] + "." ); continue; } /* We now invert last and permute all hyperedges back into their place. Note that * we use last and incOffset to speed up the process. */ i = n; while( i-- != 0 ) stack[ last[ i ] ] = i; GenericPermuting.permute( stack, new Swapper() { public void swap( final int x, final int y ) { int e0 = edge[ 0 ][ x ], e1 = edge[ 1 ][ x ], e2 = edge[ 2 ][ x ]; edge[ 0 ][ x ] = edge[ 0 ][ y ]; edge[ 1 ][ x ] = edge[ 1 ][ y ]; edge[ 2 ][ x ] = edge[ 2 ][ y ]; edge[ 0 ][ y ] = e0; edge[ 1 ][ y ] = e1; edge[ 2 ][ y ] = e2; } }, last, incOffset ); LOGGER.info( "Visiting hypergraph..." ); /* We set up the offset of each vertex in the incidence vector. This is necessary to avoid creating m incidence vectors at each round. */ IntArrays.fill( last, 0 ); incOffset[ 0 ] = 0; for( i = 1; i < m; i++ ) incOffset[ i ] = incOffset[ i - 1 ] + d[ i - 1 ]; /* We fill the vector. */ for( i = 0; i < n; i++ ) for( j = 0; j < 3; j++ ) { v = edge[ j ][ i ]; inc[ incOffset[ v ] + last[ v ]++ ] = i; } /* We visit the hypergraph. */ BooleanArrays.fill( removed, false ); for( i = 0; i < m; i++ ) if ( d[ i ] == 1 ) visit( i ); if ( top == n ) LOGGER.info( "Visit completed." ); else LOGGER.info( "Visit failed: stripped " + top + " hyperedges out of " + n + "." ); } while ( top != n ); LOGGER.info( "Assigning values..." ); /* We assign values. */ /** Whether a specific node has already been used as perfect hash value for an item. */ final BitVector used = LongArrayBitVector.getInstance( m ); used.length( m ); int value; while( top > 0 ) { k = stack[ --top ]; s = 0; for ( j = 0; j < 3; j++ ) { if ( ! used.getBoolean( edge[ j ][ k ] ) ) v = j; else s += bits.getLong( edge[ j ][ k ] ); used.set( edge[ j ][ k ] ); } value = ( v - s + 9 ) % 3; bits.set( edge[ v ][ k ], value == 0 ? 3 : value ); } LOGGER.info( "Completed." ); } /* This is the original recursive visit. It is here for documentation purposes. It cannot handle more than about 1,000,000 terms. private void visit( int x ) { int i, j, k = -1; for( i = 0; i < last[x]; i++ ) if ( !removed[ k = ((int[])inc[x])[i] ] ) break; // The only hyperedge incident on x in the current configuration. stack[top++] = k; // We update the degrees and the incidence lists. removed[k] = true; for( i = 0; i < 3; i++ ) d[edge[i][k]]--; // We follow recursively the other vertices of the hyperedge, if they have degree one in the current configuration. for( i = 0; i < 3; i++ ) if ( edge[i][k] != x && d[edge[i][k]] == 1 ) visit( edge[i][k] ); } */ final int[] recStackI = new int[ n ]; // The stack for i. final int[] recStackK = new int[ n ]; // The stack for k. private void visit( int x ) { // We cache all variables for faster access final int[] recStackI = this.recStackI; final int[] recStackK = this.recStackK; final int[][] edge = this.edge; final int[] last = this.last; final int[] inc = this.inc; final int[] incOffset = this.incOffset; final int[] stack = this.stack; final int[] d = this.d; final boolean[] removed = this.removed; int i, k = -1; boolean inside; // Stack initialization int recTop = 0; // Initial top of the recursion stack. inside = false; while ( true ) { if ( ! inside ) { for ( i = 0; i < last[ x ]; i++ ) if ( !removed[ k = inc[ incOffset[ x ] + i ] ] ) break; // The only hyperedge incident on x in the current configuration. // TODO: k could be wrong if the graph is regular and cyclic. stack[ top++ ] = k; /* We update the degrees and the incidence lists. */ removed[ k ] = true; for ( i = 0; i < 3; i++ ) d[ edge[ i ][ k ] ] } /* We follow recursively the other vertices of the hyperedge, if they have degree one in the current configuration. */ for( i = 0; i < 3; i++ ) if ( edge[ i ][ k ] != x && d[ edge[ i ][ k ] ] == 1 ) { recStackI[ recTop ] = i + 1; recStackK[ recTop ] = k; recTop++; x = edge[ i ][ k ]; inside = false; break; } if ( i < 3 ) continue; if ( --recTop < 0 ) return; i = recStackI[ recTop ]; k = recStackK[ recTop ]; inside = true; } } } private void writeObject( final ObjectOutputStream s ) throws IOException { s.defaultWriteObject(); if ( n < TERM_THRESHOLD ) s.writeObject( t ); } private void readObject( final ObjectInputStream s ) throws IOException, ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException { s.defaultReadObject(); n4 = n * 4; bits = LongArrayBitVector.wrap( array, m * 2 ).asLongBigList( 2 ); if ( n < TERM_THRESHOLD ) t = (CharSequence[])s.readObject(); } /** A main method for minimal perfect hash construction that accepts a default class. * * @param klass the default class to be built. * @param arg the usual argument array. */ @SuppressWarnings("unused") protected static void main( final Class<? extends MinimalPerfectHash> klass, final String[] arg ) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException, JSAPException, ClassNotFoundException { final SimpleJSAP jsap = new SimpleJSAP( klass.getName(), "Builds a minimal perfect hash table reading a newline-separated list of terms.", new Parameter[] { new FlaggedOption( "bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b', "buffer-size", "The size of the I/O buffer used to read terms." ), new FlaggedOption( "class", JSAP.CLASS_PARSER, klass.getName(), JSAP.NOT_REQUIRED, 'c', "class", "A subclass of MinimalPerfectHash to be used when creating the table." ), new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The term file encoding." ), new Switch( "zipped", 'z', "zipped", "The term list is compressed in gzip format." ), new Switch( "sorted", 's', "sorted", "The term list is sorted--optimise weight length." ), new FlaggedOption( "termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "offline", "Read terms from this file (without loading them into core memory) instead of standard input." ), new UnflaggedOption( "table", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised minimal perfect hash table." ) }); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final int bufferSize = jsapResult.getInt( "bufferSize" ); final String tableName = jsapResult.getString( "table" ); final String termFile = jsapResult.getString( "termFile" ); final Class<?> tableClass = jsapResult.getClass( "class" ); final Charset encoding = (Charset)jsapResult.getObject( "encoding" ); final boolean sorted = jsapResult.getBoolean( "sorted" ); final boolean zipped = jsapResult.getBoolean( "zipped" ); final MinimalPerfectHash minimalPerfectHash; if ( termFile == null ) { ArrayList<MutableString> termList = new ArrayList<MutableString>(); final ProgressLogger pl = new ProgressLogger( LOGGER ); pl.itemsName = "terms"; final LineIterator termIterator = new LineIterator( new FastBufferedReader( new InputStreamReader( System.in, encoding ), bufferSize ), pl ); pl.start( "Reading terms..." ); while( termIterator.hasNext() ) termList.add( termIterator.next().copy() ); pl.done(); LOGGER.info( "Building minimal perfect hash table..." ); minimalPerfectHash = (MinimalPerfectHash)tableClass.getConstructor( Iterable.class, int.class ).newInstance( termList, Integer.valueOf( sorted ? WEIGHT_UNKNOWN_SORTED_TERMS : WEIGHT_UNKNOWN ) ); } else { LOGGER.info( "Building minimal perfect hash table..." ); minimalPerfectHash = (MinimalPerfectHash)tableClass.getConstructor( String.class, String.class, int.class, boolean.class ).newInstance( termFile, encoding.toString(), Integer.valueOf( sorted ? WEIGHT_UNKNOWN_SORTED_TERMS : WEIGHT_UNKNOWN ), Boolean.valueOf( zipped ) ); } LOGGER.info( "Writing to file..." ); BinIO.storeObject( minimalPerfectHash, tableName ); LOGGER.info( "Completed." ); } public static void main( final String[] arg ) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException, JSAPException, ClassNotFoundException { main( MinimalPerfectHash.class, arg ); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.util.*; import java.io.*; /** * @author Torsten Hildebrandt. */ public class ReferenceManagerTest extends TestCase { Properties props = new Properties(); TestEngine engine; ReferenceManager mgr; public ReferenceManagerTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( TestEngine.findTestProperties() ); props.setProperty( "jspwiki.translatorReader.matchEnglishPlurals", "true"); // We must make sure that the reference manager cache is cleaned first. String workDir = props.getProperty( "jspwiki.workDir" ); if( workDir != null ) { File refmgrfile = new File( workDir, "refmgr.ser" ); if( refmgrfile.exists() ) refmgrfile.delete(); } engine = new TestEngine(props); engine.saveText( "TestPage", "Reference to [Foobar]." ); engine.saveText( "Foobar", "Reference to [Foobar2], [Foobars], [Foobar]" ); mgr = engine.getReferenceManager(); } public void tearDown() throws Exception { engine.deletePage( "TestPage" ); engine.deletePage( "Foobar" ); engine.deletePage( "Foobars" ); engine.deletePage( "Foobar2" ); engine.deletePage( "Foobar2s" ); engine.deletePage( "BugCommentPreviewDeletesAllComments" ); engine.deletePage( "FatalBugs" ); engine.deletePage( "RandomPage" ); engine.deletePage( "NewBugs" ); engine.deletePage( "OpenBug" ); engine.deletePage( "OpenBugs" ); engine.deletePage( "NewBug" ); engine.deletePage( "BugOne" ); engine.deletePage( "BugTwo" ); } public void testNonExistant1() throws Exception { Collection c = mgr.findReferrers("Foobar2"); assertTrue( c.size() == 1 && c.contains("Foobar") ); } public void testNonExistant2() { Collection c = mgr.findReferrers("TestBug"); assertNull( c ); } public void testRemove() throws Exception { Collection c = mgr.findReferrers("Foobar2"); assertTrue( c.size() == 1 && c.contains("Foobar") ); engine.deletePage( "Foobar" ); c = mgr.findReferrers("Foobar2"); assertNull( c ); engine.saveText( "Foobar", "[Foobar2]"); c = mgr.findReferrers("Foobar2"); assertTrue( c.size() == 1 && c.contains("Foobar") ); } public void testUnreferenced() throws Exception { Collection c = mgr.findUnreferenced(); assertTrue( "Unreferenced page not found by ReferenceManager", Util.collectionContains( c, "TestPage" )); } public void testBecomesUnreferenced() throws Exception { engine.saveText( "Foobar2", "[TestPage]" ); Collection c = mgr.findUnreferenced(); assertEquals( "Wrong # of orphan pages, stage 1", 0, c.size() ); engine.saveText( "Foobar2", "norefs" ); c = mgr.findUnreferenced(); assertEquals( "Wrong # of orphan pages", 1, c.size() ); Iterator i = c.iterator(); String first = (String) i.next(); assertEquals( "Not correct referrers", "TestPage", first ); } public void testUncreated() throws Exception { Collection c = mgr.findUncreated(); assertTrue( c.size()==1 && ((String) c.iterator().next()).equals("Foobar2") ); } public void testReferrers() throws Exception { Collection c = mgr.findReferrers( "TestPage" ); assertNull( "TestPage referrers", c ); c = mgr.findReferrers( "Foobar" ); assertTrue( "Foobar referrers", c.size()==1 && ((String) c.iterator().next()).equals("TestPage") ); c = mgr.findReferrers( "Foobar2" ); assertTrue( "Foobar2 referrers", c.size()==1 && ((String) c.iterator().next()).equals("Foobar") ); c = mgr.findReferrers( "Foobars" ); assertEquals( "Foobars referrers", 1, c.size() ); assertEquals( "Foobars referrer 'TestPage'", "TestPage", (String) c.iterator().next() ); } public void testRefersTo() throws Exception { Collection s = mgr.findRefersTo( "Foobar" ); assertTrue( "does not have Foobar", s.contains("Foobar") ); // assertTrue( "does not have Foobars", s.contains("Foobars") ); assertTrue( "does not have Foobar2", s.contains("Foobar2") ); } /** * Should fail in 2.2.14-beta * @throws Exception */ public void testSingularReferences() throws Exception { engine.saveText( "RandomPage", "FatalBugs" ); engine.saveText( "FatalBugs", "<foo>" ); engine.saveText( "BugCommentPreviewDeletesAllComments", "FatalBug" ); Collection c = mgr.findReferrers( "FatalBugs" ); assertEquals( "FatalBugs referrers number", 2, c.size() ); } /** * Is a page recognized as referenced if only plural form links exist. */ // NB: Unfortunately, cleaning out self-references in the case there's // a plural and a singular form of the page becomes nigh impossible, so we // just don't do it. public void testUpdatePluralOnlyRef() throws Exception { engine.saveText( "TestPage", "Reference to [Foobars]." ); Collection c = mgr.findUnreferenced(); assertTrue( "Foobar unreferenced", c.size()==1 && ((String) c.iterator().next()).equals("TestPage") ); c = mgr.findReferrers( "Foobar" ); Iterator it = c.iterator(); String s1 = (String)it.next(); assertTrue( "Foobar referrers", c.size()==1 && s1.equals("TestPage") ); } /** * Opposite to testUpdatePluralOnlyRef(). Is a page with plural form recognized as * the page referenced by a singular link. */ public void testUpdateFoobar2s() throws Exception { engine.saveText( "Foobar2s", "qwertz" ); assertTrue( "no uncreated", mgr.findUncreated().size()==0 ); Collection c = mgr.findReferrers( "Foobar2s" ); assertTrue( "referrers", c!=null && c.size()==1 && ((String) c.iterator().next()).equals("Foobar") ); } public void testUpdateBothExist() throws Exception { engine.saveText( "Foobars", "qwertz" ); Collection c = mgr.findReferrers( "Foobars" ); assertEquals( "Foobars referrers", 1, c.size() ); assertEquals( "Foobars referrer is not TestPage", "TestPage", ((String) c.iterator().next()) ); } public void testUpdateBothExist2() throws Exception { engine.saveText( "Foobars", "qwertz" ); engine.saveText( "TestPage", "Reference to [Foobar], [Foobars]." ); Collection c = mgr.findReferrers( "Foobars" ); assertEquals( "Foobars referrers count", 1, c.size() ); Iterator i = c.iterator(); String first = (String) i.next(); assertTrue( "Foobars referrers", first.equals("TestPage") ); } public void testCircularRefs() throws Exception { engine.saveText( "Foobar2", "ref to [TestPage]" ); assertTrue( "no uncreated", mgr.findUncreated().size()==0 ); assertTrue( "no unreferenced", mgr.findUnreferenced().size()==0 ); } public void testPluralSingularUpdate1() throws Exception { engine.saveText( "BugOne", "NewBug" ); engine.saveText( "NewBugs", "foo" ); engine.saveText( "OpenBugs", "bar" ); engine.saveText( "BugOne", "OpenBug" ); Collection ref = mgr.findReferrers( "NewBugs" ); assertNull("newbugs",ref); // No referrers must be found ref = mgr.findReferrers( "NewBug" ); assertNull("newbug",ref); // No referrers must be found ref = mgr.findReferrers( "OpenBugs" ); assertEquals("openbugs",1,ref.size()); assertEquals("openbugs2","BugOne",ref.iterator().next()); ref = mgr.findReferrers( "OpenBug" ); assertEquals("openbug",1,ref.size()); assertEquals("openbug2","BugOne",ref.iterator().next()); } public void testPluralSingularUpdate2() throws Exception { engine.saveText( "BugOne", "NewBug" ); engine.saveText( "NewBug", "foo" ); engine.saveText( "OpenBug", "bar" ); engine.saveText( "BugOne", "OpenBug" ); Collection ref = mgr.findReferrers( "NewBugs" ); assertNull("newbugs",ref); // No referrers must be found ref = mgr.findReferrers( "NewBug" ); assertNull("newbug",ref); // No referrers must be found ref = mgr.findReferrers( "OpenBugs" ); assertEquals("openbugs",1,ref.size()); assertEquals("openbugs2","BugOne",ref.iterator().next()); ref = mgr.findReferrers( "OpenBug" ); assertEquals("openbug",1,ref.size()); assertEquals("openbug2","BugOne",ref.iterator().next()); } public void testPluralSingularUpdate3() throws Exception { engine.saveText( "BugOne", "NewBug" ); engine.saveText( "BugTwo", "NewBug" ); engine.saveText( "NewBugs", "foo" ); engine.saveText( "OpenBugs", "bar" ); engine.saveText( "BugOne", "OpenBug" ); Collection ref = mgr.findReferrers( "NewBugs" ); assertEquals("newbugs",1,ref.size()); assertEquals("newbugs2","BugTwo",ref.iterator().next()); ref = mgr.findReferrers( "NewBug" ); assertEquals("newbugs",1,ref.size()); assertEquals("newbugs2","BugTwo",ref.iterator().next()); ref = mgr.findReferrers( "OpenBugs" ); assertEquals("openbugs",1,ref.size()); assertEquals("openbugs2","BugOne",ref.iterator().next()); ref = mgr.findReferrers( "OpenBug" ); assertEquals("openbug",1,ref.size()); assertEquals("openbug2","BugOne",ref.iterator().next()); } public static Test suite() { return new TestSuite( ReferenceManagerTest.class ); } public static void main(String[] args) { junit.textui.TestRunner.main( new String[] { ReferenceManagerTest.class.getName() } ); } /** * Test method: dumps the contents of ReferenceManager link lists to stdout. * This method is NOT synchronized, and should be used in testing * with one user, one WikiEngine only. */ public static String dumpReferenceManager( ReferenceManager rm ) { StringBuffer buf = new StringBuffer(); try { buf.append( "================================================================\n" ); buf.append( "Referred By list:\n" ); Set keys = rm.getReferredBy().keySet(); Iterator it = keys.iterator(); while( it.hasNext() ) { String key = (String) it.next(); buf.append( key + " referred by: " ); Set refs = (Set)rm.getReferredBy().get( key ); Iterator rit = refs.iterator(); while( rit.hasNext() ) { String aRef = (String)rit.next(); buf.append( aRef + " " ); } buf.append( "\n" ); } buf.append( " buf.append( "Refers To list:\n" ); keys = rm.getRefersTo().keySet(); it = keys.iterator(); while( it.hasNext() ) { String key = (String) it.next(); buf.append( key + " refers to: " ); Collection refs = (Collection)rm.getRefersTo().get( key ); if(refs != null) { Iterator rit = refs.iterator(); while( rit.hasNext() ) { String aRef = (String)rit.next(); buf.append( aRef + " " ); } buf.append( "\n" ); } else buf.append("(no references)\n"); } buf.append( "================================================================\n" ); } catch(Exception e) { buf.append("Problem in dump(): " + e + "\n" ); } return( buf.toString() ); } }
package com.example; import com.google.api.services.storage.model.StorageObject; import com.google.common.collect.Iterables; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponents; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.UUID; @SpringBootApplication public class StorageDemoApplication { public static void main(String[] args) { SpringApplication.run(StorageDemoApplication.class, args); } @RestController class StorageDemoController { private final GoogleCloudPlatformManager gcpManager; public StorageDemoController(GoogleCloudPlatformManager gcpManager) { this.gcpManager = gcpManager; } @GetMapping("/") public CloudFoundryDetails getCloudFoundryDetails(@Value("${CF_INSTANCE_INDEX:0}") int instance, @Value("${cloud.application.version}") String version) { return new CloudFoundryDetails(instance, version, Iterables.size(gcpManager.getAppBucketItems())); } @RequestMapping("/upload") public StorageObject upload(HttpServletRequest req) { String url = "https: // Generate a random name for the JSON upload String objectName = UUID.randomUUID().toString().concat(".json"); // Get a snapshot of the metrics endpoint from actuator String metricsJson = new RestTemplate().getForObject(url, String.class); InputStream objectData = new ByteArrayInputStream(metricsJson.getBytes()); // Upload the metrics snapshot to Google Storage return gcpManager.uploadObject(objectName, objectData); } } }
package org.jaxen.expr; import java.util.List; import org.jaxen.Context; import org.jaxen.JaxenException; public class DefaultXPathExpr implements XPathExpr { private Expr rootExpr; public DefaultXPathExpr(Expr rootExpr) { this.rootExpr = rootExpr; } public Expr getRootExpr() { return this.rootExpr; } public void setRootExpr(Expr rootExpr) { this.rootExpr = rootExpr; } public String toString() { return "[(DefaultXPath): " + getRootExpr() + "]"; } public String getText() { return getRootExpr().getText(); } public void simplify() { setRootExpr( getRootExpr().simplify() ); } public List asList(Context context) throws JaxenException { Expr expr = getRootExpr(); Object value = expr.evaluate( context ); List result = DefaultExpr.convertToList( value ); return result; } }
package imcode.server; import java.net.*; import java.lang.reflect.Constructor; import java.io.IOException; import java.util.StringTokenizer; import java.util.Properties; import java.util.Hashtable; import imcode.util.log.*; import imcode.util.Prefs; /** * Description of the Class * *@author kreiger *@created den 30 augusti 2001 */ public class ApplicationServer { private final static String VERSION = "1.4.0 (2000-09-19 13:00)"; private final static String CONFIG_FILE = "ImcServer.cfg"; private final static int LOGINTERVAL = 10000; private final static int LOGSIZE = 16384; private final Hashtable serverObjects = new Hashtable(); private final Log log = new Log( ApplicationServer.class.toString() ); /** * Constructor for the ApplicationServer object */ public ApplicationServer() { // get list of servers StringTokenizer st = null; try { String servers = Prefs.get("Servers", CONFIG_FILE); st = new StringTokenizer(servers, " ,"); int serverObjectCount = st.countTokens(); log.log(Log.INFO, "" + serverObjectCount + " Server" + (serverObjectCount == 1 ? ": " : "s: ") + servers, null); } catch (IOException ex) { log.log(Log.EMERGENCY, "Unable to load properties from " + CONFIG_FILE, ex); throw new RuntimeException(ex.getMessage()); } catch (NullPointerException ex) { log.log(Log.EMERGENCY, "Unable to load properties from " + CONFIG_FILE, ex); throw ex; } for (int i = 0; st.hasMoreTokens(); ++i) { String servername = st.nextToken(); log.log(Log.INFO, "Reading properties for server " + servername, null); Properties serverprops = null; try { String serverpropsfile = Prefs.get(servername + ".properties", CONFIG_FILE); serverprops = Prefs.getProperties(serverpropsfile); } catch (IOException ex) { log.log(Log.CRITICAL, "Unable to load properties for server " + servername, ex); continue; } // Find out what class this object is supposed to be of. String classname = serverprops.getProperty("Class"); try { // Load the class Class objClass = Class.forName(classname); // Let's find the constructor that takes an "InetPoolManager" and a Properties. Constructor objConstructor = objClass.getConstructor(new Class[]{InetPoolManager.class, Properties.class}); // Invoke Constructor(InetPoolManager, Properties) on class serverObjects.put(servername, objConstructor.newInstance(new Object[]{new InetPoolManager(serverprops), serverprops})); } catch (ClassNotFoundException ex) { log.log(Log.CRITICAL, "Unable to find class " + classname, ex); } catch (NoSuchMethodException ex) { log.log(Log.CRITICAL, "Class " + classname + " does not have a compatible constructor " + classname + "(InetPoolManager, Properties)", ex); } catch (InstantiationException ex) { log.log(Log.CRITICAL, "Failed to invoke found constructor " + classname + "(InetPoolManager, Properties) on class " + classname, ex); } catch (IllegalAccessException ex) { log.log(Log.CRITICAL, "Failed to invoke found constructor " + classname + "(InetPoolManager, Properties) on class " + classname, ex); } catch (java.lang.reflect.InvocationTargetException ex) { log.log(Log.CRITICAL, "Failed to invoke found constructor " + classname + "(InetPoolManager, Properties) on class " + classname, ex.getTargetException()); } catch (java.sql.SQLException ex) { log.log(Log.CRITICAL, "Failed to create connectionpool and datasource for " + servername, ex); } } log.log(Log.NOTICE, "ImCMS Daemon " + VERSION, null); log.log(Log.NOTICE, "imcmsd started: " + new java.util.Date(), null); log.log(Log.NOTICE, "imcmsd running...", null); } // return server count /** * Gets the serverCount attribute of the ApplicationServer object * *@return The serverCount value */ public int getServerCount() { return serverObjects.size(); } /** * Gets the serverObject attribute of the ApplicationServer object * *@param serverObjectName Description of Parameter *@return The serverObject value */ public Object getServerObject(String serverObjectName) { return serverObjects.get(serverObjectName); } }
/* * Created at 20:17 on 11/02/2017 */ package com.example.news.feed; import com.example.news.domain.News; import java.security.SecureRandom; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author zzhao */ public class NewsSupplier implements Supplier<News> { public static final String[] HEADLINES = new String[]{ "up", "down", "rise", "fall", "good", "bad", "success", "failure", "high", "low", "über", "unter" }; private final SecureRandom random; private final List<Integer> headlineIndices; NewsSupplier() { this.random = new SecureRandom(String.valueOf(System.nanoTime()).getBytes()); this.headlineIndices = IntStream .range(0, HEADLINES.length) .mapToObj(Integer::valueOf) .collect(Collectors.toList()); } @Override public News get() { final int oneFrom100 = this.random.nextInt(100); final int priority = oneFrom100 < 7 // 7% chance to be high prio ? oneFrom100 % 5 + 5 : oneFrom100 % 5; Collections.shuffle(this.headlineIndices); return new News(priority, this.headlineIndices .subList(0, this.random.nextInt(3) + 3) .stream() .map(i -> HEADLINES[i]) .collect(Collectors.toList())); } }
package biomodel.gui.sbmlcore; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import main.Gui; import main.util.Utility; import org.sbml.jsbml.InitialAssignment; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; import org.sbml.jsbml.Parameter; import org.sbml.jsbml.ext.arrays.ArraysSBasePlugin; import org.sbml.jsbml.ext.arrays.Index; import org.sbml.jsbml.ext.comp.Port; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.Rule; import org.sbml.jsbml.SpeciesReference; import biomodel.annotation.AnnotationUtility; import biomodel.gui.schematic.ModelEditor; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.SBMLutilities; /** * This is a class for creating SBML initial assignments * * @author Chris Myers * */ public class InitialAssignments extends JPanel implements ActionListener, MouseListener { private static final long serialVersionUID = 1L; private JButton addInit, removeInit, editInit; private JList initAssigns; // JList of initial assignments private BioModel bioModel; private ModelEditor modelEditor; private JComboBox dimensionType, dimensionX, dimensionY; private JTextField iIndex, jIndex; /* Create initial assignment panel */ public InitialAssignments(BioModel bioModel, ModelEditor modelEditor) { super(new BorderLayout()); this.bioModel = bioModel; this.modelEditor = modelEditor; Model model = bioModel.getSBMLDocument().getModel(); /* Create initial assignment panel */ addInit = new JButton("Add Initial"); removeInit = new JButton("Remove Initial"); editInit = new JButton("Edit Initial"); initAssigns = new JList(); dimensionType = new JComboBox(); dimensionType.addItem("Scalar"); dimensionType.addItem("1-D Array"); dimensionType.addItem("2-D Array"); dimensionType.addActionListener(this); dimensionX = new JComboBox(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) { Parameter param = bioModel.getSBMLDocument().getModel().getParameter(i); if (param.getConstant() && !BioModel.IsDefaultParameter(param.getId())) { dimensionX.addItem(param.getId()); } } dimensionY = new JComboBox(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) { Parameter param = bioModel.getSBMLDocument().getModel().getParameter(i); if (param.getConstant() && !BioModel.IsDefaultParameter(param.getId())) { dimensionY.addItem(param.getId()); } } dimensionX.setEnabled(false); dimensionY.setEnabled(false); iIndex = new JTextField(10); jIndex = new JTextField(10); iIndex.setEnabled(false); jIndex.setEnabled(false); String[] inits = new String[model.getInitialAssignmentCount()]; for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment init = model.getInitialAssignment(i); inits[i] = init.getVariable() + " = " + SBMLutilities.myFormulaToString(init.getMath()); } String[] oldInits = inits; try { inits = sortInitRules(inits); } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in initial assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); inits = oldInits; } JPanel addRem = new JPanel(); addRem.add(addInit); addRem.add(removeInit); addRem.add(editInit); addInit.addActionListener(this); removeInit.addActionListener(this); editInit.addActionListener(this); JLabel panelLabel = new JLabel("List of Initial Assignments:"); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 220)); scroll.setPreferredSize(new Dimension(276, 152)); scroll.setViewportView(initAssigns); Utility.sort(inits); initAssigns.setListData(inits); initAssigns.setSelectedIndex(0); initAssigns.addMouseListener(this); this.add(panelLabel, "North"); this.add(scroll, "Center"); this.add(addRem, "South"); } /** * Refresh initial assingment panel */ public void refreshInitialAssignmentPanel(BioModel gcm) { Model model = gcm.getSBMLDocument().getModel(); if (model.getInitialAssignmentCount() > 0) { String[] inits = new String[model.getInitialAssignmentCount()]; for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment init = model.getListOfInitialAssignments().get(i); inits[i] = init.getVariable() + " = " + SBMLutilities.myFormulaToString(init.getMath()); } try { inits = sortInitRules(inits); if (SBMLutilities.checkCycles(gcm.getSBMLDocument())) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } initAssigns.setListData(inits); initAssigns.setSelectedIndex(0); } } /** * Remove an initial assignment */ public static void removeInitialAssignment(BioModel gcm, String variable) { ListOf<InitialAssignment> r = gcm.getSBMLDocument().getModel().getListOfInitialAssignments(); for (int i = 0; i < gcm.getSBMLDocument().getModel().getInitialAssignmentCount(); i++) { if (r.get(i).getVariable().equals(variable)) { for (int j = 0; j < gcm.getSBMLCompModel().getListOfPorts().size(); j++) { Port port = gcm.getSBMLCompModel().getListOfPorts().get(j); if (port.isSetMetaIdRef() && port.getMetaIdRef().equals(r.get(i).getMetaId())) { gcm.getSBMLCompModel().getListOfPorts().remove(j); break; } } r.remove(i); } } } /** * Try to add or edit initial assignments */ public static boolean addInitialAssignment(BioModel bioModel, String variable, String assignment, String[] dimensions) { if (assignment.trim().equals("")) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment is empty.", "Enter Assignment", JOptionPane.ERROR_MESSAGE); return true; } if (SBMLutilities.myParseFormula(assignment.trim()) == null) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment is not valid.", "Enter Valid Assignment", JOptionPane.ERROR_MESSAGE); return true; } Rule rule = bioModel.getSBMLDocument().getModel().getRule(variable); if (rule != null && rule.isAssignment()) { JOptionPane.showMessageDialog(Gui.frame, "Cannot have both an assignment rule and an initial assignment on the same variable.", "Multiple Assignment", JOptionPane.ERROR_MESSAGE); return true; } String [] dimIds = SBMLutilities.getDimensionIds("",dimensions.length-1); if(SBMLutilities.displayinvalidVariables("Rule", bioModel.getSBMLDocument(), dimIds, assignment.trim(), "", false)){ return true; } if (SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), bioModel.addBooleans(assignment.trim()))) { return true; } if (SBMLutilities.returnsBoolean(bioModel.addBooleans(assignment.trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } boolean error = false; InitialAssignment ia = bioModel.getSBMLDocument().getModel().createInitialAssignment(); String initialId = "init__"+variable; SBMLutilities.setMetaId(ia, initialId); ia.setVariable(variable); ia.setMath(bioModel.addBooleans(assignment.trim())); ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(ia); sBasePlugin.unsetListOfDimensions(); for (int i = 1; i < dimensions.length; i++) { org.sbml.jsbml.ext.arrays.Dimension dim = sBasePlugin.createDimension(dimIds[i-1]); dim.setSize(dimensions[i]); dim.setArrayDimension(i-1); Index index = sBasePlugin.createIndex(); index.setReferencedAttribute("symbol"); index.setArrayDimension(i-1); index.setMath(SBMLutilities.myParseFormula(dimIds[i-1])); } if (checkInitialAssignmentUnits(bioModel, ia)) { error = true; } if (!error && SBMLutilities.checkCycles(bioModel.getSBMLDocument())) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); error = true; } if (error) { removeInitialAssignment(bioModel, variable); } else { if (bioModel.getPortByIdRef(variable)!=null) { Port port = bioModel.getSBMLCompModel().createPort(); port.setId(GlobalConstants.INITIAL_ASSIGNMENT+"__"+variable); port.setMetaIdRef(initialId); } } return error; } /** * Check the units of an initial assignment */ public static boolean checkInitialAssignmentUnits(BioModel bioModel, InitialAssignment init) { if (init.containsUndeclaredUnits()) { if (Gui.getCheckUndeclared()) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment contains literals numbers or parameters with undeclared units.\n" + "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units", JOptionPane.WARNING_MESSAGE); } return false; } else if (Gui.getCheckUnits()) { if (SBMLutilities.checkUnitsInInitialAssignment(bioModel.getSBMLDocument(), init)) { JOptionPane.showMessageDialog(Gui.frame, "Units on the left and right-hand side of the initial assignment do not agree.", "Units Do Not Match", JOptionPane.ERROR_MESSAGE); return true; } } return false; } /** * Sort initial rules in order to be evaluated */ private static String[] sortInitRules(String[] initRules) { String[] result = new String[initRules.length]; int j = 0; boolean[] used = new boolean[initRules.length]; for (int i = 0; i < initRules.length; i++) { used[i] = false; } boolean progress; do { progress = false; for (int i = 0; i < initRules.length; i++) { if (used[i]) continue; String[] initRule = initRules[i].split(" "); boolean insert = true; for (int k = 1; k < initRule.length; k++) { for (int l = 0; l < initRules.length; l++) { if (used[l]) continue; String[] initRule2 = initRules[l].split(" "); if (initRule[k].equals(initRule2[0])) { insert = false; break; } } if (!insert) break; } if (insert) { result[j] = initRules[i]; j++; progress = true; used[i] = true; } } } while ((progress) && (j < initRules.length)); if (j != initRules.length) { throw new RuntimeException(); } return result; } /** * Try to add or edit initial assignments */ private boolean addUpdateInitialAssignment(String option, int Rindex, String variable, String assignment) { if (assignment.equals("")) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment is empty.", "Enter Assignment", JOptionPane.ERROR_MESSAGE); return true; } if (SBMLutilities.myParseFormula(assignment) == null) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment is not valid.", "Enter Valid Assignment", JOptionPane.ERROR_MESSAGE); return true; } if(SBMLutilities.displayinvalidVariables("Rule", bioModel.getSBMLDocument(), null, assignment, "", false)){ return true; } if (SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), SBMLutilities.myParseFormula(assignment))) { return true; } if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(assignment), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Initial assignment must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } boolean error = false; if (option.equals("OK")) { String[] inits = new String[initAssigns.getModel().getSize()]; for (int i = 0; i < initAssigns.getModel().getSize(); i++) { inits[i] = initAssigns.getModel().getElementAt(i).toString(); } int index = initAssigns.getSelectedIndex(); initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); inits = Utility.getList(inits, initAssigns); initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); InitialAssignment r = (bioModel.getSBMLDocument().getModel().getListOfInitialAssignments()).get(Rindex); String oldSymbol = r.getVariable(); String oldInit = SBMLutilities.myFormulaToString(r.getMath()); String oldVal = inits[index]; r.setVariable(variable); r.setMath(SBMLutilities.myParseFormula(assignment)); inits[index] = variable + " = " + SBMLutilities.myFormulaToString(r.getMath()); if (InitialAssignments.checkInitialAssignmentUnits(bioModel, r)) { error = true; } if (!error) { try { inits = sortInitRules(inits); } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in initial assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); error = true; } } if (!error) { if (SBMLutilities.checkCycles(bioModel.getSBMLDocument())) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); error = true; } } if (error) { r.setVariable(oldSymbol); r.setMath(SBMLutilities.myParseFormula(oldInit)); inits[index] = oldVal; } initAssigns.setListData(inits); initAssigns.setSelectedIndex(index); } else { String[] inits = new String[initAssigns.getModel().getSize()]; for (int i = 0; i < initAssigns.getModel().getSize(); i++) { inits[i] = initAssigns.getModel().getElementAt(i).toString(); } JList add = new JList(); int index = initAssigns.getSelectedIndex(); String addStr; InitialAssignment r = bioModel.getSBMLDocument().getModel().createInitialAssignment(); r.setVariable(variable); r.setMath(SBMLutilities.myParseFormula(assignment)); addStr = variable + " = " + SBMLutilities.myFormulaToString(r.getMath()); Object[] adding = { addStr }; add.setListData(adding); add.setSelectedIndex(0); initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); adding = Utility.add(inits, initAssigns, add); String[] oldInits = inits; inits = new String[adding.length]; for (int i = 0; i < adding.length; i++) { inits[i] = (String) adding[i]; } if (InitialAssignments.checkInitialAssignmentUnits(bioModel, r)) { error = true; } if (!error) { try { inits = sortInitRules(inits); } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in initial assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); error = true; } } if (!error && SBMLutilities.checkCycles(bioModel.getSBMLDocument())) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); error = true; } if (error) { inits = oldInits; ListOf<InitialAssignment> ia = bioModel.getSBMLDocument().getModel().getListOfInitialAssignments(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getInitialAssignmentCount(); i++) { if (SBMLutilities.myFormulaToString(ia.get(i).getMath()).equals( SBMLutilities.myFormulaToString(r.getMath())) && ia.get(i).getVariable().equals(r.getVariable())) { ia.remove(i); } } } initAssigns.setListData(inits); initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (bioModel.getSBMLDocument().getModel().getInitialAssignmentCount() == 1) { initAssigns.setSelectedIndex(0); } else { initAssigns.setSelectedIndex(index); } } if (!error) { modelEditor.setDirty(true); bioModel.makeUndoPoint(); } return error; } /** * Creates a frame used to edit initial assignments or create new ones. */ private void initEditor(String option) { if (option.equals("OK") && initAssigns.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(Gui.frame, "No initial assignment selected.", "Must Select an Initial Assignment", JOptionPane.ERROR_MESSAGE); return; } JPanel initAssignPanel = new JPanel(); JPanel initPanel = new JPanel(); JLabel varLabel = new JLabel("Symbol:"); JLabel assignLabel = new JLabel("Assignment:"); JComboBox initVar = new JComboBox(); String selected; if (option.equals("OK")) { selected = ((String) initAssigns.getSelectedValue()); } else { selected = new String(""); } Model model = bioModel.getSBMLDocument().getModel(); for (int i = 0; i < model.getCompartmentCount(); i++) { String id = model.getCompartment(i).getId(); if (keepVarInit(bioModel, selected.split(" ")[0], id) && (bioModel.getSBMLDocument().getLevel() > 2 || model.getCompartment(i).getSpatialDimensions() != 0)) { initVar.addItem(id); } } for (int i = 0; i < model.getParameterCount(); i++) { String id = model.getParameter(i).getId(); if (keepVarInit(bioModel, selected.split(" ")[0], id)) { initVar.addItem(id); } } for (int i = 0; i < model.getSpeciesCount(); i++) { String id = model.getSpecies(i).getId(); if (keepVarInit(bioModel, selected.split(" ")[0], id)) { initVar.addItem(id); } } for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); for (int j = 0; j < reaction.getReactantCount(); j++) { SpeciesReference reactant = reaction.getReactant(j); if ((reactant.isSetId()) && (!reactant.getId().equals(""))) { String id = reactant.getId(); if (keepVarInit(bioModel, selected.split(" ")[0], id)) { initVar.addItem(id); } } } for (int j = 0; j < reaction.getProductCount(); j++) { SpeciesReference product = reaction.getProduct(j); if ((product.isSetId()) && (!product.getId().equals(""))) { String id = product.getId(); if (keepVarInit(bioModel, selected.split(" ")[0], id)) { initVar.addItem(id); } } } } JTextField initMath = new JTextField(30); int Rindex = -1; if (option.equals("OK")) { initVar.setSelectedItem(selected.split(" ")[0]); initMath.setText(selected.substring(selected.indexOf('=') + 2)); ListOf<InitialAssignment> r = bioModel.getSBMLDocument().getModel().getListOfInitialAssignments(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getInitialAssignmentCount(); i++) { if (SBMLutilities.myFormulaToString(r.get(i).getMath()).equals(initMath.getText()) && r.get(i).getVariable().equals(initVar.getSelectedItem())) { Rindex = i; } } } initPanel.add(varLabel); initPanel.add(initVar); initPanel.add(assignLabel); initPanel.add(initMath); initAssignPanel.add(initPanel); Object[] options = { option, "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, initAssignPanel, "Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); boolean error = true; while (error && value == JOptionPane.YES_OPTION) { error = addUpdateInitialAssignment(option, Rindex, (String) initVar.getSelectedItem(), initMath.getText().trim()); if (error) { value = JOptionPane.showOptionDialog(Gui.frame, initAssignPanel, "Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } /** * Remove an initial assignment */ private void removeInit() { int index = initAssigns.getSelectedIndex(); if (index != -1) { String selected = ((String) initAssigns.getSelectedValue()); String tempVar = selected.split(" ")[0]; String tempMath = selected.substring(selected.indexOf('=') + 2); ListOf<InitialAssignment> r = bioModel.getSBMLDocument().getModel().getListOfInitialAssignments(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getInitialAssignmentCount(); i++) { if (SBMLutilities.myFormulaToString(r.get(i).getMath()).equals(tempMath) && r.get(i).getVariable().equals(tempVar)) { r.remove(i); } } initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); Utility.remove(initAssigns); initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (index < initAssigns.getModel().getSize()) { initAssigns.setSelectedIndex(index); } else { initAssigns.setSelectedIndex(index - 1); } modelEditor.setDirty(true); bioModel.makeUndoPoint(); } } /** * Determines if a variable is already in an initial or assignment rule */ public static boolean keepVarInit(BioModel gcm, String selected, String id) { if (!selected.equals(id)) { for (int i = 0; i < gcm.getSBMLDocument().getModel().getInitialAssignmentCount(); i++) { InitialAssignment init = gcm.getSBMLDocument().getModel().getInitialAssignment(i); if (init.getVariable().equals(id)) return false; } for (int i = 0; i < gcm.getSBMLDocument().getModel().getRuleCount(); i++) { Rule rule = gcm.getSBMLDocument().getModel().getRule(i); if (rule.isAssignment() && SBMLutilities.getVariable(rule).equals(id)) return false; } } return true; } @Override public void actionPerformed(ActionEvent e) { // if the add event button is clicked if (e.getSource() == addInit) { initEditor("Add"); } // if the edit event button is clicked else if (e.getSource() == editInit) { initEditor("OK"); } // if the remove event button is clicked else if (e.getSource() == removeInit) { removeInit(); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (e.getSource() == initAssigns) { initEditor("OK"); } } } /** * This method currently does nothing. */ @Override public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mouseExited(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mousePressed(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mouseReleased(MouseEvent e) { } }
package org.apache.commons.digester; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.collections.ArrayStack; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; public class Digester extends DefaultHandler { /** * Construct a new Digester with default properties. */ public Digester() { super(); } /** * Construct a new Digester, allowing a SAXParser to be passed in. This * allows Digester to be used in environments which are unfriendly to * JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to * James House (james@interobjective.com). This may help in places where * you are able to load JAXP 1.1 classes yourself. */ public Digester(SAXParser parser) { super(); this.parser = parser; } /** * Construct a new Digester, allowing an XMLReader to be passed in. This * allows Digester to be used in environments which are unfriendly to * JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you * have to configure namespace and validation support yourself, as these * properties only affect the SAXParser and emtpy constructor. */ public Digester(XMLReader reader) { super(); this.reader = reader; } /** * The body text of the current element. */ protected StringBuffer bodyText = new StringBuffer(); /** * The stack of body text string buffers for surrounding elements. */ protected ArrayStack bodyTexts = new ArrayStack(); /** * The class loader to use for instantiating application objects. * If not specified, the context class loader, or the class loader * used to load Digester itself, is used, based on the value of the * <code>useContextClassLoader</code> variable. */ protected ClassLoader classLoader = null; /** * The debugging detail level of this component. */ protected int debug = 0; /** * The URLs of DTDs that have been registered, keyed by the public * identifier that corresponds. */ protected HashMap dtds = new HashMap(); /** * The application-supplied error handler that is notified when parsing * warnings, errors, or fatal errors occur. */ protected ErrorHandler errorHandler = null; /** * The SAXParserFactory that is created the first time we need it. */ protected static SAXParserFactory factory = null; /** * The Locator associated with our parser. */ protected Locator locator = null; /** * The current match pattern for nested element processing. */ protected String match = ""; /** * Do we want a "namespace aware" parser? */ protected boolean namespaceAware = false; /** * Registered namespaces we are currently processing. The key is the * namespace prefix that was declared in the document. The value is an * ArrayStack of the namespace URIs this prefix has been mapped to -- * the top Stack element is the most current one. (This architecture * is required because documents can declare nested uses of the same * prefix for different Namespace URIs). */ protected HashMap namespaces = new HashMap(); /** * The parameters stack being utilized by CallMethodRule and * CallParamRule rules. */ protected ArrayStack params = new ArrayStack(); /** * The SAXParser we will use to parse the input stream. */ protected SAXParser parser = null; /** * The XMLReader used to parse digester rules. */ protected XMLReader reader = null; /** * The "root" element of the stack (in other words, the last object * that was popped. */ protected Object root = null; /** * The <code>Rules</code> implementation containing our collection of * <code>Rule</code> instances and associated matching policy. If not * established before the first rule is added, a default implementation * will be provided. */ protected Rules rules = null; /** * The object stack being constructed. */ protected ArrayStack stack = new ArrayStack(); /** * Do we want to use the Context ClassLoader when loading classes * for instantiating new objects? Default is <code>false</code>. */ protected boolean useContextClassLoader = false; /** * Do we want to use a validating parser? */ protected boolean validating = false; /** * The PrintWriter to which we should send log output, or * <code>null</code> to write to <code>System.out</code>. */ protected PrintWriter writer = null; /** * Return the currently mapped namespace URI for the specified prefix, * if any; otherwise return <code>null</code>. These mappings come and * go dynamically as the document is parsed. * * @param prefix Prefix to look up */ public String findNamespaceURI(String prefix) { ArrayStack stack = (ArrayStack) namespaces.get(prefix); if (stack == null) return (null); try { return ((String) stack.peek()); } catch (EmptyStackException e) { return (null); } } /** * Return the class loader to be used for instantiating application objects * when required. This is determined based upon the following rules: * <ul> * <li>The class loader set by <code>setClassLoader()</code>, if any</li> * <li>The thread context class loader, if it exists and the * <code>useContextClassLoader</code> property is set to true</li> * <li>The class loader used to load the Digester class itself. * </ul> */ public ClassLoader getClassLoader() { if (this.classLoader != null) return (this.classLoader); if (this.useContextClassLoader) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) return (classLoader); } return (this.getClass().getClassLoader()); } /** * Set the class loader to be used for instantiating application objects * when required. * * @param classLoader The new class loader to use, or <code>null</code> * to revert to the standard rules */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Return the current depth of the element stack. */ public int getCount() { return (stack.size()); } /** * Return the debugging detail level of this Digester. */ public int getDebug() { return (this.debug); } /** * Set the debugging detail level of this Digester. * * @param debug The new debugging detail level */ public void setDebug(int debug) { this.debug = debug; } /** * Return the error handler for this Digester. */ public ErrorHandler getErrorHandler() { return (this.errorHandler); } /** * Set the error handler for this Digester. * * @param errorHandler The new error handler */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Return the "namespace aware" flag for parsers we create. */ public boolean getNamespaceAware() { return (this.namespaceAware); } /** * Set the "namespace aware" flag for parsers we create. * * @param namespaceAware The new "namespace aware" flag */ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } /** * Return the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. */ public String getRuleNamespaceURI() { return (getRules().getNamespaceURI()); } /** * Set the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. * * @param ruleNamespaceURI Namespace URI that must match on all * subsequently added rules, or <code>null</code> for matching * regardless of the current namespace URI */ public void setRuleNamespaceURI(String ruleNamespaceURI) { getRules().setNamespaceURI(ruleNamespaceURI); } /** * Return the SAXParser we will use to parse the input stream. If there * is a problem creating the parser, return <code>null</code>. */ public SAXParser getParser() { // Return the parser we already created (if any) if (parser != null) return (parser); // Create and return a new parser synchronized (this) { try { if (factory == null) factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); parser = factory.newSAXParser(); return (parser); } catch (Exception e) { log("Digester.getParser: ", e); return (null); } } } /** * By setting the reader in the constructor, you can bypass JAXP and be able * to use digester in Weblogic 6.0. */ public synchronized XMLReader getReader() { if (reader == null) { try { reader = getParser().getXMLReader(); } catch (SAXException se) { return null; } } //set up the parse reader.setContentHandler(this); reader.setDTDHandler(this); reader.setEntityResolver(this); reader.setErrorHandler(this); return reader; } /** * Return the <code>Rules</code> implementation object containing our * rules collection and associated matching policy. If none has been * established, a default implementation will be created and returned. */ public Rules getRules() { if (this.rules == null) { this.rules = new RulesBase(); this.rules.setDigester(this); } return (this.rules); } /** * Set the <code>Rules</code> implementation object containing our * rules collection and associated matching policy. * * @param rules New Rules implementation */ public void setRules(Rules rules) { this.rules = rules; this.rules.setDigester(this); } /** * Return the validating parser flag. */ public boolean getValidating() { return (this.validating); } /** * Set the validating parser flag. This must be called before * <code>parse()</code> is called the first time. * * @param validating The new validating parser flag. */ public void setValidating(boolean validating) { this.validating = validating; } /** * Return the logging writer for this Digester. */ public PrintWriter getWriter() { return (this.writer); } /** * Set the logging writer for this Digester. * * @param writer The new PrintWriter, or <code>null</code> for * <code>System.out</code>. */ public void setWriter(PrintWriter writer) { this.writer = writer; } /** * Return the boolean as to whether the context classloader should be used. */ public boolean getUseContextClassLoader() { return useContextClassLoader; } /** * Determine whether to use the Context ClassLoader (the one found by * calling <code>Thread.currentThread().getContextClassLoader()</code>) * to resolve/load classes that are defined in various rules. If not * using Context ClassLoader, then the class-loading defaults to * using the calling-class' ClassLoader. * * @param boolean determines whether to use Context ClassLoader. */ public void setUseContextClassLoader(boolean use) { useContextClassLoader = use; } /** * Process notification of character data received from the body of * an XML element. * * @param buffer The characters from the XML document * @param start Starting offset into the buffer * @param length Number of characters from the buffer * * @exception SAXException if a parsing error is to be reported */ public void characters(char buffer[], int start, int length) throws SAXException { if (debug >= 3) log("characters(" + new String(buffer, start, length) + ")"); bodyText.append(buffer, start, length); } /** * Process notification of the end of the document being reached. * * @exception SAXException if a parsing error is to be reported */ public void endDocument() throws SAXException { if (debug >= 3) log("endDocument()"); if (getCount() > 1) log("endDocument(): " + getCount() + " elements left"); while (getCount() > 1) pop(); // Fire "finish" events for all defined rules Iterator rules = getRules().rules().iterator(); while (rules.hasNext()) { Rule rule = (Rule) rules.next(); try { rule.finish(); } catch (Exception e) { log("Finish event threw exception", e); throw createSAXException(e); } catch (Throwable t) { log("Finish event threw exception", t); throw createSAXException(t.getMessage()); } } // Perform final cleanup clear(); } /** * Process notification of the end of an XML element being reached. * * @param uri - The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace processing is not * being performed. * @param localName - The local name (without prefix), or the empty * string if Namespace processing is not being performed. * @param qName - The qualified XML 1.0 name (with prefix), or the * empty string if qualified names are not available. * @exception SAXException if a parsing error is to be reported */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (debug >= 3) log("endElement(" + namespaceURI + "," + localName + "," + qName + ")"); // Fire "body" events for all relevant rules List rules = getRules().match(namespaceURI, match); if ((rules != null) && (rules.size() > 0)) { String bodyText = this.bodyText.toString().trim(); for (int i = 0; i < rules.size(); i++) { try { Rule rule = (Rule) rules.get(i); if (debug >= 4) log(" Fire body() for " + rule); rule.body(bodyText); } catch (Exception e) { log("Body event threw exception", e); throw createSAXException(e); } catch (Throwable t) { log("Body event threw exception", t); throw createSAXException(t.getMessage()); } } } // Recover the body text from the surrounding element bodyText = (StringBuffer) bodyTexts.pop(); // Fire "end" events for all relevant rules in reverse order if (rules != null) { for (int i = 0; i < rules.size(); i++) { int j = (rules.size() - i) - 1; try { Rule rule = (Rule) rules.get(j); if (debug >= 4) log(" Fire end() for " + rule); rule.end(); } catch (Exception e) { log("End event threw exception", e); throw createSAXException(e); } catch (Throwable t) { log("End event threw exception", t); throw createSAXException(t.getMessage()); } } } // Recover the previous match expression int slash = match.lastIndexOf('/'); if (slash >= 0) match = match.substring(0, slash); else match = ""; } /** * Process notification that a namespace prefix is going out of scope. * * @param prefix Prefix that is going out of scope * * @exception SAXException if a parsing error is to be reported */ public void endPrefixMapping(String prefix) throws SAXException { if (debug >= 3) log("endPrefixMapping(" + prefix + ")"); // Deregister this prefix mapping ArrayStack stack = (ArrayStack) namespaces.get(prefix); if (stack == null) return; try { stack.pop(); if (stack.empty()) namespaces.remove(prefix); } catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); } } /** * Process notification of ignorable whitespace received from the body of * an XML element. * * @param buffer The characters from the XML document * @param start Starting offset into the buffer * @param length Number of characters from the buffer * * @exception SAXException if a parsing error is to be reported */ public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { if (debug >= 3) log("ignorableWhitespace(" + new String(buffer, start, len) + ")"); ; // No processing required } /** * Process notification of a processing instruction that was encountered. * * @param target The processing instruction target * @param data The processing instruction data (if any) * * @exception SAXException if a parsing error is to be reported */ public void processingInstruction(String target, String data) throws SAXException { if (debug >= 3) log("processingInstruction('" + target + "','" + data + "')"); ; // No processing is required } /** * Set the document locator associated with our parser. * * @param locator The new locator */ public void setDocumentLocator(Locator locator) { if (debug >= 3) log("setDocumentLocator(" + locator + ")"); this.locator = locator; } /** * Process notification of a skipped entity. * * @param name Name of the skipped entity * * @exception SAXException if a parsing error is to be reported */ public void skippedEntity(String name) { if (debug >= 3) log("skippedEntity(" + name + ")"); ; // No processing required } /** * Process notification of the beginning of the document being reached. * * @exception SAXException if a parsing error is to be reported */ public void startDocument() throws SAXException { if (debug >= 3) log("startDocument()"); ; // No processing required } /** * Process notification of the start of an XML element being reached. * * @param uri The Namespace URI, or the empty string if the element * has no Namespace URI or if Namespace processing is not being performed. * @param localName The local name (without prefix), or the empty * string if Namespace processing is not being performed. * @param qName The qualified name (with prefix), or the empty * string if qualified names are not available.\ * @param list The attributes attached to the element. If there are * no attributes, it shall be an empty Attributes object. * @exception SAXException if a parsing error is to be reported */ public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { if (debug >= 3) log("startElement(" + namespaceURI + "," + localName + "," + qName + ")"); // Save the body text accumulated for our surrounding element bodyTexts.push(bodyText); bodyText.setLength(0); // Compute the current matching rule StringBuffer sb = new StringBuffer(match); if (match.length() > 0) sb.append('/'); if ((localName == null) || (localName.length() < 1)) sb.append(qName); else sb.append(localName); match = sb.toString(); if (debug >= 3) log(" New match='" + match + "'"); // Fire "begin" events for all relevant rules List rules = getRules().match(namespaceURI, match); if ((rules != null) && (rules.size() > 0)) { String bodyText = this.bodyText.toString(); for (int i = 0; i < rules.size(); i++) { try { Rule rule = (Rule) rules.get(i); if (debug >= 4) log(" Fire begin() for " + rule); rule.begin(list); } catch (Exception e) { log("Begin event threw exception", e); throw createSAXException(e); } catch (Throwable t) { log("Begin event threw exception", t); throw createSAXException(t.getMessage()); } } } } /** * Process notification that a namespace prefix is coming in to scope. * * @param prefix Prefix that is being declared * @param namespaceURI Corresponding namespace URI being mapped to * * @exception SAXException if a parsing error is to be reported */ public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if (debug >= 3) log("startPrefixMapping(" + prefix + "," + namespaceURI + ")"); // Register this prefix mapping ArrayStack stack = (ArrayStack) namespaces.get(prefix); if (stack == null) { stack = new ArrayStack(); namespaces.put(prefix, stack); } stack.push(namespaceURI); } /** * Receive notification of a notation declaration event. * * @param name The notation name * @param publicId The public identifier (if any) * @param systemId The system identifier (if any) */ public void notationDecl(String name, String publicId, String systemId) { if (debug >= 3) log("notationDecl(" + name + "," + publicId + "," + systemId + ")"); } /** * Receive notification of an unparsed entity declaration event. * * @param name The unparsed entity name * @param publicId The public identifier (if any) * @param systemId The system identifier (if any) * @param notation The name of the associated notation */ public void unparsedEntityDecl(String name, String publicId, String systemId, String notation) { if (debug >= 3) log("unparsedEntityDecl(" + name + "," + publicId + "," + systemId + "," + notation + ")"); } /** * Resolve the requested external entity. * * @param publicId The public identifier of the entity being referenced * @param systemId The system identifier of the entity being referenced * * @exception SAXException if a parsing exception occurs */ public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (debug >= 1) log("resolveEntity('" + publicId + "', '" + systemId + "')"); // Has this system identifier been registered? String dtdURL = null; if (publicId != null) dtdURL = (String) dtds.get(publicId); if (dtdURL == null) { if (debug >= 1) log(" Not registered, use system identifier"); return (null); } // Return an input source to our alternative URL if (debug >= 1) log(" Resolving to alternate DTD '" + dtdURL + "'"); try { URL url = new URL(dtdURL); InputStream stream = url.openStream(); return (new InputSource(stream)); } catch (Exception e) { throw createSAXException(e); } } /** * Forward notification of a parsing error to the application supplied * error handler (if any). * * @param exception The error information * * @exception SAXException if a parsing exception occurs */ public void error(SAXParseException exception) throws SAXException { log("Parse Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) errorHandler.error(exception); } /** * Forward notification of a fatal parsing error to the application * supplied error handler (if any). * * @param exception The fatal error information * * @exception SAXException if a parsing exception occurs */ public void fatalError(SAXParseException exception) throws SAXException { log("Parse Fatal Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) errorHandler.fatalError(exception); } /** * Forward notification of a parse warning to the application supplied * error handler (if any). * * @param exception The warning information * * @exception SAXException if a parsing exception occurs */ public void warning(SAXParseException exception) throws SAXException { log("Parse Warning at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) errorHandler.warning(exception); } /** * Log a message to the log writer associated with this context. * * @param message The message to be logged */ public void log(String message) { if (writer == null) System.out.println(message); else writer.println(message); } /** * Log a message and associated exception to the log writer * associated with this context. * * @param message The message to be logged * @param exception The associated exception to be logged */ public void log(String message, Throwable exception) { if (writer == null) { System.out.println(message); exception.printStackTrace(System.out); } else { writer.println(message); exception.printStackTrace(writer); } } /** * Parse the content of the specified file using this Digester. Returns * the root element from the object stack (if any). * * @param file File containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(File file) throws IOException, SAXException { getReader().parse(new InputSource(new FileReader(file))); return (root); } /** * Parse the content of the specified input source using this Digester. * Returns the root element from the object stack (if any). * * @param input Input source containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(InputSource input) throws IOException, SAXException { getReader().parse(input); return (root); } /** * Parse the content of the specified input stream using this Digester. * Returns the root element from the object stack (if any). * * @param input Input stream containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(InputStream input) throws IOException, SAXException { getReader().parse(new InputSource(input)); return (root); } /** * Parse the content of the specified URI using this Digester. * Returns the root element from the object stack (if any). * * @param uri URI containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(String uri) throws IOException, SAXException { getReader().parse(uri); return (root); } /** * Register the specified DTD URL for the specified public identifier. * This must be called before the first call to <code>parse()</code>. * * @param publicId Public identifier of the DTD to be resolved * @param dtdURL The URL to use for reading this DTD */ public void register(String publicId, String dtdURL) { if (debug >= 1) log("register('" + publicId + "', '" + dtdURL + "'"); dtds.put(publicId, dtdURL); } /** * Register a new Rule matching the specified pattern. * * @param pattern Element matching pattern * @param rule Rule to be registered */ public void addRule(String pattern, Rule rule) { getRules().add(pattern, rule); } /** * Register a set of Rule instances defined in a RuleSet. * * @param ruleSet The RuleSet instance to configure from */ public void addRuleSet(RuleSet ruleSet) { String oldNamespaceURI = getRuleNamespaceURI(); String newNamespaceURI = ruleSet.getNamespaceURI(); if (debug >= 3) { if (newNamespaceURI == null) log("addRuleSet() with no namespace URI"); else log("addRuleSet() with namespace URI " + newNamespaceURI); } setRuleNamespaceURI(newNamespaceURI); ruleSet.addRuleInstances(this); setRuleNamespaceURI(oldNamespaceURI); } /** * Add an "call method" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to be called * @param paramCount Number of expected parameters (or zero * for a single parameter from the body of this element) */ public void addCallMethod(String pattern, String methodName, int paramCount) { addRule(pattern, new CallMethodRule(this, methodName, paramCount)); } /** * Add an "call method" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to be called * @param paramCount Number of expected parameters (or zero * for a single parameter from the body of this element) * @param paramTypes Set of Java class names for the types * of the expected parameters * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) */ public void addCallMethod(String pattern, String methodName, int paramCount, String paramTypes[]) { addRule(pattern, new CallMethodRule(this, methodName, paramCount, paramTypes)); } /** * Add an "call method" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to be called * @param paramCount Number of expected parameters (or zero * for a single parameter from the body of this element) * @param paramTypes The Java class names of the arguments * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) */ public void addCallMethod(String pattern, String methodName, int paramCount, Class paramTypes[]) { addRule(pattern, new CallMethodRule(this, methodName, paramCount, paramTypes)); } /** * Add a "call parameter" rule for the specified parameters. * * @param pattern Element matching pattern * @param paramIndex Zero-relative parameter index to set * (from the body of this element) */ public void addCallParam(String pattern, int paramIndex) { addRule(pattern, new CallParamRule(this, paramIndex)); } /** * Add a "call parameter" rule for the specified parameters. * * @param pattern Element matching pattern * @param paramIndex Zero-relative parameter index to set * (from the specified attribute) * @param attributeName Attribute whose value is used as the * parameter value */ public void addCallParam(String pattern, int paramIndex, String attributeName) { addRule(pattern, new CallParamRule(this, paramIndex, attributeName)); } /** * Add a "factory create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Java class name of the object creation factory class */ public void addFactoryCreate(String pattern, String className) { addRule(pattern, new FactoryCreateRule(this, className)); } /** * Add a "factory create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Java class name of the object creation factory class * @param attributeName Attribute name which, if present, overrides the * value specified by <code>className</code> */ public void addFactoryCreate(String pattern, String className, String attributeName) { addRule(pattern, new FactoryCreateRule(this, className, attributeName)); } /** * Add a "factory create" rule for the specified parameters. * * @param pattern Element matching pattern * @param creationFactory Previously instantiated ObjectCreationFactory * to be utilized */ public void addFactoryCreate(String pattern, ObjectCreationFactory creationFactory) { addRule(pattern, new FactoryCreateRule(this, creationFactory)); } /** * Add an "object create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Java class name to be created */ public void addObjectCreate(String pattern, String className) { addRule(pattern, new ObjectCreateRule(this, className)); } /** * Add an "object create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Default Java class name to be created * @param attributeName Attribute name that optionally overrides * the default Java class name to be created */ public void addObjectCreate(String pattern, String className, String attributeName) { addRule(pattern, new ObjectCreateRule(this, className, attributeName)); } /** * Add a "set next" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element */ public void addSetNext(String pattern, String methodName) { addRule(pattern, new SetNextRule(this, methodName)); } /** * Add a "set next" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element * @param paramType Java class name of the expected parameter type * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) */ public void addSetNext(String pattern, String methodName, String paramType) { addRule(pattern, new SetNextRule(this, methodName, paramType)); } /** * Add a "set properties" rule for the specified parameters. * * @param pattern Element matching pattern */ public void addSetProperties(String pattern) { addRule(pattern, new SetPropertiesRule(this)); } /** * Add a "set property" rule for the specified parameters. * * @param pattern Element matching pattern * @param name Attribute name containing the property name to be set * @param value Attribute name containing the property value to set */ public void addSetProperty(String pattern, String name, String value) { addRule(pattern, new SetPropertyRule(this, name, value)); } /** * Add a "set top" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element */ public void addSetTop(String pattern, String methodName) { addRule(pattern, new SetTopRule(this, methodName)); } /** * Add a "set top" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element * @param paramType Java class name of the expected parameter type * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) */ public void addSetTop(String pattern, String methodName, String paramType) { addRule(pattern, new SetTopRule(this, methodName, paramType)); } /** * Clear the current contents of the object stack. */ public void clear() { match = ""; bodyTexts.clear(); params.clear(); stack.clear(); getRules().clear(); } /** * Return the top object on the stack without removing it. If there are * no objects on the stack, return <code>null</code>. */ public Object peek() { try { return (stack.peek()); } catch (EmptyStackException e) { return (null); } } /** * Return the n'th object down the stack, where 0 is the top element * and [getCount()-1] is the bottom element. If the specified index * is out of range, return <code>null</code>. * * @param n Index of the desired element, where 0 is the top of the stack, * 1 is the next element down, and so on. */ public Object peek(int n) { try { return (stack.peek(n)); } catch (EmptyStackException e) { return (null); } } /** * Pop the top object off of the stack, and return it. If there are * no objects on the stack, return <code>null</code>. */ public Object pop() { try { return (stack.pop()); } catch (EmptyStackException e) { return (null); } } /** * Push a new object onto the top of the object stack. * * @param object The new object */ public void push(Object object) { if (stack.size() == 0) root = object; stack.push(object); } /** * Return the set of DTD URL registrations, keyed by public identifier. */ Map getRegistrations() { return (dtds); } /** * Return the set of rules that apply to the specified match position. * The selected rules are those that match exactly, or those rules * that specify a suffix match and the tail of the rule matches the * current match position. Exact matches have precedence over * suffix matches, then (among suffix matches) the longest match * is preferred. * * @param match The current match position * * @deprecated Call <code>match()</code> on the <code>Rules</code> * implementation returned by <code>getRules()</code> */ List getRules(String match) { return (getRules().match(match)); } /** * Return the top object on the stack without removing it. If there are * no objects on the stack, return <code>null</code>. */ Object peekParams() { try { return (params.peek()); } catch (EmptyStackException e) { return (null); } } /** * Return the n'th object down the stack, where 0 is the top element * and [getCount()-1] is the bottom element. If the specified index * is out of range, return <code>null</code>. * * @param n Index of the desired element, where 0 is the top of the stack, * 1 is the next element down, and so on. */ Object peekParams(int n) { try { return (params.peek(n)); } catch (EmptyStackException e) { return (null); } } /** * Pop the top object off of the stack, and return it. If there are * no objects on the stack, return <code>null</code>. */ Object popParams() { try { return (params.pop()); } catch (EmptyStackException e) { return (null); } } /** * Push a new object onto the top of the object stack. * * @param object The new object */ void pushParams(Object object) { params.push(object); } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ protected SAXException createSAXException(String message, Exception e) { if ( locator != null ) { String error = "Error at (" + locator.getLineNumber() + ", " + locator.getColumnNumber() + ": " + message; if ( e != null ) { return new SAXParseException( error, locator, e ); } else { return new SAXParseException( error, locator ); } } System.out.println( "No Locator!" ); if ( e != null ) { return new SAXException(message, e); } else { return new SAXException(message); } } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ protected SAXException createSAXException(Exception e) { return createSAXException(e.getMessage(), e); } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ protected SAXException createSAXException(String message) { return createSAXException(message, null); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Arrays; import java.util.List; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JPanel p = new JPanel(new GridLayout(0, 1, 0, 2)); List<JTabbedPane> list = Arrays.asList(new JTabbedPane(), makeTabbedPane1(), makeTabbedPane2()); list.forEach(tabs -> { tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); tabs.addTab("00000000", new JLabel("0")); tabs.addTab("11111111", new JLabel("1")); tabs.addTab("22222222", new JLabel("2")); tabs.addTab("33333333", new JLabel("3")); tabs.addTab("44444444", new JLabel("4")); tabs.addTab("55555555", new JLabel("5")); tabs.addTab("66666666", new JLabel("6")); tabs.addTab("77777777", new JLabel("7")); tabs.addTab("88888888", new JLabel("8")); tabs.addTab("99999999", new JLabel("9")); tabs.setSelectedIndex(tabs.getTabCount() - 1); // // TEST: // EventQueue.invokeLater(() -> { // tabs.setSelectedIndex(tabs.getTabCount() - 1); p.add(tabs); }); JButton button = new JButton("Remove"); button.addActionListener(e -> list.stream() .filter(t -> t.getTabCount() > 0) .forEach(t -> t.removeTabAt(t.getTabCount() - 1))); add(p); add(button, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } private static JTabbedPane makeTabbedPane1() { return new JTabbedPane() { @Override public void removeTabAt(int index) { if (getTabCount() > 0) { setSelectedIndex(0); super.removeTabAt(index); setSelectedIndex(index - 1); } else { super.removeTabAt(index); } } }; } private static JTabbedPane makeTabbedPane2() { return new JTabbedPane() { private Component getScrollableViewport() { Component cmp = null; for (Component c : getComponents()) { if ("TabbedPane.scrollableViewport".equals(c.getName())) { cmp = c; break; } } return cmp; } private void resetViewportPosition(int idx) { if (getTabCount() <= 0) { return; } Component o = getScrollableViewport(); if (o instanceof JViewport) { JViewport viewport = (JViewport) o; JComponent c = (JComponent) viewport.getView(); c.scrollRectToVisible(getBoundsAt(idx)); } } @Override public void removeTabAt(int index) { if (getTabCount() > 0) { resetViewportPosition(0); super.removeTabAt(index); resetViewportPosition(index - 1); } else { super.removeTabAt(index); } } }; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package io.digdag.cli; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import com.beust.jcommander.DynamicParameter; import com.beust.jcommander.JCommander; import com.beust.jcommander.MissingCommandException; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import io.digdag.cli.client.Archive; import io.digdag.cli.client.Backfill; import io.digdag.cli.client.Delete; import io.digdag.cli.client.Kill; import io.digdag.cli.client.Push; import io.digdag.cli.client.Reschedule; import io.digdag.cli.client.Retry; import io.digdag.cli.client.Secrets; import io.digdag.cli.client.ShowAttempt; import io.digdag.cli.client.ShowAttempts; import io.digdag.cli.client.ShowLog; import io.digdag.cli.client.ShowSchedule; import io.digdag.cli.client.ShowSession; import io.digdag.cli.client.ShowTask; import io.digdag.cli.client.ShowWorkflow; import io.digdag.cli.client.Start; import io.digdag.cli.client.Upload; import io.digdag.cli.client.Version; import io.digdag.core.Environment; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import static io.digdag.cli.ConfigUtil.defaultConfigPath; import static io.digdag.cli.SystemExitException.systemExit; import static io.digdag.core.Version.buildVersion; import static io.digdag.core.agent.OperatorManager.formatExceptionMessage; public class Main { private static final String DEFAULT_PROGRAM_NAME = "digdag"; private final io.digdag.core.Version version; private final Map<String, String> env; private final PrintStream out; private final PrintStream err; private final InputStream in; private final String programName; public Main(io.digdag.core.Version version, Map<String, String> env, PrintStream out, PrintStream err, InputStream in) { this.version = version; this.env = env; this.out = out; this.err = err; this.in = in; this.programName = System.getProperty("io.digdag.cli.programName", DEFAULT_PROGRAM_NAME); } public static class MainOptions { @Parameter(names = {"-c", "--config"}) protected String configPath = null; @Parameter(names = {"-help", "--help"}, help = true, hidden = true) boolean help; } public static void main(String... args) { int code = new Main(buildVersion(), System.getenv(), System.out, System.err, System.in).cli(args); if (code != 0) { System.exit(code); } } public int cli(String... args) { for (String arg : args) { if ("--version".equals(arg)) { out.println(version.version()); return 0; } } err.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date()) + ": Digdag v" + version); if (args.length == 0) { usage(null); return 0; } boolean verbose = false; MainOptions mainOpts = new MainOptions(); JCommander jc = new JCommander(mainOpts); jc.setProgramName(programName); // TODO: Use a pojo instead to avoid guice overhead Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Map<String, String>>() {}).annotatedWith(Environment.class).toInstance(env); bind(io.digdag.core.Version.class).toInstance(version); bind(String.class).annotatedWith(ProgramName.class).toInstance(programName); bind(InputStream.class).annotatedWith(StdIn.class).toInstance(in); bind(PrintStream.class).annotatedWith(StdOut.class).toInstance(out); bind(PrintStream.class).annotatedWith(StdErr.class).toInstance(err); } }); jc.addCommand("init", injector.getInstance(Init.class), "new"); jc.addCommand("run", injector.getInstance(Run.class), "r"); jc.addCommand("check", injector.getInstance(Check.class), "c"); jc.addCommand("scheduler", injector.getInstance(Sched.class), "sched"); jc.addCommand("server", injector.getInstance(Server.class)); jc.addCommand("push", injector.getInstance(Push.class)); jc.addCommand("archive", injector.getInstance(Archive.class)); jc.addCommand("upload", injector.getInstance(Upload.class)); jc.addCommand("workflow", injector.getInstance(ShowWorkflow.class), "workflows"); jc.addCommand("start", injector.getInstance(Start.class)); jc.addCommand("retry", injector.getInstance(Retry.class)); jc.addCommand("session", injector.getInstance(ShowSession.class), "sessions"); jc.addCommand("attempts", injector.getInstance(ShowAttempts.class)); jc.addCommand("attempt", injector.getInstance(ShowAttempt.class)); jc.addCommand("reschedule", injector.getInstance(Reschedule.class)); jc.addCommand("backfill", injector.getInstance(Backfill.class)); jc.addCommand("log", injector.getInstance(ShowLog.class), "logs"); jc.addCommand("kill", injector.getInstance(Kill.class)); jc.addCommand("task", injector.getInstance(ShowTask.class), "tasks"); jc.addCommand("schedule", injector.getInstance(ShowSchedule.class), "schedules"); jc.addCommand("delete", injector.getInstance(Delete.class)); jc.addCommand("secrets", injector.getInstance(Secrets.class), "secret"); jc.addCommand("version", injector.getInstance(Version.class), "version"); jc.addCommand("selfupdate", injector.getInstance(SelfUpdate.class)); // Disable @ expansion jc.setExpandAtSign(false); jc.getCommands().values().forEach(c -> c.setExpandAtSign(false)); try { try { jc.parse(args); } catch (MissingCommandException ex) { throw usage("available commands are: "+jc.getCommands().keySet()); } catch (ParameterException ex) { if (getParsedCommand(jc) == null) { // go to Run.asImplicit section } else { throw ex; } } if (mainOpts.help) { throw usage(null); } Command command = getParsedCommand(jc); if (command == null) { throw usage(null); } verbose = processCommonOptions(mainOpts, command); command.main(); return 0; } catch (ParameterException ex) { err.println("error: " + ex.getMessage()); return 1; } catch (SystemExitException ex) { if (ex.getMessage() != null) { err.println("error: " + ex.getMessage()); } return ex.getCode(); } catch (Exception ex) { String message = formatExceptionMessage(ex); if (message.trim().isEmpty()) { // prevent silent crash ex.printStackTrace(err); } else { err.println("error: " + message); if (verbose) { ex.printStackTrace(err); } } return 1; } } private static Command getParsedCommand(JCommander jc) { String commandName = jc.getParsedCommand(); if (commandName == null) { return null; } return (Command) jc.getCommands().get(commandName).getObjects().get(0); } private boolean processCommonOptions(MainOptions mainOpts, Command command) throws SystemExitException { if (command.help) { throw command.usage(null); } boolean verbose; switch (command.logLevel) { case "error": case "warn": case "info": verbose = false; break; case "debug": case "trace": verbose = true; break; default: throw usage("Unknown log level '"+command.logLevel+"'"); } if (command.configPath == null) { command.configPath = mainOpts.configPath; } configureLogging(command.logLevel, command.logPath); for (Map.Entry<String, String> pair : command.systemProperties.entrySet()) { System.setProperty(pair.getKey(), pair.getValue()); } return verbose; } private static void configureLogging(String level, String logPath) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); // logback uses system property to embed variables in XML file Level lv = Level.toLevel(level.toUpperCase(), Level.DEBUG); System.setProperty("digdag.log.level", lv.toString()); String name; if (logPath.equals("-")) { if (System.console() != null) { name = "/digdag/cli/logback-color.xml"; } else { name = "/digdag/cli/logback-console.xml"; } } else { System.setProperty("digdag.log.path", logPath); name = "/digdag/cli/logback-file.xml"; } try { configurator.doConfigure(Main.class.getResource(name)); } catch (JoranException ex) { throw new RuntimeException(ex); } } // called also by Run private SystemExitException usage(String error) { err.println("Usage: " + programName + " <command> [options...]"); err.println(" Local-mode commands:"); err.println(" new <path> create a new workflow project"); err.println(" r[un] <workflow.dig> run a workflow"); err.println(" c[heck] show workflow definitions"); err.println(" sched[uler] run a scheduler server"); err.println(" selfupdate update cli to the latest version"); err.println(""); err.println(" Server-mode commands:"); err.println(" server start server"); err.println(""); err.println(" Client-mode commands:"); err.println(" push <project-name> create and upload a new revision"); err.println(" start <project-name> <name> start a new session attempt of a workflow"); err.println(" retry <attempt-id> retry a session"); err.println(" kill <attempt-id> kill a running session attempt"); err.println(" backfill <project-name> <name> start sessions of a schedule for past times"); err.println(" reschedule skip sessions of a schedule to a future time"); err.println(" log <attempt-id> show logs of a session attempt"); err.println(" workflows [project-name] [name] show registered workflow definitions"); err.println(" schedules show registered schedules"); err.println(" sessions show sessions for all workflows"); err.println(" sessions <project-name> show sessions for all workflows in a project"); err.println(" sessions <project-name> <name> show sessions for a workflow"); err.println(" session <session-id> show a single session"); err.println(" attempts show attempts for all sessions"); err.println(" attempts <session-id> show attempts for a session"); err.println(" attempt <attempt-id> show a single attempt"); err.println(" tasks <attempt-id> show tasks of a session attempt"); err.println(" delete <project-name> delete a project"); err.println(" secrets --project <project-name> manage secrets"); err.println(" version show client and server version"); err.println(""); err.println(" Options:"); showCommonOptions(env, err); if (error == null) { err.println("Use `<command> --help` to see detailed usage of a command."); return systemExit(null); } else { return systemExit(error); } } public static void showCommonOptions(Map<String, String> env, PrintStream err) { err.println(" -L, --log PATH output log messages to a file (default: -)"); err.println(" -l, --log-level LEVEL log level (error, warn, info, debug or trace)"); err.println(" -X KEY=VALUE add a performance system config"); err.println(" -c, --config PATH.properties Configuration file (default: " + defaultConfigPath(env) + ")"); err.println(""); } }
package verification.platu.stategraph; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.common.IndexObjMap; import verification.platu.logicAnalysis.Constraint; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LpnTranList; import verification.platu.main.Main; import verification.platu.main.Options; import verification.platu.project.PrjState; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.Zone; public class StateGraph { protected State init = null; protected IndexObjMap<State> stateCache; protected IndexObjMap<State> localStateCache; protected HashMap<State, State> state2LocalMap; protected HashMap<State, LpnTranList> enabledSetTbl; protected HashMap<State, HashMap<Transition, State>> nextStateMap; protected List<State> stateSet = new LinkedList<State>(); protected List<State> frontierStateSet = new LinkedList<State>(); protected List<State> entryStateSet = new LinkedList<State>(); protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> newConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>(); protected Set<Constraint> constraintSet = new HashSet<Constraint>(); protected LhpnFile lpn; public StateGraph(LhpnFile lpn) { this.lpn = lpn; this.stateCache = new IndexObjMap<State>(); this.localStateCache = new IndexObjMap<State>(); this.state2LocalMap = new HashMap<State, State>(); this.enabledSetTbl = new HashMap<State, LpnTranList>(); this.nextStateMap = new HashMap<State, HashMap<Transition, State>>(); } public LhpnFile getLpn(){ return this.lpn; } public void printStates(){ System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size())); } public Set<Transition> getTranList(State currentState){ return this.nextStateMap.get(currentState).keySet(); } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * @param baseState - State to start from * @return Number of new transitions. */ public int constrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { State newState = constrFire(firedTran,currentState); State nextState = addState(newState); newStateFlag = false; if(nextState == newState){ addFrontierState(nextState); newStateFlag = true; } // StateTran stTran = new StateTran(currentState, firedTran, state); if(nextState != currentState){ // this.addStateTran(currentState, nextState, firedTran); this.addStateTran(currentState, firedTran, nextState); newTransitions++; // TODO: (original) check that a variable was changed before creating a constraint if(!firedTran.isLocal()){ for(LhpnFile lpn : firedTran.getDstLpnList()){ // TODO: (temp) Hack here. Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn); // TODO: (temp) Ignore constraint. } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions.isEmpty()) continue; // currentEnabledTransitions = getEnabled(nexState); // Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); // if(disabledTran != null) { // System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + // firedTran.getFullLabel()); // currentState.setFailure(); // return -1; stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods * @param baseState State to start from * @return Number of new transitions. */ public int synchronizedConstrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { State st = constrFire(firedTran,currentState); State nextState = addState(st); newStateFlag = false; if(nextState == st){ newStateFlag = true; addFrontierState(nextState); } if(nextState != currentState){ newTransitions++; if(!firedTran.isLocal()){ // TODO: (original) check that a variable was changed before creating a constraint for(LhpnFile lpn : firedTran.getDstLpnList()){ // TODO: (temp) Hack here. Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn); // TODO: (temp) Ignore constraints. } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) { continue; } // currentEnabledTransitions = getEnabled(nexState); // Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); // if(disabledTran != null) { // prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + // firedTran.getFullLabel()); // currentState.setFailure(); // return -1; stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } public List<State> getFrontierStateSet(){ return this.frontierStateSet; } public List<State> getStateSet(){ return this.stateSet; } public void addFrontierState(State st){ this.entryStateSet.add(st); } public List<Constraint> getOldConstraintSet(){ return this.oldConstraintSet; } /** * Adds constraint to the constraintSet. * @param c - Constraint to be added. * @return True if added, otherwise false. */ public boolean addConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } /** * Adds constraint to the constraintSet. Synchronized version of addConstraint(). * @param c - Constraint to be added. * @return True if added, otherwise false. */ public synchronized boolean synchronizedAddConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } public List<Constraint> getNewConstraintSet(){ return this.newConstraintSet; } public void genConstraints(){ oldConstraintSet.addAll(newConstraintSet); newConstraintSet.clear(); newConstraintSet.addAll(frontierConstraintSet); frontierConstraintSet.clear(); } public void genFrontier(){ this.stateSet.addAll(this.frontierStateSet); this.frontierStateSet.clear(); this.frontierStateSet.addAll(this.entryStateSet); this.entryStateSet.clear(); } public void setInitialState(State init){ this.init = init; } public State getInitialState(){ return this.init; } public void draw(){ String dotFile = Options.getDotPath(); if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){ String dirSlash = "/"; if(Main.isWindows) dirSlash = "\\"; dotFile = dotFile += dirSlash; } dotFile += this.lpn.getLabel() + ".dot"; PrintStream graph = null; try { graph = new PrintStream(new FileOutputStream(dotFile)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } graph.println("digraph SG{"); //graph.println(" fixedsize=true"); int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size(); String[] variables = new String[size]; DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap(); int i; for(i = 0; i < size; i++){ variables[i] = varIndexMap.getKey(i); } //for(State state : this.reachableSet.keySet()){ for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) { State state = this.getState(stateIdx); String dotLabel = state.getIndex() + ": "; int[] vector = state.getVector(); for(i = 0; i < size; i++){ dotLabel += variables[i]; if(vector[i] == 0) dotLabel += "'"; if(i < size-1) dotLabel += " "; } int[] mark = state.getMarking(); dotLabel += "\\n"; for(i = 0; i < mark.length; i++){ if(i == 0) dotLabel += "["; dotLabel += mark[i]; if(i < mark.length - 1) dotLabel += ", "; else dotLabel += "]"; } String attributes = ""; if(state == this.init) attributes += " peripheries=2"; if(state.failure()) attributes += " style=filled fillcolor=\"red\""; graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " + "label=\"" + dotLabel + "\"" + attributes + "]"); for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){ State tailState = state; State headState = stateTran.getValue(); Transition lpnTran = stateTran.getKey(); String edgeLabel = lpnTran.getName() + ": "; int[] headVector = headState.getVector(); int[] tailVector = tailState.getVector(); for(i = 0; i < size; i++){ if(headVector[i] != tailVector[i]){ if(headVector[i] == 0){ edgeLabel += variables[i]; edgeLabel += "-"; } else{ edgeLabel += variables[i]; edgeLabel += "+"; } } } graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]"); } } graph.println("}"); graph.close(); } /** * Return the enabled transitions in the state with index 'stateIdx'. * @param stateIdx * @return */ public LpnTranList getEnabled(int stateIdx) { State curState = this.getState(stateIdx); return this.getEnabled(curState); } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); return curEnabled; } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState, boolean init) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ if (Options.getDebugMode()) { System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~"); printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state "); } return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); if (init) { for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if (Options.getDebugMode()) System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled"); if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } } else { for (int i=0; i < this.lpn.getAllTransitions().length; i++) { Transition tran = this.lpn.getAllTransitions()[i]; if (curState.getTranVector()[i]) if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); if (Options.getDebugMode()) { System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl."); printEnabledSetTbl(); } return curEnabled; } private void printEnabledSetTbl() { System.out.println("******* enabledSetTbl**********"); for (State s : enabledSetTbl.keySet()) { System.out.print("S" + s.getIndex() + " -> "); printTransitionSet(enabledSetTbl.get(s), ""); } } public boolean isEnabled(Transition tran, State curState) { int[] varValuesVector = curState.getVector(); String tranName = tran.getName(); int tranIndex = tran.getIndex(); if (Options.getDebugMode()) System.out.println("Checking " + tran); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0 && !(tran.isPersistent() && curState.getTranVector()[tranIndex])) { if (Options.getDebugMode()) System.out.println(tran.getName() + " " + "Enabling condition is false"); return false; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) { if (Options.getDebugMode()) System.out.println("Rate is zero"); return false; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { int[] curMarking = curState.getMarking(); for (int place : this.lpn.getPresetIndex(tranName)) { if (curMarking[place]==0) { if (Options.getDebugMode()) System.out.println(tran.getName() + " " + "Missing a preset token"); return false; } } // if a transition is enabled and it is not recorded in the enabled transition vector curState.getTranVector()[tranIndex] = true; } return true; } public int reachSize() { if(this.stateCache == null){ return this.stateSet.size(); } return this.stateCache.size(); } public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); for (State s : stateArray) { if (s == curState) { isStateOnStack = true; break; } } if (isStateOnStack) break; } return isStateOnStack; } /* * Add the module state mState into the local cache, and also add its local portion into * the local portion cache, and build the mapping between the mState and lState for fast lookup * in the future. */ public State addState(State mState) { State cachedState = this.stateCache.add(mState); State lState = this.state2LocalMap.get(cachedState); if(lState == null) { lState = cachedState.getLocalState(); lState = this.localStateCache.add(lState); this.state2LocalMap.put(cachedState, lState); } return cachedState; } /* * Get the local portion of mState from the cache.. */ public State getLocalState(State mState) { return this.state2LocalMap.get(mState); } public State getState(int stateIdx) { return this.stateCache.get(stateIdx); } public void addStateTran(State curSt, Transition firedTran, State nextSt) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) { nextMap = new HashMap<Transition,State>(); nextMap.put(firedTran, nextSt); this.nextStateMap.put(curSt, nextMap); } else nextMap.put(firedTran, nextSt); } public State getNextState(State curSt, Transition firedTran) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) return null; return nextMap.get(firedTran); } private static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0); public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){ HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState); if(tranMap == null){ return emptySet; } return tranMap.entrySet(); } public int numConstraints(){ if(this.constraintSet == null){ return this.oldConstraintSet.size(); } return this.constraintSet.size(); } public void clear(){ this.constraintSet.clear(); this.frontierConstraintSet.clear(); this.newConstraintSet.clear(); this.frontierStateSet.clear(); this.entryStateSet.clear(); this.constraintSet = null; this.frontierConstraintSet = null; this.newConstraintSet = null; this.frontierStateSet = null; this.entryStateSet = null; this.stateCache = null; } public State getInitState() { // create initial vector int size = this.lpn.getVarIndexMap().size(); int[] initialVector = new int[size]; for(int i = 0; i < size; i++) { String var = this.lpn.getVarIndexMap().getKey(i); int val = this.lpn.getInitVector(var);// this.initVector.get(var); initialVector[i] = val; } return new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector)); } /** * Fire a transition on a state array, find new local states, and return the new state array formed by the new local states. * @param firedTran * @param curLpnArray * @param curStateArray * @param curLpnIndex * @return */ public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) { State[] stateArray = new State[curSgArray.length]; for(int i = 0; i < curSgArray.length; i++) stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]); return this.fire(curSgArray, stateArray, firedTran); } // This method is called by search_dfs(StateGraph[], State[]). public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran) { int thisLpnIndex = this.getLpn().getLpnIndex(); State[] nextStateArray = curStateArray.clone(); State curState = curStateArray[thisLpnIndex]; State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran); //int[] nextVector = nextState.getVector(); //int[] curVector = curState.getVector(); // TODO: (future) assertions in our LPN? /* for(Expression e : assertions){ if(e.evaluate(nextVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ nextStateArray[thisLpnIndex] = nextState; if(firedTran.isLocal()==true) { // nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState); return nextStateArray; } HashMap<String, Integer> vvSet = new HashMap<String, Integer>(); vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector()); // for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) { // if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // // TODO: (temp) type cast continuous variable to int. // if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); /* for (VarExpr s : this.getAssignments()) { int newValue = nextVector[s.getVar().getIndex(curVector)]; vvSet.put(s.getVar().getName(), newValue); } */ // Update other local states with the new values generated for the shared variables. //nextStateArray[this.lpn.getIndex()] = nextState; // if (!firedTran.getDstLpnList().contains(this.lpn)) // firedTran.getDstLpnList().add(this.lpn); for(LhpnFile curLPN : firedTran.getDstLpnList()) { int curIdx = curLPN.getLpnIndex(); // System.out.println("Checking " + curLPN.getLabel() + " " + curIdx); State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran); if(newState != null) { nextStateArray[curIdx] = newState; } else { State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap()); if (newOther == null) nextStateArray[curIdx] = curStateArray[curIdx]; else { State cachedOther = curSgArray[curIdx].addState(newOther); //nextStateArray[curIdx] = newOther; nextStateArray[curIdx] = cachedOther; // System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" + // curStateArray[curIdx].print() + firedTran.getName() + "\n" + // cachedOther.getIndex() + ":\n" + cachedOther.print()); curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther); } } } return nextStateArray; } // TODO: (original) add transition that fires to parameters public State fire(final StateGraph thisSg, final State curState, Transition firedTran) { // Search for and return cached next state first. // if(this.nextStateMap.containsKey(curState) == true) // return (State)this.nextStateMap.get(curState); State nextState = thisSg.getNextState(curState, firedTran); if(nextState != null) return nextState; // If no cached next state exists, do regular firing. // Marking update int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0) curNewMarking = curOldMarking; else { curNewMarking = new int[curOldMarking.length]; curNewMarking = curOldMarking.clone(); for (int prep : this.lpn.getPresetIndex(firedTran.getName())) { curNewMarking[prep]=0; } for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) { curNewMarking[postp]=1; } } // State vector update int[] newVectorArray = curState.getVector().clone(); int[] curVector = curState.getVector(); for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } // TODO: (temp) type cast continuous variable to int. if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } /* for (VarExpr s : firedTran.getAssignments()) { int newValue = (int) s.getExpr().evaluate(curVector); newVectorArray[s.getVar().getIndex(curVector)] = newValue; } */ // Enabled transition vector update boolean[] newEnabledTranVector = updateEnabledTranVector(curState.getTranVector(), curNewMarking, newVectorArray, firedTran); State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector)); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ thisSg.addStateTran(curState, firedTran, newState); return newState; } public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring, int[] newMarking, int[] newVectorArray, Transition firedTran) { boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone(); // firedTran is disabled if (firedTran != null) { enabledTranAfterFiring[firedTran.getIndex()] = false; for (Iterator<Integer> conflictIter = firedTran.getConflictSetTransIndices().iterator(); conflictIter.hasNext();) { Integer curConflictingTranIndex = conflictIter.next(); enabledTranAfterFiring[curConflictingTranIndex] = false; } } // find newly enabled transition(s) based on the updated markings and variables for (Transition tran : this.lpn.getAllTransitions()) { boolean needToUpdate = true; String tranName = tran.getName(); int tranIndex = tran.getIndex(); //System.out.println("Checking " + tran); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { //System.out.println(tran.getName() + " " + "Enabling condition is false"); if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent()) enabledTranAfterFiring[tranIndex] = false; continue; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { //System.out.println("Rate is zero"); continue; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { for (int place : this.lpn.getPresetIndex(tranName)) { if (newMarking[place]==0) { //System.out.println(tran.getName() + " " + "Missing a preset token"); needToUpdate = false; break; } } } if (needToUpdate) { // if a transition is enabled and it is not recorded in the enabled transition vector enabledTranAfterFiring[tranIndex] = true; } } return enabledTranAfterFiring; } public State constrFire(Transition firedTran, final State curState) { // Marking update int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){ curNewMarking = curOldMarking; } else { curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length]; int index = 0; for (int i : curOldMarking) { boolean existed = false; for (int prep : this.lpn.getPresetIndex(firedTran.getName())) { if (i == prep) { existed = true; break; } // TODO: (??) prep > i else if(prep > i){ break; } } if (existed == false) { curNewMarking[index] = i; index++; } } for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) { curNewMarking[index] = postp; index++; } } // State vector update int[] oldVector = curState.getVector(); int size = oldVector.length; int[] newVectorArray = new int[size]; System.arraycopy(oldVector, 0, newVectorArray, 0, size); int[] curVector = curState.getVector(); for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } // TODO: (temp) type cast continuous variable to int. if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } // TODO: (check) Is the update is equivalent to the one below? /* for (VarExpr s : getAssignments()) { int newValue = s.getExpr().evaluate(curVector); newVectorArray[s.getVar().getIndex(curVector)] = newValue; } */ // Enabled transition vector update boolean[] newEnabledTranArray = curState.getTranVector(); newEnabledTranArray[firedTran.getIndex()] = false; State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ return newState; } public void outputLocalStateGraph(String file) { try { int size = this.lpn.getVarIndexMap().size(); String varNames = ""; for(int i = 0; i < size; i++) { varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i); } varNames = varNames.replaceFirst(", ", ""); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("digraph G {\n"); out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n"); for (State curState : nextStateMap.keySet()) { String markings = intArrayToString("markings", curState); String vars = intArrayToString("vars", curState); String enabledTrans = boolArrayToString("enabledTrans", curState); String curStateName = "S" + curState.getIndex(); out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n"); } for (State curState : nextStateMap.keySet()) { HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState); for (Transition curTran : stateTransitionPair.keySet()) { String curStateName = "S" + curState.getIndex(); String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex(); String curTranName = curTran.getName(); if (curTran.isFail() && !curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n"); else if (!curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n"); else if (curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n"); else out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } 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("enabledTrans")) { 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 printTransitionSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " "); 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 static void printAmpleSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " "); 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"); } } public HashMap<State,LpnTranList> copyEnabledSetTbl() { HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>(); for (State s : enabledSetTbl.keySet()) { LpnTranList tranList = enabledSetTbl.get(s).clone(); copyEnabledSetTbl.put(s.clone(), tranList); } return copyEnabledSetTbl; } public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) { this.enabledSetTbl = enabledSetTbl; } public HashMap<State, LpnTranList> getEnabledSetTbl() { return this.enabledSetTbl; } public HashMap<State, HashMap<Transition, State>> getNextStateMap() { return this.nextStateMap; } public TimedPrjState fire(final StateGraph[] curSgArray, final PrjState currentPrjState, Transition firedTran){ TimedPrjState currentTimedPrjState; // Check that this is a timed state. if(currentPrjState instanceof TimedPrjState){ currentTimedPrjState = (TimedPrjState) currentPrjState; } else{ throw new IllegalArgumentException(); } // Extract relevant information from the current project state. State[] curStateArray = currentTimedPrjState.toStateArray(); Zone[] currentZones = currentTimedPrjState.toZoneArray(); // Zone[] newZones = new Zone[curStateArray.length]; Zone[] newZones = new Zone[1]; // Get the new un-timed local states. State[] newStates = fire(curSgArray, curStateArray, firedTran); LpnTranList enabledTransitions = new LpnTranList(); for(int i=0; i<newStates.length; i++) { // enabledTransitions = getEnabled(newStates[i]); // TODO : The stategraph has to be used to call getEnabled // since it is being passed implicitly. LpnTranList localEnabledTransitions = curSgArray[i].getEnabled(newStates[i]); for(int j=0; j<localEnabledTransitions.size(); j++){ enabledTransitions.add(localEnabledTransitions.get(j)); } // newZones[i] = currentZones[i].fire(firedTran, // enabledTransitions, newStates); } newZones[0] = currentZones[0].fire(firedTran, enabledTransitions, newStates); return new TimedPrjState(newStates, newZones); } }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import com.facebook.R; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.reference.Reference; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.view.View.MeasureSpec.makeMeasureSpec; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState; import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_MOUNT; import static com.facebook.litho.ComponentsLogger.EVENT_PREPARE_MOUNT; import static com.facebook.litho.ComponentsLogger.EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH; import static com.facebook.litho.ComponentsLogger.PARAM_IS_DIRTY; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_MOUNTED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_MOVED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_NO_OP_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UNCHANGED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UNMOUNTED_COUNT; import static com.facebook.litho.ComponentsLogger.PARAM_UPDATED_COUNT; import static com.facebook.litho.ThreadUtils.assertMainThread; /** * Encapsulates the mounted state of a {@link Component}. Provides APIs to update state * by recycling existing UI elements e.g. {@link Drawable}s. * * @see #mount(LayoutState, Rect) * @see ComponentView * @see LayoutState */ class MountState { static final int ROOT_HOST_ID = 0; // Holds the current list of mounted items. // Should always be used within a draw lock. private final LongSparseArray<MountItem> mIndexToItemMap; // Holds a list with information about the components linked to the VisibilityOutputs that are // stored in LayoutState. An item is inserted in this map if its corresponding component is // visible. When the component exits the viewport, the item associated with it is removed from the // map. private final LongSparseArray<VisibilityItem> mVisibilityIdToItemMap; // Holds a list of MountItems that are currently mounted which can mount incrementally. private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems; // A map from test key to a list of one or more `TestItem`s which is only allocated // and populated during test runs. private final Map<String, Deque<TestItem>> mTestItemMap; private long[] mLayoutOutputsIds; // True if we are receiving a new LayoutState and we need to completely // refresh the content of the HostComponent. Always set from the main thread. private boolean mIsDirty; // Holds the list of known component hosts during a mount pass. private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>(); private static final Rect sTempRect = new Rect(); private final ComponentContext mContext; private final ComponentView mComponentView; private final Rect mPreviousLocalVisibleRect = new Rect(); private final PrepareMountStats mPrepareMountStats = new PrepareMountStats(); private final MountStats mMountStats = new MountStats(); private TransitionManager mTransitionManager; private int mPreviousTopsIndex; private int mPreviousBottomsIndex; private int mLastMountedComponentTreeId; private final MountItem mRootHostMountItem; public MountState(ComponentView view) { mIndexToItemMap = new LongSparseArray<>(); mVisibilityIdToItemMap = new LongSparseArray<>(); mCanMountIncrementallyMountItems = new LongSparseArray<>(); mContext = (ComponentContext) view.getContext(); mComponentView = view; mIsDirty = true; mTestItemMap = ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null; // The mount item representing the top-level ComponentView which // is always automatically mounted. mRootHostMountItem = ComponentsPools.acquireRootHostMountItem( HostComponent.create(), mComponentView, mComponentView); } /** * To be called whenever the components needs to start the mount process from scratch * e.g. when the component's props or layout change or when the components * gets attached to a host. */ void setDirty() { assertMainThread(); mIsDirty = true; mPreviousLocalVisibleRect.setEmpty(); } boolean isDirty() { assertMainThread(); return mIsDirty; } /** * Mount the layoutState on the pre-set HostView. * @param layoutState * @param localVisibleRect If this variable is null, then mount everything, since incremental * mount is not enabled. * Otherwise mount only what the rect (in local coordinates) contains */ void mount(LayoutState layoutState, Rect localVisibleRect) { assertMainThread(); ComponentsSystrace.beginSection("mount"); final ComponentTree componentTree = mComponentView.getComponent(); final ComponentsLogger logger = componentTree.getContext().getLogger(); if (logger != null) { logger.eventStart(EVENT_MOUNT, componentTree); } prepareTransitionManager(layoutState); if (mTransitionManager != null) { if (mIsDirty) { mTransitionManager.onNewTransitionContext(layoutState.getTransitionContext()); } mTransitionManager.onMountStart(); recordMountedItemsWithTransitionKeys( mTransitionManager, mIndexToItemMap, true /* isPreMount */); } if (mIsDirty) { suppressInvalidationsOnHosts(true); // Prepare the data structure for the new LayoutState and removes mountItems // that are not present anymore if isUpdateMountInPlace is enabled. prepareMount(layoutState); } mMountStats.reset(); final int componentTreeId = layoutState.getComponentTreeId(); final boolean isIncrementalMountEnabled = localVisibleRect != null; if (!isIncrementalMountEnabled || !performIncrementalMount(layoutState, localVisibleRect)) { for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) { final LayoutOutput layoutOutput = layoutState.getMountableOutputAt(i); final Component component = layoutOutput.getComponent(); ComponentsSystrace.beginSection(component.getSimpleName()); final MountItem currentMountItem = getItemAt(i); final boolean isMounted = currentMountItem != null; final boolean isMountable = !isIncrementalMountEnabled || isMountedHostWithChildContent(currentMountItem) || Rect.intersects(localVisibleRect, layoutOutput.getBounds()); if (isMountable && !isMounted) { mountLayoutOutput(i, layoutOutput, layoutState); } else if (!isMountable && isMounted) { unmountItem(mContext, i, mHostsByMarker); } else if (isMounted) { if (isIncrementalMountEnabled && canMountIncrementally(component)) { mountItemIncrementally(currentMountItem, layoutOutput.getBounds(), localVisibleRect); } if (mIsDirty) { final boolean useUpdateValueFromLayoutOutput = (componentTreeId >= 0) && (componentTreeId == mLastMountedComponentTreeId); final boolean itemUpdated = updateMountItemIfNeeded( layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput, logger); if (itemUpdated) { mMountStats.updatedCount++; } else { mMountStats.noOpCount++; } } } ComponentsSystrace.endSection(); } if (isIncrementalMountEnabled) { setupPreviousMountableOutputData(layoutState, localVisibleRect); } } mIsDirty = false; if (localVisibleRect != null) { mPreviousLocalVisibleRect.set(localVisibleRect); } processVisibilityOutputs(layoutState, localVisibleRect); if (mTransitionManager != null) { recordMountedItemsWithTransitionKeys( mTransitionManager, mIndexToItemMap, false /* isPreMount */); mTransitionManager.processTransitions(); } processTestOutputs(layoutState); suppressInvalidationsOnHosts(false); mLastMountedComponentTreeId = componentTreeId; if (logger != null) { final String logTag = componentTree.getContext().getLogTag(); logMountEnd(logger, logTag, componentTree, mMountStats); } ComponentsSystrace.endSection(); } private void processVisibilityOutputs(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect == null) { return; } for (int j = 0, size = layoutState.getVisibilityOutputCount(); j < size; j++) { final VisibilityOutput visibilityOutput = layoutState.getVisibilityOutputAt(j); final EventHandler visibleHandler = visibilityOutput.getVisibleEventHandler(); final EventHandler focusedHandler = visibilityOutput.getFocusedEventHandler(); final EventHandler fullImpressionHandler = visibilityOutput.getFullImpressionEventHandler(); final EventHandler invisibleHandler = visibilityOutput.getInvisibleEventHandler(); final long visibilityOutputId = visibilityOutput.getId(); final Rect visibilityOutputBounds = visibilityOutput.getBounds(); sTempRect.set(visibilityOutputBounds); final boolean isCurrentlyVisible = sTempRect.intersect(localVisibleRect); VisibilityItem visibilityItem = mVisibilityIdToItemMap.get(visibilityOutputId); if (isCurrentlyVisible) { // The component is visible now, but used to be outside the viewport. if (visibilityItem == null) { visibilityItem = ComponentsPools.acquireVisibilityItem(invisibleHandler); mVisibilityIdToItemMap.put(visibilityOutputId, visibilityItem); if (visibleHandler != null) { EventDispatcherUtils.dispatchOnVisible(visibleHandler); } } // Check if the component has entered the focused range. if (focusedHandler != null && !visibilityItem.isInFocusedRange()) { final View parent = (View) mComponentView.getParent(); if (hasEnteredFocusedRange( parent.getWidth(), parent.getHeight(), visibilityOutputBounds, sTempRect)) { visibilityItem.setIsInFocusedRange(); EventDispatcherUtils.dispatchOnFocused(focusedHandler); } } // If the component has not entered the full impression range yet, make sure to update the // information about the visible edges. if (fullImpressionHandler != null && !visibilityItem.isInFullImpressionRange()) { visibilityItem.setVisibleEdges(visibilityOutputBounds, sTempRect); if (visibilityItem.isInFullImpressionRange()) { EventDispatcherUtils.dispatchOnFullImpression(fullImpressionHandler); } } } else if (visibilityItem != null) { // The component is invisible now, but used to be visible. if (invisibleHandler != null) { EventDispatcherUtils.dispatchOnInvisible(invisibleHandler); } mVisibilityIdToItemMap.remove(visibilityOutputId); ComponentsPools.release(visibilityItem); } } } /** * Clears and re-populates the test item map if we are in e2e test mode. */ private void processTestOutputs(LayoutState layoutState) { if (mTestItemMap == null) { return; } for (Collection<TestItem> items : mTestItemMap.values()) { for (TestItem item : items) { ComponentsPools.release(item); } } mTestItemMap.clear(); for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) { final TestOutput testOutput = layoutState.getTestOutputAt(i); final long hostMarker = testOutput.getHostMarker(); final long layoutOutputId = testOutput.getLayoutOutputId(); final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId); final TestItem testItem = ComponentsPools.acquireTestItem(); testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker)); testItem.setBounds(testOutput.getBounds()); testItem.setTestKey(testOutput.getTestKey()); testItem.setContent(mountItem == null ? null : mountItem.getContent()); final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey()); final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items; updatedItems.add(testItem); mTestItemMap.put(testOutput.getTestKey(), updatedItems); } } private boolean isMountedHostWithChildContent(MountItem mountItem) { if (mountItem == null) { return false; } final Object content = mountItem.getContent(); if (!(content instanceof ComponentHost)) { return false; } final ComponentHost host = (ComponentHost) content; return host.getMountItemCount() > 0; } private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) { if (localVisibleRect.isEmpty()) { return; } final ArrayList<LayoutOutput> layoutOutputTops = layoutState.getMountableOutputTops(); final ArrayList<LayoutOutput> layoutOutputBottoms = layoutState.getMountableOutputBottoms(); final int mountableOutputCount = layoutState.getMountableOutputCount(); mPreviousTopsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) { mPreviousTopsIndex = i; break; } } mPreviousBottomsIndex = layoutState.getMountableOutputCount(); for (int i = 0; i < mountableOutputCount; i++) { if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) { mPreviousBottomsIndex = i; break; } } } private void clearVisibilityItems() { for (int i = mVisibilityIdToItemMap.size() - 1; i >= 0; i final VisibilityItem visibilityItem = mVisibilityIdToItemMap.valueAt(i); final EventHandler invisibleHandler = visibilityItem.getInvisibleHandler(); if (invisibleHandler != null) { EventDispatcherUtils.dispatchOnInvisible(invisibleHandler); } mVisibilityIdToItemMap.removeAt(i); ComponentsPools.release(visibilityItem); } } private void registerHost(long id, ComponentHost host) { host.suppressInvalidations(true); mHostsByMarker.put(id, host); } /** * Returns true if the component has entered the focused visible range. */ static boolean hasEnteredFocusedRange( int viewportWidth, int viewportHeight, Rect componentBounds, Rect componentVisibleBounds) { final int halfViewportArea = viewportWidth * viewportHeight / 2; final int totalComponentArea = computeRectArea(componentBounds); final int visibleComponentArea = computeRectArea(componentVisibleBounds); // The component has entered the focused range either if it is larger than half of the viewport // and it occupies at least half of the viewport or if it is smaller than half of the viewport // and it is fully visible. return (totalComponentArea >= halfViewportArea) ? (visibleComponentArea >= halfViewportArea) : componentBounds.equals(componentVisibleBounds); } private static int computeRectArea(Rect rect) { return rect.isEmpty() ? 0 : (rect.width() * rect.height()); } private void suppressInvalidationsOnHosts(boolean suppressInvalidations) { for (int i = mHostsByMarker.size() - 1; i >= 0; i mHostsByMarker.valueAt(i).suppressInvalidations(suppressInvalidations); } } private boolean updateMountItemIfNeeded( LayoutOutput layoutOutput, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, ComponentsLogger logger) { final Component layoutOutputComponent = layoutOutput.getComponent(); final Component itemComponent = currentMountItem.getComponent(); // 1. Check if the mount item generated from the old component should be updated. final boolean shouldUpdate = shouldUpdateMountItem( layoutOutput, currentMountItem, useUpdateValueFromLayoutOutput, mIndexToItemMap, mLayoutOutputsIds, logger); // 2. Reset all the properties like click handler, content description and tags related to // this item if it needs to be updated. the update mount item will re-set the new ones. if (shouldUpdate) { unsetViewAttributes(currentMountItem); } // 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound. if (currentMountItem.isBound()) { itemComponent.getLifecycle().onUnbind( itemComponent.getScopedContext(), currentMountItem.getContent(), itemComponent); currentMountItem.setIsBound(false); } // 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput currentMountItem.init(layoutOutput.getComponent(), currentMountItem, layoutOutput); // 5. If the mount item is not valid for this component update its content and view attributes. if (shouldUpdate) { updateMountedContent(currentMountItem, layoutOutput, itemComponent); setViewAttributes(currentMountItem); } final Object currentContent = currentMountItem.getContent(); // 6. Set the mounted content on the Component and call the bind callback. layoutOutputComponent.getLifecycle().bind( layoutOutputComponent.getScopedContext(), currentContent, layoutOutputComponent); currentMountItem.setIsBound(true); // 7. Update the bounds of the mounted content. This needs to be done regardless of whether // the component has been updated or not since the mounted item might might have the same // size and content but a different position. updateBoundsForMountedLayoutOutput(layoutOutput, currentMountItem); maybeInvalidateAccessibilityState(currentMountItem); if (currentMountItem.getContent() instanceof Drawable) { maybeSetDrawableState( currentMountItem.getHost(), (Drawable) currentMountItem.getContent(), currentMountItem.getFlags(), currentMountItem.getNodeInfo()); } if (currentMountItem.getDisplayListDrawable() != null) { currentMountItem.getDisplayListDrawable().suppressInvalidations(false); } return shouldUpdate; } private static boolean shouldUpdateMountItem( LayoutOutput layoutOutput, MountItem currentMountItem, boolean useUpdateValueFromLayoutOutput, LongSparseArray<MountItem> indexToItemMap, long[] layoutOutputsIds, ComponentsLogger logger) { final @LayoutOutput.UpdateState int updateState = layoutOutput.getUpdateState(); final Component currentComponent = currentMountItem.getComponent(); final ComponentLifecycle currentLifecycle = currentComponent.getLifecycle(); final Component nextComponent = layoutOutput.getComponent(); final ComponentLifecycle nextLifecycle = nextComponent.getLifecycle(); // If the two components have different sizes and the mounted content depends on the size we // just return true immediately. if (!sameSize(layoutOutput, currentMountItem) && nextLifecycle.isMountSizeDependent()) { return true; } if (useUpdateValueFromLayoutOutput) { if (updateState == LayoutOutput.STATE_UPDATED) { // Check for incompatible ReferenceLifecycle. if (currentLifecycle instanceof DrawableComponent && nextLifecycle instanceof DrawableComponent && currentLifecycle.shouldComponentUpdate(currentComponent, nextComponent)) { if (logger != null) { ComponentsLogger.LayoutOutputLog logObj = new ComponentsLogger.LayoutOutputLog(); logObj.currentId = indexToItemMap.keyAt( indexToItemMap.indexOfValue(currentMountItem)); logObj.currentLifecycle = currentLifecycle.toString(); logObj.nextId = layoutOutput.getId(); logObj.nextLifecycle = nextLifecycle.toString(); for (int i = 0; i < layoutOutputsIds.length; i++) { if (layoutOutputsIds[i] == logObj.currentId) { if (logObj.currentIndex == -1) { logObj.currentIndex = i; } logObj.currentLastDuplicatedIdIndex = i; } } if (logObj.nextId == logObj.currentId) { logObj.nextIndex = logObj.currentIndex; logObj.nextLastDuplicatedIdIndex = logObj.currentLastDuplicatedIdIndex; } else { for (int i = 0; i < layoutOutputsIds.length; i++) { if (layoutOutputsIds[i] == logObj.nextId) { if (logObj.nextIndex == -1) { logObj.nextIndex = i; } logObj.nextLastDuplicatedIdIndex = i; } } } logger.eventStart(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj); logger .eventEnd(EVENT_SHOULD_UPDATE_REFERENCE_LAYOUT_MISMATCH, logObj, ACTION_SUCCESS); } return true; } return false; } else if (updateState == LayoutOutput.STATE_DIRTY) { return true; } } if (!currentLifecycle.callsShouldUpdateOnMount()) { return true; } return currentLifecycle.shouldComponentUpdate( currentComponent, nextComponent); } private static boolean sameSize(LayoutOutput layoutOutput, MountItem item) { final Rect layoutOutputBounds = layoutOutput.getBounds(); final Object mountedContent = item.getContent(); return layoutOutputBounds.width() == getWidthForMountedContent(mountedContent) && layoutOutputBounds.height() == getHeightForMountedContent(mountedContent); } private static int getWidthForMountedContent(Object content) { return content instanceof Drawable ? ((Drawable) content).getBounds().width() : ((View) content).getWidth(); } private static int getHeightForMountedContent(Object content) { return content instanceof Drawable ? ((Drawable) content).getBounds().height() : ((View) content).getHeight(); } private void updateBoundsForMountedLayoutOutput(LayoutOutput layoutOutput, MountItem item) { // MountState should never update the bounds of the top-level host as this // should be done by the ViewGroup containing the ComponentView. if (layoutOutput.getId() == ROOT_HOST_ID) { return; } layoutOutput.getMountBounds(sTempRect); final boolean forceTraversal = Component.isMountViewSpec(layoutOutput.getComponent()) && ((View) item.getContent()).isLayoutRequested(); applyBoundsToMountContent( item.getContent(), sTempRect.left, sTempRect.top, sTempRect.right, sTempRect.bottom, forceTraversal /* force */); } /** * Prepare the {@link MountState} to mount a new {@link LayoutState}. */ @SuppressWarnings("unchecked") private void prepareMount(LayoutState layoutState) { final ComponentTree component = mComponentView.getComponent(); final ComponentsLogger logger = component.getContext().getLogger(); final String logTag = component.getContext().getLogTag(); if (logger != null) { logger.eventStart(EVENT_PREPARE_MOUNT, component); } PrepareMountStats stats = unmountOrMoveOldItems(layoutState); if (logger != null) { logPrepareMountParams(logger, logTag, component, stats); } if (mHostsByMarker.get(ROOT_HOST_ID) == null) { // Mounting always starts with the root host. registerHost(ROOT_HOST_ID, mComponentView); // Root host is implicitly marked as mounted. mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem); } int outputCount = layoutState.getMountableOutputCount(); if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) { mLayoutOutputsIds = new long[layoutState.getMountableOutputCount()]; } for (int i = 0; i < outputCount; i++) { mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getId(); } if (logger != null) { logger.eventEnd(EVENT_PREPARE_MOUNT, component, ACTION_SUCCESS); } } /** * Determine whether to apply disappear animation to the given {@link MountItem} */ private static boolean isItemDisappearing( MountItem mountItem, TransitionContext transitionContext) { if (mountItem == null || mountItem.getViewNodeInfo() == null || transitionContext == null) { return false; } return transitionContext.isDisappearingKey(mountItem.getViewNodeInfo().getTransitionKey()); } /** * Go over all the mounted items from the leaves to the root and unmount only the items that are * not present in the new LayoutOutputs. * If an item is still present but in a new position move the item inside its host. * The condition where an item changed host doesn't need any special treatment here since we * mark them as removed and re-added when calculating the new LayoutOutputs */ private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) { mPrepareMountStats.reset(); if (mLayoutOutputsIds == null) { return mPrepareMountStats; } // Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there // but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively // all its mounted children. for (int i = 0; i < mLayoutOutputsIds.length; i++) { final int newPosition = newLayoutState.getLayoutOutputPositionForId(mLayoutOutputsIds[i]); final MountItem oldItem = getItemAt(i); if (isItemDisappearing(oldItem, newLayoutState.getTransitionContext())) { startUnmountDisappearingItem(i, oldItem.getViewNodeInfo().getTransitionKey()); final int lastDescendantOfItem = findLastDescendantOfItem(i, oldItem); // Disassociate disappearing items from current mounted items. The layout tree will not // contain disappearing items anymore, however they are kept separately in their hosts. removeDisappearingItemMappings(i, lastDescendantOfItem); // Skip this disappearing item and all its descendants. Do not unmount or move them yet. // We will unmount them after animation is completed. i = lastDescendantOfItem; continue; } if (newPosition == -1) { unmountItem(mContext, i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else { final long newHostMarker = newLayoutState.getMountableOutputAt(newPosition).getHostMarker(); if (oldItem == null) { // This was previously unmounted. mPrepareMountStats.unmountedCount++; } else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) { // If the id is the same but the parent host is different we simply unmount the item and // re-mount it later. If the item to unmount is a ComponentHost, all the children will be // recursively unmounted. unmountItem(mContext, i, mHostsByMarker); mPrepareMountStats.unmountedCount++; } else if (newPosition != i) { // If a MountItem for this id exists and the hostMarker has not changed but its position // in the outputs array has changed we need to update the position in the Host to ensure // the z-ordering. oldItem.getHost().moveItem(oldItem, i, newPosition);
package hex; import hex.ensemble.StackedEnsemble; import hex.ensemble.StackedEnsembleMojoWriter; import hex.genmodel.utils.DistributionFamily; import hex.glm.GLMModel; import hex.tree.drf.DRFModel; import water.*; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Frame; import water.fvec.Vec; import water.nbhm.NonBlockingHashSet; import water.udf.CFuncRef; import water.util.Log; import water.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.Arrays; import static hex.Model.Parameters.FoldAssignmentScheme.AUTO; import static hex.Model.Parameters.FoldAssignmentScheme.Random; public class StackedEnsembleModel extends Model<StackedEnsembleModel,StackedEnsembleModel.StackedEnsembleParameters,StackedEnsembleModel.StackedEnsembleOutput> { // common parameters for the base models: public ModelCategory modelCategory; public long trainingFrameRows = -1; public String responseColumn = null; private NonBlockingHashSet<String> names = null; // keep columns as a set for easier comparison //public int nfolds = -1; //From 1st base model // Get from 1st base model (should be identical across base models) public int basemodel_nfolds = -1; //From 1st base model public Parameters.FoldAssignmentScheme basemodel_fold_assignment; //From 1st base model public String basemodel_fold_column; //From 1st base model public long seed = -1; //From 1st base model // TODO: add a separate holdout dataset for the ensemble // TODO: add a separate overall cross-validation for the ensemble, including _fold_column and FoldAssignmentScheme / _fold_assignment public StackedEnsembleModel(Key selfKey, StackedEnsembleParameters parms, StackedEnsembleOutput output) { super(selfKey, parms, output); } public static class StackedEnsembleParameters extends Model.Parameters { public String algoName() { return "StackedEnsemble"; } public String fullName() { return "Stacked Ensemble"; } public String javaName() { return StackedEnsembleModel.class.getName(); } @Override public long progressUnits() { return 1; } // TODO // base_models is a list of base model keys to ensemble (must have been cross-validated) public Key<Model> _base_models[] = new Key[0]; // Should we keep the level-one frame of cv preds + repsonse col? public boolean _keep_levelone_frame = false; // Metalearner params public int _metalearner_nfolds; public Parameters.FoldAssignmentScheme _metalearner_fold_assignment; public String _metalearner_fold_column; //What to use as a metalearner (GLM, GBM, DRF, or DeepLearning) public enum MetalearnerAlgorithm { AUTO, glm, gbm, drf, deeplearning } public MetalearnerAlgorithm _metalearner_algorithm = MetalearnerAlgorithm.AUTO; } public static class StackedEnsembleOutput extends Model.Output { public StackedEnsembleOutput() { super(); } public StackedEnsembleOutput(StackedEnsemble b) { super(b); } public StackedEnsembleOutput(Job job) { _job = job; } // The metalearner model (e.g., a GLM that has a coefficient for each of the base_learners). public Model _metalearner; public Frame _levelone_frame_id; } /** * For StackedEnsemble we call score on all the base_models and then combine the results * with the metalearner to create the final predictions frame. * * @see Model#predictScoreImpl(Frame, Frame, String, Job, boolean, CFuncRef) * @param adaptFrm Already adapted frame * @param computeMetrics * @return A Frame containing the prediction column, and class distribution */ @Override protected Frame predictScoreImpl(Frame fr, Frame adaptFrm, String destination_key, Job j, boolean computeMetrics, CFuncRef customMetricFunc) { // Build up the names & domains. String[] names = makeScoringNames(); String[][] domains = new String[names.length][]; domains[0] = names.length == 1 ? null : computeMetrics ? _output._domains[_output._domains.length-1] : adaptFrm.lastVec().domain(); // TODO: optimize these DKV lookups: Frame levelOneFrame = new Frame(Key.<Frame>make("preds_levelone_" + this._key.toString() + fr._key)); int baseIdx = 0; Frame[] base_prediction_frames = new Frame[this._parms._base_models.length]; // TODO: don't score models that have 0 coefficients / aren't used by the metalearner. for (Key<Model> baseKey : this._parms._base_models) { Model base = baseKey.get(); // TODO: cacheme! // adapt fr for each base_model // TODO: cache: don't need to call base.adaptTestForTrain() if the // base_model has the same names and domains as one we've seen before. // Such base_models can share their adapted frame. Frame adaptedFrame = new Frame(fr); base.adaptTestForTrain(adaptedFrame, true, computeMetrics); // TODO: parallel scoring for the base_models BigScore baseBs = (BigScore) base.makeBigScoreTask(domains, names, adaptedFrame, computeMetrics, true, j, customMetricFunc).doAll(names.length, Vec.T_NUM, adaptedFrame); Frame basePreds = baseBs.outputFrame(Key.<Frame>make("preds_base_" + this._key.toString() + fr._key), names, domains); //Need to remove 'predict' column from multinomial since it contains outcome if (base._output.isMultinomialClassifier()) { basePreds.remove("predict"); } base_prediction_frames[baseIdx] = basePreds; StackedEnsemble.addModelPredictionsToLevelOneFrame(base, basePreds, levelOneFrame); DKV.remove(basePreds._key); //Cleanup Frame.deleteTempFrameAndItsNonSharedVecs(adaptedFrame, fr); baseIdx++; } // Add response column to level one frame levelOneFrame.add(this.responseColumn, adaptFrm.vec(this.responseColumn)); // TODO: what if we're running multiple in parallel and have a name collision? Log.info("Finished creating \"level one\" frame for scoring: " + levelOneFrame.toString()); // Score the dataset, building the class distribution & predictions Model metalearner = this._output._metalearner; Frame levelOneAdapted = new Frame(levelOneFrame); metalearner.adaptTestForTrain(levelOneAdapted, true, computeMetrics); String[] metaNames = metalearner.makeScoringNames(); String[][] metaDomains = new String[metaNames.length][]; metaDomains[0] = metaNames.length == 1 ? null : !computeMetrics ? metalearner._output._domains[metalearner._output._domains.length-1] : levelOneAdapted.lastVec().domain(); BigScore metaBs = (BigScore) metalearner.makeBigScoreTask(metaDomains, metaNames, levelOneAdapted, computeMetrics, true, j, CFuncRef.from(_parms._custom_metric_func)). doAll(metaNames.length, Vec.T_NUM, levelOneAdapted); if (computeMetrics) { ModelMetrics mmMetalearner = metaBs._mb.makeModelMetrics(metalearner, levelOneFrame, levelOneAdapted, metaBs.outputFrame()); // This has just stored a ModelMetrics object for the (metalearner, preds_levelone) Model/Frame pair. // We need to be able to look it up by the (this, fr) pair. // The ModelMetrics object for the metalearner will be removed when the metalearner is removed. ModelMetrics mmStackedEnsemble = mmMetalearner.deepCloneWithDifferentModelAndFrame(this, fr); this.addModelMetrics(mmStackedEnsemble); } Frame.deleteTempFrameAndItsNonSharedVecs(levelOneAdapted, levelOneFrame); return metaBs.outputFrame(Key.<Frame>make(destination_key), metaNames, metaDomains); } /** * Should never be called: the code paths that normally go here should call predictScoreImpl(). * @see Model#score0(double[], double[]) */ @Override protected double[] score0(double data[/*ncols*/], double preds[/*nclasses+1*/]) { throw new UnsupportedOperationException("StackedEnsembleModel.score0() should never be called: the code paths that normally go here should call predictScoreImpl()."); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { throw new UnsupportedOperationException("StackedEnsembleModel.makeMetricBuilder should never be called!"); } public ModelMetrics doScoreMetricsOneFrame(Frame frame, Job job) { Frame pred = this.predictScoreImpl(frame, new Frame(frame), null, job, true, CFuncRef.from(_parms._custom_metric_func)); pred.remove(); return ModelMetrics.getFromDKV(this, frame); } public void doScoreOrCopyMetrics(Job job) { // To get ensemble training metrics, the training frame needs to be re-scored since // training metrics from metalearner are not equal to ensemble training metrics. // The training metrics for the metalearner do not reflect true ensemble training metrics because // the metalearner was trained on cv preds, not training preds. So, rather than clone the metalearner // training metrics, we have to re-score the training frame on all the base models, then send these // biased preds through to the metalearner, and then compute the metrics there. this._output._training_metrics = doScoreMetricsOneFrame(this._parms.train(), job); // Validation metrics can be copied from metalearner (may be null). // Validation frame was already piped through so there's no need to re-do that to get the same results. this._output._validation_metrics = this._output._metalearner._output._validation_metrics; // Cross-validation metrics can be copied from metalearner (may be null). // For cross-validation metrics, we use metalearner cross-validation metrics as a proxy for the ensemble // cross-validation metrics -- the true k-fold cv metrics for the ensemble would require training k sets of // cross-validated base models (rather than a single set of cross-validated base models), which is extremely // computationally expensive and awkward from the standpoint of the existing Stacked Ensemble API. this._output._cross_validation_metrics = this._output._metalearner._output._cross_validation_metrics; } private DistributionFamily distributionFamily(Model aModel) { // TODO: hack alert: In DRF, _parms._distribution is always set to multinomial. Yay. if (aModel instanceof DRFModel) if (aModel._output.isBinomialClassifier()) return DistributionFamily.bernoulli; else if (aModel._output.isClassifier()) return DistributionFamily.multinomial; else return DistributionFamily.gaussian; try { Field familyField = ReflectionUtils.findNamedField(aModel._parms, "_family"); Field distributionField = (familyField != null ? null : ReflectionUtils.findNamedField(aModel, "_dist")); if (null != familyField) { // GLM only, for now GLMModel.GLMParameters.Family thisFamily = (GLMModel.GLMParameters.Family) familyField.get(aModel._parms); if (thisFamily == GLMModel.GLMParameters.Family.binomial) { return DistributionFamily.bernoulli; } try { return Enum.valueOf(DistributionFamily.class, thisFamily.toString()); } catch (IllegalArgumentException e) { throw new H2OIllegalArgumentException("Don't know how to find the right DistributionFamily for Family: " + thisFamily); } } if (null != distributionField) { Distribution distribution = ((Distribution)distributionField.get(aModel)); DistributionFamily distributionFamily; if (null != distribution) distributionFamily = distribution.distribution; else distributionFamily = aModel._parms._distribution; // NOTE: If the algo does smart guessing of the distribution family we need to duplicate the logic here. if (distributionFamily == DistributionFamily.AUTO) { if (aModel._output.isBinomialClassifier()) distributionFamily = DistributionFamily.bernoulli; else if (aModel._output.isClassifier()) throw new H2OIllegalArgumentException("Don't know how to determine the distribution for a multinomial classifier."); else distributionFamily = DistributionFamily.gaussian; } // DistributionFamily.AUTO return distributionFamily; } throw new H2OIllegalArgumentException("Don't know how to stack models that have neither a distribution hyperparameter nor a family hyperparameter."); } catch (Exception e) { throw new H2OIllegalArgumentException(e.toString(), e.toString()); } } public void checkAndInheritModelProperties() { if (null == _parms._base_models || 0 == _parms._base_models.length) throw new H2OIllegalArgumentException("When creating a StackedEnsemble you must specify one or more models; found 0."); if (null != _parms._metalearner_fold_column && 0 != _parms._metalearner_nfolds) throw new H2OIllegalArgumentException("Cannot specify fold_column and nfolds at the same time."); Model aModel = null; boolean beenHere = false; trainingFrameRows = _parms.train().numRows(); for (Key<Model> k : _parms._base_models) { aModel = DKV.getGet(k); if (null == aModel) { Log.warn("Failed to find base model; skipping: " + k); continue; } if (!aModel.isSupervised()) { throw new H2OIllegalArgumentException("Base model is not supervised: " + aModel._key.toString()); } if (beenHere) { // check that the base models are all consistent with first based model if (modelCategory != aModel._output.getModelCategory()) throw new H2OIllegalArgumentException("Base models are inconsistent: there is a mix of different categories of models: " + Arrays.toString(_parms._base_models)); // NOTE: if we loosen this restriction and fold_column is set add a check below. Frame aTrainingFrame = aModel._parms.train(); if (trainingFrameRows != aTrainingFrame.numRows() && !this._parms._is_cv_model) throw new H2OIllegalArgumentException("Base models are inconsistent: they use different size(number of rows) training frames. Found number of rows: " + trainingFrameRows + " and: " + aTrainingFrame.numRows() + "."); if (! responseColumn.equals(aModel._parms._response_column)) throw new H2OIllegalArgumentException("Base models are inconsistent: they use different response columns. Found: " + responseColumn + " and: " + aModel._parms._response_column + "."); // TODO: we currently require xval; loosen this iff we add a separate holdout dataset for the ensemble if (aModel._parms._fold_assignment != basemodel_fold_assignment) { if ((aModel._parms._fold_assignment == AUTO && basemodel_fold_assignment == Random) || (aModel._parms._fold_assignment == Random && basemodel_fold_assignment == AUTO)) { // A-ok } else { throw new H2OIllegalArgumentException("Base models are inconsistent: they use different fold_assignments."); } } // If we have a fold_column make sure nfolds from base models are consistent if (aModel._parms._fold_column == null && basemodel_nfolds != aModel._parms._nfolds) throw new H2OIllegalArgumentException("Base models are inconsistent: they use different values for nfolds."); // If we don't have a fold_column require nfolds > 1 if (aModel._parms._fold_column == null && aModel._parms._nfolds < 2) throw new H2OIllegalArgumentException("Base model does not use cross-validation: " + aModel._parms._nfolds); // NOTE: we already check that the training_frame checksums are the same, so // we don't need to check the Vec checksums here: if (aModel._parms._fold_column != null && ! aModel._parms._fold_column.equals(basemodel_fold_column)) throw new H2OIllegalArgumentException("Base models are inconsistent: they use different fold_columns."); if (aModel._parms._fold_column == null && basemodel_fold_assignment == Random && aModel._parms._seed != seed) throw new H2OIllegalArgumentException("Base models are inconsistent: they use random-seeded k-fold cross-validation but have different seeds."); if (! aModel._parms._keep_cross_validation_predictions) throw new H2OIllegalArgumentException("Base model does not keep cross-validation predictions: " + aModel._parms._nfolds); // In GLM, we get _family instead of _distribution. // Further, we have Family.binomial instead of DistributionFamily.bernoulli. // We also handle DistributionFamily.AUTO in distributionFamily() // Hack alert: DRF only does Bernoulli and Gaussian, so only compare _domains.length above. if (! (aModel instanceof DRFModel) && distributionFamily(aModel) != distributionFamily(this)) Log.warn("Base models are inconsistent; they use different distributions: " + distributionFamily(this) + " and: " + distributionFamily(aModel) + ". Is this intentional?"); // TODO: If we're set to DistributionFamily.AUTO then GLM might auto-conform the response column // giving us inconsistencies. } else { // !beenHere: this is the first base_model this.modelCategory = aModel._output.getModelCategory(); this._dist = new Distribution(distributionFamily(aModel)); _output._domains = Arrays.copyOf(aModel._output._domains, aModel._output._domains.length); // TODO: set _parms._train to aModel._parms.train() _output.setNames(aModel._output._names); this.names = new NonBlockingHashSet<>(); this.names.addAll(Arrays.asList(aModel._output._names)); responseColumn = aModel._parms._response_column; if (! responseColumn.equals(_parms._response_column)) throw new H2OIllegalArgumentException("StackedModel response_column must match the response_column of each base model. Found: " + responseColumn + " and: " + _parms._response_column); basemodel_nfolds = aModel._parms._nfolds; basemodel_fold_assignment = aModel._parms._fold_assignment; if (basemodel_fold_assignment == AUTO) basemodel_fold_assignment = Random; basemodel_fold_column = aModel._parms._fold_column; seed = aModel._parms._seed; _parms._distribution = aModel._parms._distribution; beenHere = true; } } // for all base_models if (null == aModel) throw new H2OIllegalArgumentException("When creating a StackedEnsemble you must specify one or more models; " + _parms._base_models.length + " were specified but none of those were found: " + Arrays.toString(_parms._base_models)); } // TODO: Are we leaking anything? @Override protected Futures remove_impl(Futures fs ) { if (_output._metalearner != null) DKV.remove(_output._metalearner._key, fs); return super.remove_impl(fs); } /** Write out models (base + metalearner) */ @Override protected AutoBuffer writeAll_impl(AutoBuffer ab) { //Metalearner ab.putKey(_output._metalearner._key); //Base Models for (Key<Model> ks : _parms._base_models) ab.putKey(ks); return super.writeAll_impl(ab); } /** Read in models (base + metalearner) */ @Override protected Keyed readAll_impl(AutoBuffer ab, Futures fs) { //Metalearner ab.getKey(_output._metalearner._key,fs); //Base Models for (Key<Model> ks : _parms._base_models) ab.getKey(ks,fs); return super.readAll_impl(ab,fs); } @Override public StackedEnsembleMojoWriter getMojo() { return new StackedEnsembleMojoWriter(this); } }
package org.jivesoftware.spark; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jivesoftware.MainWindowListener; import org.jivesoftware.Spark; import org.jivesoftware.spark.plugin.Plugin; import org.jivesoftware.spark.plugin.PluginClassLoader; import org.jivesoftware.spark.plugin.PublicPlugin; import org.jivesoftware.spark.util.URLFileSystem; import org.jivesoftware.spark.util.log.Log; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.concurrent.CopyOnWriteArrayList; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipFile; /** * This manager is responsible for the loading of all Plugins and Workspaces within Spark environment. * * @author Derek DeMoro */ public class PluginManager implements MainWindowListener { private final List<Plugin> plugins = new ArrayList<Plugin>(); private final List<PublicPlugin> publicPlugins = new CopyOnWriteArrayList<PublicPlugin>(); private static PluginManager singleton; private static final Object LOCK = new Object(); /** * The root Plugins Directory. */ public static File PLUGINS_DIRECTORY = new File(Spark.getBinDirectory().getParent(), "plugins").getAbsoluteFile(); private PluginClassLoader classLoader; /** * Returns the singleton instance of <CODE>PluginManager</CODE>, * creating it if necessary. * <p/> * * @return the singleton instance of <Code>PluginManager</CODE> */ public static PluginManager getInstance() { // Synchronize on LOCK to ensure that we don't end up creating // two singletons. synchronized (LOCK) { if (null == singleton) { PluginManager controller = new PluginManager(); singleton = controller; return controller; } } return singleton; } private PluginManager() { try { PLUGINS_DIRECTORY = new File(Spark.getBinDirectory().getParentFile(), "plugins").getCanonicalFile(); } catch (IOException e) { Log.error(e); } // Copy Files over if not on Windows. This is a workaround for installation issues. if (!Spark.isWindows()) { copyFiles(); } SparkManager.getMainWindow().addMainWindowListener(this); // Create the extension directory if one does not exist. if (!PLUGINS_DIRECTORY.exists()) { PLUGINS_DIRECTORY.mkdirs(); } } private void copyFiles() { // Current Plugin directory File newPlugins = new File(Spark.getLogDirectory().getParentFile(), "plugins").getAbsoluteFile(); newPlugins.mkdirs(); File[] files = PLUGINS_DIRECTORY.listFiles(); final int no = files != null ? files.length : 0; for (int i = 0; i < no; i++) { File file = files[i]; if (file.isFile()) { // Copy over File newFile = new File(newPlugins, file.getName()); try { URLFileSystem.copy(file.toURL(), newFile); } catch (IOException e) { Log.error(e); } } } PLUGINS_DIRECTORY = newPlugins; } /** * Loads all {@link Plugin} from the agent plugins.xml and extension lib. */ public void loadPlugins() { // Delete all old plugins File[] oldFiles = PLUGINS_DIRECTORY.listFiles(); final int no = oldFiles != null ? oldFiles.length : 0; for (int i = 0; i < no; i++) { File file = oldFiles[i]; if (file.isDirectory()) { // Check to see if it has an associated .jar File jarFile = new File(PLUGINS_DIRECTORY, file.getName() + ".jar"); if (!jarFile.exists()) { uninstall(file); } } } updateClasspath(); // At the moment, the plug list is hardcode internally until I begin // using external property files. All depends on deployment. final URL url = getClass().getClassLoader().getResource("META-INF/plugins.xml"); try { InputStreamReader reader = new InputStreamReader(url.openStream()); loadInternalPlugins(reader); } catch (IOException e) { Log.error("Could not load plugins.xml file."); } // Load extension plugins loadPublicPlugins(); // For development purposes, load the plugin specified by -Dplugin=... String plugin = System.getProperty("plugin"); if (plugin != null) { final StringTokenizer st = new StringTokenizer(plugin, ",", false); while (st.hasMoreTokens()) { String token = st.nextToken(); File pluginXML = new File(token); loadPublicPlugin(pluginXML.getParentFile()); } } } /** * Loads public plugins. * * @param pluginDir the directory of the expanded public plugin. * @return the new Plugin model for the Public Plugin. */ private Plugin loadPublicPlugin(File pluginDir) { File pluginFile = new File(pluginDir, "plugin.xml"); SAXReader saxReader = new SAXReader(); Document pluginXML = null; try { pluginXML = saxReader.read(pluginFile); } catch (DocumentException e) { Log.error(e); } Plugin pluginClass = null; List plugins = pluginXML.selectNodes("/plugin"); Iterator iter = plugins.iterator(); while (iter.hasNext()) { PublicPlugin publicPlugin = new PublicPlugin(); String clazz = null; String name = null; try { Element plugin = (Element)iter.next(); name = plugin.selectSingleNode("name").getText(); clazz = plugin.selectSingleNode("class").getText(); try { plugin.selectSingleNode("minSparkVersion").getText(); } catch (Exception e) { Log.error("Unable to load plugin " + name + " due to no minSparkVersion."); return null; } publicPlugin.setPluginClass(clazz); publicPlugin.setName(name); try { String version = plugin.selectSingleNode("version").getText(); publicPlugin.setVersion(version); String author = plugin.selectSingleNode("author").getText(); publicPlugin.setAuthor(author); String email = plugin.selectSingleNode("email").getText(); publicPlugin.setEmail(email); String description = plugin.selectSingleNode("description").getText(); publicPlugin.setDescription(description); String homePage = plugin.selectSingleNode("homePage").getText(); publicPlugin.setHomePage(homePage); } catch (Exception e) { Log.debug("We can ignore these."); } try { pluginClass = (Plugin)getParentClassLoader().loadClass(clazz).newInstance(); Log.debug(name + " has been loaded."); publicPlugin.setPluginDir(pluginDir); publicPlugins.add(publicPlugin); registerPlugin(pluginClass); } catch (Exception e) { Log.error("Unable to load plugin " + clazz + ".", e); } } catch (Exception ex) { Log.error("Unable to load plugin " + clazz + ".", ex); } } return pluginClass; } private void loadInternalPlugins(InputStreamReader reader) { SAXReader saxReader = new SAXReader(); Document pluginXML = null; try { pluginXML = saxReader.read(reader); } catch (DocumentException e) { Log.error(e); } List plugins = pluginXML.selectNodes("/plugins/plugin"); Iterator iter = plugins.iterator(); while (iter.hasNext()) { String clazz = null; String name = null; try { Element plugin = (Element)iter.next(); name = plugin.selectSingleNode("name").getText(); clazz = plugin.selectSingleNode("class").getText(); Plugin pluginClass = (Plugin)Class.forName(clazz).newInstance(); Log.debug(name + " has been loaded. Internal plugin."); registerPlugin(pluginClass); } catch (Exception ex) { Log.error("Unable to load plugin " + clazz + ".", ex); } } } private void updateClasspath() { try { classLoader = new PluginClassLoader(getParentClassLoader(), PLUGINS_DIRECTORY); } catch (MalformedURLException e) { Log.error("Error updating classpath.", e); } Thread.currentThread().setContextClassLoader(classLoader); } /** * Returns the plugin classloader. * * @return the plugin classloader. */ public ClassLoader getPluginClassLoader() { return classLoader; } /** * Registers a plugin. * * @param plugin the plugin to register. */ public void registerPlugin(Plugin plugin) { plugins.add(plugin); } /** * Removes a plugin from the plugin list. * * @param plugin the plugin to remove. */ public void removePlugin(Plugin plugin) { plugins.remove(plugin); } /** * Returns a Collection of Plugins. * * @return a Collection of Plugins. */ public Collection getPlugins() { return plugins; } /** * Returns the instance of the plugin class initialized during startup. * * @param communicatorPlugin the plugin to find. * @return the instance of the plugin. */ public Plugin getPlugin(Class communicatorPlugin) { Iterator iter = getPlugins().iterator(); while (iter.hasNext()) { Plugin plugin = (Plugin)iter.next(); if (plugin.getClass() == communicatorPlugin) { return plugin; } } return null; } /** * Loads and initalizes all Plugins. * * @see Plugin */ public void initializePlugins() { SwingUtilities.invokeLater(new Runnable() { public void run() { final Iterator iter = plugins.iterator(); while (iter.hasNext()) { long start = System.currentTimeMillis(); Plugin plugin = (Plugin)iter.next(); Log.debug("Trying to initialize " + plugin); plugin.initialize(); long end = System.currentTimeMillis(); Log.debug("Took " + (end - start) + " ms. to load " + plugin); } } }); } public void shutdown() { final Iterator pluginIter = plugins.iterator(); while (pluginIter.hasNext()) { Plugin plugin = (Plugin)pluginIter.next(); try { plugin.shutdown(); } catch (Exception e) { Log.warning("Exception on shutdown of plugin.", e); } } } public void mainWindowActivated() { } public void mainWindowDeactivated() { } /** * Locates the best class loader based on context (see class description). * * @return The best parent classloader to use */ private ClassLoader getParentClassLoader() { ClassLoader parent = Thread.currentThread().getContextClassLoader(); if (parent == null) { parent = this.getClass().getClassLoader(); if (parent == null) { parent = ClassLoader.getSystemClassLoader(); } } return parent; } private void expandNewPlugins() { File[] jars = PLUGINS_DIRECTORY.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { boolean accept = false; String smallName = name.toLowerCase(); if (smallName.endsWith(".jar")) { accept = true; } return accept; } }); // Do nothing if no jar or zip files were found if (jars == null) { return; } for (int i = 0; i < jars.length; i++) { if (jars[i].isFile()) { File file = jars[i]; URL url = null; try { url = file.toURL(); } catch (MalformedURLException e) { Log.error(e); } String name = URLFileSystem.getName(url); File directory = new File(PLUGINS_DIRECTORY, name); if (directory.exists() && directory.isDirectory()) { // Check to see if directory contains the plugin.xml file. // If not, delete directory. File pluginXML = new File(directory, "plugin.xml"); if (pluginXML.exists()) { if (pluginXML.lastModified() < file.lastModified()) { uninstall(directory); unzipPlugin(file, directory); } continue; } uninstall(directory); } else { // Unzip contents into directory unzipPlugin(file, directory); } } } } private void loadPublicPlugins() { // First, expand all plugins that have yet to be expanded. expandNewPlugins(); File[] files = PLUGINS_DIRECTORY.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return dir.isDirectory(); } }); // Do nothing if no jar or zip files were found if (files == null) { return; } for (int i = 0; i < files.length; i++) { File file = files[i]; File pluginXML = new File(file, "plugin.xml"); if (pluginXML.exists()) { try { classLoader.addPlugin(file); } catch (MalformedURLException e) { Log.error("Unable to load dirs", e); } loadPublicPlugin(file); } } } /** * Adds and installs a new plugin into Spark. * * @param plugin the plugin to install. * @throws Exception thrown if there was a problem loading the plugin. */ public void addPlugin(PublicPlugin plugin) throws Exception { expandNewPlugins(); URL url = new URL(plugin.getDownloadURL()); String name = URLFileSystem.getName(url); File pluginDownload = new File(PluginManager.PLUGINS_DIRECTORY, name); classLoader.addPlugin(pluginDownload); Plugin pluginClass = loadPublicPlugin(pluginDownload); Log.debug("Trying to initialize " + pluginClass); pluginClass.initialize(); } /** * Unzips a plugin from a JAR file into a directory. If the JAR file * isn't a plugin, this method will do nothing. * * @param file the JAR file * @param dir the directory to extract the plugin to. */ private void unzipPlugin(File file, File dir) { try { ZipFile zipFile = new JarFile(file); // Ensure that this JAR is a plugin. if (zipFile.getEntry("plugin.xml") == null) { return; } dir.mkdir(); for (Enumeration e = zipFile.entries(); e.hasMoreElements();) { JarEntry entry = (JarEntry)e.nextElement(); File entryFile = new File(dir, entry.getName()); // Ignore any manifest.mf entries. if (entry.getName().toLowerCase().endsWith("manifest.mf")) { continue; } if (!entry.isDirectory()) { entryFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(entryFile); InputStream zin = zipFile.getInputStream(entry); byte[] b = new byte[512]; int len = 0; while ((len = zin.read(b)) != -1) { out.write(b, 0, len); } out.flush(); out.close(); zin.close(); } } zipFile.close(); zipFile = null; } catch (Exception e) { Log.error("Error unzipping plugin", e); } } /** * Returns a collection of all public plugins. * * @return the collection of public plugins. */ public List<PublicPlugin> getPublicPlugins() { return publicPlugins; } private void uninstall(File pluginDir) { File[] files = pluginDir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isFile()) { f.delete(); } } File libDir = new File(pluginDir, "lib"); File[] libs = libDir.listFiles(); final int no = libs != null ? libs.length : 0; for (int i = 0; i < no; i++) { File f = libs[i]; f.delete(); } libDir.delete(); pluginDir.delete(); } /** * Removes and uninstall a plugin from Spark. * * @param plugin the plugin to uninstall. */ public void removePublicPlugin(PublicPlugin plugin) { for (PublicPlugin publicPlugin : getPublicPlugins()) { if (plugin.getName().equals(publicPlugin.getName())) { publicPlugins.remove(plugin); } } } /** * Returns true if the specified plugin is installed. * * @param plugin the <code>PublicPlugin</code> plugin to check. * @return true if installed. */ public boolean isInstalled(PublicPlugin plugin) { for (PublicPlugin publicPlugin : getPublicPlugins()) { if (plugin.getName().equals(publicPlugin.getName())) { return true; } } return false; } }
package com.forgeessentials.util; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import com.forgeessentials.commons.selections.WorldPoint; public abstract class WorldUtil { /** * Checks if the blocks from [x,y,z] to [x,y+h-1,z] are either air or replacable * * @param world * @param x * @param y * @param z * @param h * @return y value */ public static boolean isFree(World world, int x, int y, int z, int h) { for (int i = 0; i < h; i++) { Block block = world.getBlock(x, y + i, z); if (block.getMaterial().isSolid() || block.getMaterial().isLiquid()) return false; } return true; } /** * Returns a free spot of height h in the world at the coordinates [x,z] near y. If the blocks at [x,y,z] are free, * it returns the next location that is on the ground. If the blocks at [x,y,z] are not free, it goes up until it * finds a free spot. * * @param world * @param x * @param y * @param z * @param h * @return y value */ public static int placeInWorld(World world, int x, int y, int z, int h) { if (isFree(world, x, y, z, h)) { while (isFree(world, x, y - 1, z, h) && y > 0) y } else { y++; while (y + h < world.getHeight() && !isFree(world, x, y, z, h)) y++; } if (y == 0) y = world.getHeight() - h; return y; } /** * Returns a free spot of height 2 in the world at the coordinates [x,z] near y. If the blocks at [x,y,z] are free, * it returns the next location that is on the ground. If the blocks at [x,y,z] are not free, it goes up until it * finds a free spot. * * @param world * @param x * @param y * @param z * @return y value */ public static int placeInWorld(World world, int x, int y, int z) { return placeInWorld(world, x, y, z, 2); } public static WorldPoint placeInWorld(WorldPoint p) { return p.setY(placeInWorld(p.getWorld(), p.getX(), p.getY(), p.getZ(), 2)); } public static void placeInWorld(EntityPlayer player) { WorldPoint p = placeInWorld(new WorldPoint(player)); player.setPositionAndUpdate(p.getX() + 0.5, p.getY(), p.getZ() + 0.5); } }
package hex.tree; import hex.*; import water.*; import water.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class SharedTreeModel<M extends SharedTreeModel<M,P,O>, P extends SharedTreeModel.SharedTreeParameters, O extends SharedTreeModel.SharedTreeOutput> extends Model<M,P,O> { public abstract static class SharedTreeParameters extends Model.Parameters { /** Maximal number of supported levels in response. */ static final int MAX_SUPPORTED_LEVELS = 1000; public int _ntrees=50; // Number of trees in the final model. Grid Search, comma sep values:50,100,150,200 public int _max_depth = 5; // Maximum tree depth. Grid Search, comma sep values:5,7 public double _min_rows = 10; // Fewest allowed observations in a leaf (in R called 'nodesize'). Grid Search, comma sep values public int _nbins = 20; // Numerical (real/int) cols: Build a histogram of this many bins, then split at the best point public int _nbins_cats = 1024; // Categorical (enum) cols: Build a histogram of this many bins, then split at the best point public double _r2_stopping = 0.999999; // Stop when the r^2 metric equals or exceeds this value public long _seed = RandomUtils.getRNG(System.nanoTime()).nextLong(); // TRUE: Continue extending an existing checkpointed model // FALSE: Overwrite any prior model public boolean _checkpoint; public int _nbins_top_level = 1<<10; //hardcoded minimum top-level number of bins for real-valued columns (not currently user-facing) public boolean _build_tree_one_node = false; /** Distribution functions. Note: AUTO will select gaussian for * continuous, and multinomial for categorical response * * <p>TODO: Replace with drop-down that displays different distributions * depending on cont/cat response */ public Distributions.Family _distribution = Distributions.Family.AUTO; public float _tweedie_power=1.5f; } final public VarImp varImp() { return _output._varimp; } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { switch(_output.getModelCategory()) { case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain); case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain); case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); default: throw H2O.unimpl(); } } public abstract static class SharedTreeOutput extends Model.Output { /** InitF value (for zero trees) * f0 = mean(yi) for gaussian * f0 = log(yi/1-yi) for bernoulli * * For GBM bernoulli, the initial prediction for 0 trees is * p = 1/(1+exp(-f0)) * * From this, the mse for 0 trees (null model) can be computed as follows: * mean((yi-p)^2) * */ public double _init_f; /** Number of trees actually in the model (as opposed to requested) */ public int _ntrees; /** More indepth tree stats */ final public TreeStats _treeStats; /** Trees get big, so store each one seperately in the DKV. */ public Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeys; public ScoreKeeper _scored_train[/*ntrees+1*/]; public ScoreKeeper _scored_valid[/*ntrees+1*/]; /** Training time */ public long _training_time_ms[/*ntrees+1*/] = new long[]{System.currentTimeMillis()}; /** * Variable importances computed during training */ public TwoDimTable _variable_importances; public VarImp _varimp; public SharedTreeOutput( SharedTree b, double mse_train, double mse_valid ) { super(b); _ntrees = 0; // No trees yet _treeKeys = new Key[_ntrees][]; // No tree keys yet _treeStats = new TreeStats(); _scored_train = new ScoreKeeper[]{new ScoreKeeper(mse_train)}; _scored_valid = new ScoreKeeper[]{new ScoreKeeper(mse_valid)}; _modelClassDist = _priorClassDist; } // Append next set of K trees public void addKTrees( DTree[] trees) { // DEBUG: Print the generated K trees //SharedTree.printGenerateTrees(trees); assert nclasses()==trees.length; // Compress trees and record tree-keys _treeKeys = Arrays.copyOf(_treeKeys ,_ntrees+1); Key[] keys = _treeKeys[_ntrees] = new Key[trees.length]; Futures fs = new Futures(); for( int i=0; i<nclasses(); i++ ) if( trees[i] != null ) { CompressedTree ct = trees[i].compress(_ntrees,i); DKV.put(keys[i]=ct._key,ct,fs); _treeStats.updateBy(trees[i]); // Update tree shape stats } _ntrees++; // 1-based for errors; _scored_train[0] is for zero trees, not 1 tree _scored_train = ArrayUtils.copyAndFillOf(_scored_train, _ntrees+1, new ScoreKeeper()); _scored_valid = _scored_valid != null ? ArrayUtils.copyAndFillOf(_scored_valid, _ntrees+1, new ScoreKeeper()) : null; _training_time_ms = ArrayUtils.copyAndFillOf(_training_time_ms, _ntrees+1, System.currentTimeMillis()); fs.blockForPending(); } public CompressedTree ctree( int tnum, int knum ) { return _treeKeys[tnum][knum].get(); } public String toStringTree ( int tnum, int knum ) { return ctree(tnum,knum).toString(this); } } public SharedTreeModel(Key selfKey, P parms, O output) { super(selfKey,parms,output); } @Override protected double[] score0(double data[/*ncols*/], double preds[/*nclasses+1*/]) { return score0(data, preds, 1.0, 0.0); } @Override protected double[] score0(double[] data, double[] preds, double weight, double offset) { // Prefetch trees into the local cache if it is necessary // Invoke scoring Arrays.fill(preds,0); for( int tidx=0; tidx<_output._treeKeys.length; tidx++ ) score0(data, preds, tidx); return preds; } // Score per line per tree private void score0(double data[], double preds[], int treeIdx) { Key[] keys = _output._treeKeys[treeIdx]; for( int c=0; c<keys.length; c++ ) { if (keys[c] != null) { double pred = DKV.get(keys[c]).<CompressedTree>get().score(data); assert (!Double.isInfinite(pred)); preds[keys.length == 1 ? 0 : c + 1] += pred; } } } @Override protected Futures remove_impl( Futures fs ) { for( Key ks[] : _output._treeKeys) for( Key k : ks ) if( k != null ) k.remove(fs); return super.remove_impl(fs); } // Override in subclasses to provide some top-level model-specific goodness @Override protected boolean toJavaCheckTooBig() { // If the number of leaves in a forest is more than N, don't try to render it in the browser as POJO code. return _output==null || _output._treeStats._num_trees * _output._treeStats._mean_leaves > 1000000; } protected boolean binomialOpt() { return true; } @Override protected SB toJavaInit(SB sb, SB fileContext) { sb.nl(); sb.ip("public boolean isSupervised() { return true; }").nl(); sb.ip("public int nfeatures() { return "+_output.nfeatures()+"; }").nl(); sb.ip("public int nclasses() { return "+_output.nclasses()+"; }").nl(); return sb; } @Override protected void toJavaPredictBody(SB body, SB classCtx, SB file) { final int nclass = _output.nclasses(); body.ip("java.util.Arrays.fill(preds,0);").nl(); body.ip("double[] fdata = hex.genmodel.GenModel.SharedTree_clean(data);").nl(); String mname = JCodeGen.toJavaId(_key.toString()); // One forest-per-GBM-tree, with a real-tree-per-class for( int t=0; t < _output._treeKeys.length; t++ ) { toJavaForestName(body.i(),mname,t).p(".score0(fdata,preds);").nl(); file.nl(); toJavaForestName(file.ip("class "),mname,t).p(" {").nl().ii(1); file.ip("public static void score0(double[] fdata, double[] preds) {").nl().ii(1); for( int c=0; c<nclass; c++ ) if( !binomialOpt() || !(c==1 && nclass==2) ) // Binomial optimization toJavaTreeName(file.ip("preds[").p(nclass==1?0:c+1).p("] += "),mname,t,c).p(".score0(fdata);").nl(); file.di(1).ip("}").nl(); // end of function file.di(1).ip("}").nl(); // end of forest class // Generate the pre-tree classes afterwards for( int c=0; c<nclass; c++ ) { if( !binomialOpt() || !(c==1 && nclass==2) ) { // Binomial optimization toJavaTreeName(file.ip("class "),mname,t,c).p(" {").nl().ii(1); CompressedTree ct = _output.ctree(t,c); new TreeJCodeGen(this,ct, file).generate(); file.di(1).ip("}").nl(); // close the class } } } toJavaUnifyPreds(body,file); } abstract protected void toJavaUnifyPreds( SB body, SB file ); protected SB toJavaTreeName( final SB sb, String mname, int t, int c ) { return sb.p(mname).p("_Tree_").p(t).p("_class_").p(c); } protected SB toJavaForestName( final SB sb, String mname, int t ) { return sb.p(mname).p("_Forest_").p(t); } @Override public List<Key> getPublishedKeys() { assert _output._ntrees == _output._treeKeys.length : "Tree model is inconsistent: number of trees do not match number of tree keys!"; List<Key> superP = super.getPublishedKeys(); List<Key> p = new ArrayList<Key>(_output._ntrees * _output.nclasses()); for (int i = 0; i < _output._treeKeys.length; i++) { for (int j = 0; j < _output._treeKeys[i].length; j++) { p.add(_output._treeKeys[i][j]); } } p.addAll(superP); return p; } }
package org.jivesoftware.wildfire; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.jivesoftware.database.DbConnectionManager; import org.jivesoftware.util.*; import org.jivesoftware.wildfire.audit.AuditManager; import org.jivesoftware.wildfire.audit.spi.AuditManagerImpl; import org.jivesoftware.wildfire.commands.AdHocCommandHandler; import org.jivesoftware.wildfire.component.InternalComponentManager; import org.jivesoftware.wildfire.container.AdminConsolePlugin; import org.jivesoftware.wildfire.container.Module; import org.jivesoftware.wildfire.container.PluginManager; import org.jivesoftware.wildfire.disco.IQDiscoInfoHandler; import org.jivesoftware.wildfire.disco.IQDiscoItemsHandler; import org.jivesoftware.wildfire.disco.ServerFeaturesProvider; import org.jivesoftware.wildfire.disco.ServerItemsProvider; import org.jivesoftware.wildfire.filetransfer.DefaultFileTransferManager; import org.jivesoftware.wildfire.filetransfer.FileTransferManager; import org.jivesoftware.wildfire.filetransfer.proxy.FileTransferProxy; import org.jivesoftware.wildfire.handler.*; import org.jivesoftware.wildfire.mediaproxy.MediaProxyService; import org.jivesoftware.wildfire.muc.MultiUserChatServer; import org.jivesoftware.wildfire.muc.spi.MultiUserChatServerImpl; import org.jivesoftware.wildfire.net.MulticastDNSService; import org.jivesoftware.wildfire.net.SSLConfig; import org.jivesoftware.wildfire.net.ServerTrafficCounter; import org.jivesoftware.wildfire.pubsub.PubSubModule; import org.jivesoftware.wildfire.roster.RosterManager; import org.jivesoftware.wildfire.spi.*; import org.jivesoftware.wildfire.stun.STUNService; import org.jivesoftware.wildfire.transport.TransportHandler; import org.jivesoftware.wildfire.update.UpdateManager; import org.jivesoftware.wildfire.user.UserManager; import org.jivesoftware.wildfire.vcard.VCardManager; import org.xmpp.packet.JID; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.security.KeyStore; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * The main XMPP server that will load, initialize and start all the server's * modules. The server is unique in the JVM and could be obtained by using the * {@link #getInstance()} method.<p> * <p/> * The loaded modules will be initialized and may access through the server other * modules. This means that the only way for a module to locate another module is * through the server. The server maintains a list of loaded modules.<p> * <p/> * After starting up all the modules the server will load any available plugin. * For more information see: {@link org.jivesoftware.wildfire.container.PluginManager}.<p> * <p/> * A configuration file keeps the server configuration. This information is required for the * server to work correctly. The server assumes that the configuration file is named * <b>wildfire.xml</b> and is located in the <b>conf</b> folder. The folder that keeps * the configuration file must be located under the home folder. The server will try different * methods to locate the home folder. * <p/> * <ol> * <li><b>system property</b> - The server will use the value defined in the <i>wildfireHome</i> * system property.</li> * <li><b>working folder</b> - The server will check if there is a <i>conf</i> folder in the * working directory. This is the case when running in standalone mode.</li> * <li><b>wildfire_init.xml file</b> - Attempt to load the value from wildfire_init.xml which * must be in the classpath</li> * </ol> * * @author Gaston Dombiak */ public class XMPPServer { private static XMPPServer instance; private String name; private Version version; private Date startDate; private Date stopDate; private boolean initialized = false; /** * All modules loaded by this server */ private Map<Class, Module> modules = new LinkedHashMap<Class, Module>(); /** * Listeners that will be notified when the server has started or is about to be stopped. */ private List<XMPPServerListener> listeners = new CopyOnWriteArrayList<XMPPServerListener>(); /** * Location of the home directory. All configuration files should be * located here. */ private File wildfireHome; private ClassLoader loader; private PluginManager pluginManager; private InternalComponentManager componentManager; /** * True if in setup mode */ private boolean setupMode = true; private static final String STARTER_CLASSNAME = "org.jivesoftware.wildfire.starter.ServerStarter"; private static final String WRAPPER_CLASSNAME = "org.tanukisoftware.wrapper.WrapperManager"; /** * Returns a singleton instance of XMPPServer. * * @return an instance. */ public static XMPPServer getInstance() { return instance; } /** * Creates a server and starts it. */ public XMPPServer() { // We may only have one instance of the server running on the JVM if (instance != null) { throw new IllegalStateException("A server is already running"); } instance = this; start(); } /** * Returns a snapshot of the server's status. * * @return the server information current at the time of the method call. */ public XMPPServerInfo getServerInfo() { if (!initialized) { throw new IllegalStateException("Not initialized yet"); } return new XMPPServerInfoImpl(name, version, startDate, stopDate, getConnectionManager()); } /** * Returns true if the given address is local to the server (managed by this * server domain). Return false even if the jid's domain matches a local component's * service JID. * * @param jid the JID to check. * @return true if the address is a local address to this server. */ public boolean isLocal(JID jid) { boolean local = false; if (jid != null && name != null && name.equals(jid.getDomain())) { local = true; } return local; } /** * Returns true if the given address does not match the local server hostname and does not * match a component service JID. * * @param jid the JID to check. * @return true if the given address does not match the local server hostname and does not * match a component service JID. */ public boolean isRemote(JID jid) { if (jid != null) { if (!name.equals(jid.getDomain()) && componentManager.getComponent(jid) == null) { return true; } } return false; } /** * Returns true if the given address matches a component service JID. * * @param jid the JID to check. * @return true if the given address matches a component service JID. */ public boolean matchesComponent(JID jid) { return jid != null && !name.equals(jid.getDomain()) && componentManager.getComponent(jid) != null; } /** * Creates an XMPPAddress local to this server. * * @param username the user name portion of the id or null to indicate none is needed. * @param resource the resource portion of the id or null to indicate none is needed. * @return an XMPPAddress for the server. */ public JID createJID(String username, String resource) { return new JID(username, name, resource); } /** * Returns a collection with the JIDs of the server's admins. The collection may include * JIDs of local users and users of remote servers. * * @return a collection with the JIDs of the server's admins. */ public Collection<JID> getAdmins() { Collection<JID> admins = new ArrayList<JID>(); // Add the JIDs of the local users that are admins String usernames = JiveGlobals.getXMLProperty("admin.authorizedUsernames"); if (usernames == null) { // Fall back to old method for defining admins (i.e. using adminConsole prefix usernames = JiveGlobals.getXMLProperty("adminConsole.authorizedUsernames"); } usernames = (usernames == null || usernames.trim().length() == 0) ? "admin" : usernames; StringTokenizer tokenizer = new StringTokenizer(usernames, ","); while (tokenizer.hasMoreTokens()) { String username = tokenizer.nextToken(); try { admins.add(createJID(username.toLowerCase().trim(), null)); } catch (IllegalArgumentException e) { // Ignore usernames that when appended @server.com result in an invalid JID Log.warn("Invalid username found in authorizedUsernames at wildfire.xml: " + username, e); } } // Add bare JIDs of users that are admins (may include remote users) String jids = JiveGlobals.getXMLProperty("admin.authorizedJIDs"); jids = (jids == null || jids.trim().length() == 0) ? "" : jids; tokenizer = new StringTokenizer(jids, ","); while (tokenizer.hasMoreTokens()) { String jid = tokenizer.nextToken().toLowerCase().trim(); try { admins.add(new JID(jid)); } catch (IllegalArgumentException e) { Log.warn("Invalid JID found in authorizedJIDs at wildfire.xml: " + jid, e); } } return admins; } /** * Adds a new server listener that will be notified when the server has been started * or is about to be stopped. * * @param listener the new server listener to add. */ public void addServerListener(XMPPServerListener listener) { listeners.add(listener); } /** * Removes a server listener that was being notified when the server was being started * or was about to be stopped. * * @param listener the server listener to remove. */ public void removeServerListener(XMPPServerListener listener) { listeners.remove(listener); } private void initialize() throws FileNotFoundException { locateWildfire(); name = JiveGlobals.getProperty("xmpp.domain", "127.0.0.1").toLowerCase(); version = new Version(3, 2, 0, Version.ReleaseStatus.Release_Candidate, 2); if ("true".equals(JiveGlobals.getXMLProperty("setup"))) { setupMode = false; } if (isStandAlone()) { Runtime.getRuntime().addShutdownHook(new ShutdownHookThread()); } loader = Thread.currentThread().getContextClassLoader(); initialized = true; } /** * Finish the setup process. Because this method is meant to be called from inside * the Admin console plugin, it spawns its own thread to do the work so that the * class loader is correct. */ public void finishSetup() { if (!setupMode) { return; } // Make sure that setup finished correctly. if ("true".equals(JiveGlobals.getXMLProperty("setup"))) { // Set the new server domain assigned during the setup process name = JiveGlobals.getProperty("xmpp.domain").toLowerCase(); // Update certificates (if required) try { // Check if keystore already has certificates for current domain KeyStore ksKeys = SSLConfig.getKeyStore(); boolean dsaFound = CertificateManager.isDSACertificate(ksKeys, name); boolean rsaFound = CertificateManager.isRSACertificate(ksKeys, name); // No certificates were found so create new self-signed certificates if (!dsaFound) { CertificateManager.createDSACert(ksKeys, SSLConfig.getKeyPassword(), name + "_dsa", "cn=" + name, "cn=" + name, "*." + name); } if (!rsaFound) { CertificateManager.createRSACert(ksKeys, SSLConfig.getKeyPassword(), name + "_rsa", "cn=" + name, "cn=" + name, "*." + name); } // Save new certificates into the key store if (!dsaFound || !rsaFound) { SSLConfig.saveStores(); } } catch (Exception e) { Log.error("Error generating self-signed certificates", e); } Thread finishSetup = new Thread() { public void run() { try { if (isStandAlone()) { // Always restart the HTTP server manager. This covers the case // of changing the ports, as well as generating self-signed certificates. // Wait a short period before shutting down the admin console. // Otherwise, the page that requested the setup finish won't // render properly! Thread.sleep(1000); ((AdminConsolePlugin) pluginManager.getPlugin("admin")).shutdown(); ((AdminConsolePlugin) pluginManager.getPlugin("admin")).startup(); } verifyDataSource(); // First load all the modules so that modules may access other modules while // being initialized loadModules(); // Initize all the modules initModules(); // Start all the modules startModules(); // Keep a reference to the internal component manager componentManager = getComponentManager(); } catch (Exception e) { e.printStackTrace(); Log.error(e); shutdownServer(); } } }; // Use the correct class loader. finishSetup.setContextClassLoader(loader); finishSetup.start(); // We can now safely indicate that setup has finished setupMode = false; } } public void start() { try { initialize(); // Create PluginManager now (but don't start it) so that modules may use it File pluginDir = new File(wildfireHome, "plugins"); pluginManager = new PluginManager(pluginDir); // If the server has already been setup then we can start all the server's modules if (!setupMode) { verifyDataSource(); // First load all the modules so that modules may access other modules while // being initialized loadModules(); // Initize all the modules initModules(); // Start all the modules startModules(); // Keep a reference to the internal component manager componentManager = getComponentManager(); } // Initialize statistics ServerTrafficCounter.initStatistics(); // Load plugins (when in setup mode only the admin console will be loaded) pluginManager.start(); // Log that the server has been started List<String> params = new ArrayList<String>(); params.add(version.getVersionString()); params.add(JiveGlobals.formatDateTime(new Date())); String startupBanner = LocaleUtils.getLocalizedString("startup.name", params); Log.info(startupBanner); System.out.println(startupBanner); startDate = new Date(); stopDate = null; // Notify server listeners that the server has been started for (XMPPServerListener listener : listeners) { listener.serverStarted(); } } catch (Exception e) { e.printStackTrace(); Log.error(e); System.out.println(LocaleUtils.getLocalizedString("startup.error")); shutdownServer(); } } private void loadModules() { // Load boot modules loadModule(RoutingTableImpl.class.getName()); loadModule(AuditManagerImpl.class.getName()); loadModule(RosterManager.class.getName()); loadModule(PrivateStorage.class.getName()); // Load core modules loadModule(PresenceManagerImpl.class.getName()); loadModule(SessionManager.class.getName()); loadModule(PacketRouterImpl.class.getName()); loadModule(IQRouter.class.getName()); loadModule(MessageRouter.class.getName()); loadModule(PresenceRouter.class.getName()); loadModule(MulticastRouter.class.getName()); loadModule(PacketTransporterImpl.class.getName()); loadModule(PacketDelivererImpl.class.getName()); loadModule(TransportHandler.class.getName()); loadModule(OfflineMessageStrategy.class.getName()); loadModule(OfflineMessageStore.class.getName()); loadModule(VCardManager.class.getName()); // Load standard modules loadModule(IQBindHandler.class.getName()); loadModule(IQSessionEstablishmentHandler.class.getName()); loadModule(IQAuthHandler.class.getName()); loadModule(IQPrivateHandler.class.getName()); loadModule(IQRegisterHandler.class.getName()); loadModule(IQRosterHandler.class.getName()); loadModule(IQTimeHandler.class.getName()); loadModule(IQvCardHandler.class.getName()); loadModule(IQVersionHandler.class.getName()); loadModule(IQLastActivityHandler.class.getName()); loadModule(PresenceSubscribeHandler.class.getName()); loadModule(PresenceUpdateHandler.class.getName()); loadModule(IQDiscoInfoHandler.class.getName()); loadModule(IQDiscoItemsHandler.class.getName()); loadModule(IQOfflineMessagesHandler.class.getName()); loadModule(MultiUserChatServerImpl.class.getName()); loadModule(MulticastDNSService.class.getName()); loadModule(IQSharedGroupHandler.class.getName()); loadModule(AdHocCommandHandler.class.getName()); loadModule(IQPrivacyHandler.class.getName()); loadModule(DefaultFileTransferManager.class.getName()); loadModule(FileTransferProxy.class.getName()); loadModule(MediaProxyService.class.getName()); loadModule(STUNService.class.getName()); loadModule(PubSubModule.class.getName()); loadModule(UpdateManager.class.getName()); loadModule(InternalComponentManager.class.getName()); // Load this module always last since we don't want to start listening for clients // before the rest of the modules have been started loadModule(ConnectionManagerImpl.class.getName()); } /** * Loads a module. * * @param module the name of the class that implements the Module interface. */ private void loadModule(String module) { try { Class modClass = loader.loadClass(module); Module mod = (Module) modClass.newInstance(); this.modules.put(modClass, mod); } catch (Exception e) { e.printStackTrace(); Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } private void initModules() { for (Module module : modules.values()) { boolean isInitialized = false; try { module.initialize(this); isInitialized = true; } catch (Exception e) { e.printStackTrace(); // Remove the failed initialized module this.modules.remove(module.getClass()); if (isInitialized) { module.stop(); module.destroy(); } Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } /** * <p>Following the loading and initialization of all the modules * this method is called to iterate through the known modules and * start them.</p> */ private void startModules() { for (Module module : modules.values()) { boolean started = false; try { module.start(); } catch (Exception e) { if (started && module != null) { module.stop(); module.destroy(); } Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } /** * Restarts the server and all it's modules only if the server is restartable. Otherwise do * nothing. */ public void restart() { if (isStandAlone() && isRestartable()) { try { Class wrapperClass = Class.forName(WRAPPER_CLASSNAME); Method restartMethod = wrapperClass.getMethod("restart", (Class []) null); restartMethod.invoke(null, (Object []) null); } catch (Exception e) { Log.error("Could not restart container", e); } } } /** * Restarts the HTTP server only when running in stand alone mode. The restart * process will be done in another thread that will wait 1 second before doing * the actual restart. The delay will give time to the page that requested the * restart to fully render its content. */ public void restartHTTPServer() { Thread restartThread = new Thread() { public void run() { if (isStandAlone()) { // Restart the HTTP server manager. This covers the case // of changing the ports, as well as generating self-signed certificates. // Wait a short period before shutting down the admin console. // Otherwise, this page won't render properly! try { Thread.sleep(1000); ((AdminConsolePlugin) pluginManager.getPlugin("admin")).shutdown(); ((AdminConsolePlugin) pluginManager.getPlugin("admin")).startup(); } catch (Exception e) { e.printStackTrace(); } } } }; restartThread.setContextClassLoader(loader); restartThread.start(); } /** * Stops the server only if running in standalone mode. Do nothing if the server is running * inside of another server. */ public void stop() { // Only do a system exit if we're running standalone if (isStandAlone()) { // if we're in a wrapper, we have to tell the wrapper to shut us down if (isRestartable()) { try { Class wrapperClass = Class.forName(WRAPPER_CLASSNAME); Method stopMethod = wrapperClass.getMethod("stop", Integer.TYPE); stopMethod.invoke(null, 0); } catch (Exception e) { Log.error("Could not stop container", e); } } else { shutdownServer(); stopDate = new Date(); Thread shutdownThread = new ShutdownThread(); shutdownThread.setDaemon(true); shutdownThread.start(); } } else { // Close listening socket no matter what the condition is in order to be able // to be restartable inside a container. shutdownServer(); stopDate = new Date(); } } public boolean isSetupMode() { return setupMode; } public boolean isRestartable() { boolean restartable; try { restartable = Class.forName(WRAPPER_CLASSNAME) != null; } catch (ClassNotFoundException e) { restartable = false; } return restartable; } /** * Returns if the server is running in standalone mode. We consider that it's running in * standalone if the "org.jivesoftware.wildfire.starter.ServerStarter" class is present in the * system. * * @return true if the server is running in standalone mode. */ public boolean isStandAlone() { boolean standalone; try { standalone = Class.forName(STARTER_CLASSNAME) != null; } catch (ClassNotFoundException e) { standalone = false; } return standalone; } /** * Verify that the database is accessible. */ private void verifyDataSource() { java.sql.Connection conn = null; try { conn = DbConnectionManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT count(*) FROM jiveID"); ResultSet rs = stmt.executeQuery(); rs.next(); rs.close(); stmt.close(); } catch (Exception e) { System.err.println("Database setup or configuration error: " + "Please verify your database settings and check the " + "logs/error.log file for detailed error messages."); Log.error("Database could not be accessed", e); throw new IllegalArgumentException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { Log.error(e); } } } } /** * Verifies that the given home guess is a real Wildfire home directory. * We do the verification by checking for the Wildfire config file in * the config dir of jiveHome. * * @param homeGuess a guess at the path to the home directory. * @param jiveConfigName the name of the config file to check. * @return a file pointing to the home directory or null if the * home directory guess was wrong. * @throws java.io.FileNotFoundException if there was a problem with the home * directory provided */ private File verifyHome(String homeGuess, String jiveConfigName) throws FileNotFoundException { File wildfireHome = new File(homeGuess); File configFile = new File(wildfireHome, jiveConfigName); if (!configFile.exists()) { throw new FileNotFoundException(); } else { try { return new File(wildfireHome.getCanonicalPath()); } catch (Exception ex) { throw new FileNotFoundException(); } } } /** * <p>Retrieve the jive home for the container.</p> * * @throws FileNotFoundException If jiveHome could not be located */ private void locateWildfire() throws FileNotFoundException { String jiveConfigName = "conf" + File.separator + "wildfire.xml"; // First, try to load it wildfireHome as a system property. if (wildfireHome == null) { String homeProperty = System.getProperty("wildfireHome"); try { if (homeProperty != null) { wildfireHome = verifyHome(homeProperty, jiveConfigName); } } catch (FileNotFoundException fe) { // Ignore. } } // If we still don't have home, let's assume this is standalone // and just look for home in a standard sub-dir location and verify // by looking for the config file if (wildfireHome == null) { try { wildfireHome = verifyHome("..", jiveConfigName).getCanonicalFile(); } catch (FileNotFoundException fe) { // Ignore. } catch (IOException ie) { // Ignore. } } // If home is still null, no outside process has set it and // we have to attempt to load the value from wildfire_init.xml, // which must be in the classpath. if (wildfireHome == null) { InputStream in = null; try { in = getClass().getResourceAsStream("/wildfire_init.xml"); if (in != null) { SAXReader reader = new SAXReader(); Document doc = reader.read(in); String path = doc.getRootElement().getText(); try { if (path != null) { wildfireHome = verifyHome(path, jiveConfigName); } } catch (FileNotFoundException fe) { fe.printStackTrace(); } } } catch (Exception e) { System.err.println("Error loading wildfire_init.xml to find home."); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { System.err.println("Could not close open connection"); e.printStackTrace(); } } } if (wildfireHome == null) { System.err.println("Could not locate home"); throw new FileNotFoundException(); } else { // Set the home directory for the config file JiveGlobals.setHomeDirectory(wildfireHome.toString()); // Set the name of the config file JiveGlobals.setConfigName(jiveConfigName); } } /** * <p>A thread to ensure the server shuts down no matter what.</p> * <p>Spawned when stop() is called in standalone mode, we wait a few * seconds then call system exit().</p> * * @author Iain Shigeoka */ private class ShutdownHookThread extends Thread { /** * <p>Logs the server shutdown.</p> */ public void run() { shutdownServer(); Log.info("Server halted"); System.err.println("Server halted"); } } /** * <p>A thread to ensure the server shuts down no matter what.</p> * <p>Spawned when stop() is called in standalone mode, we wait a few * seconds then call system exit().</p> * * @author Iain Shigeoka */ private class ShutdownThread extends Thread { /** * <p>Shuts down the JVM after a 5 second delay.</p> */ public void run() { try { Thread.sleep(5000); // No matter what, we make sure it's dead System.exit(0); } catch (InterruptedException e) { // Ignore. } } } /** * Makes a best effort attempt to shutdown the server */ private void shutdownServer() { // Notify server listeners that the server is about to be stopped for (XMPPServerListener listener : listeners) { listener.serverStopping(); } // Shutdown the task engine. TaskEngine.getInstance().shutdown(); // If we don't have modules then the server has already been shutdown if (modules.isEmpty()) { return; } // Get all modules and stop and destroy them for (Module module : modules.values()) { module.stop(); module.destroy(); } modules.clear(); // Stop all plugins if (pluginManager != null) { pluginManager.shutdown(); } // Stop the Db connection manager. DbConnectionManager.destroyConnectionProvider(); // hack to allow safe stopping Log.info("Wildfire stopped"); } /** * Returns the <code>ConnectionManager</code> registered with this server. The * <code>ConnectionManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>ConnectionManager</code> registered with this server. */ public ConnectionManager getConnectionManager() { return (ConnectionManager) modules.get(ConnectionManagerImpl.class); } /** * Returns the <code>RoutingTable</code> registered with this server. The * <code>RoutingTable</code> was registered with the server as a module while starting up * the server. * * @return the <code>RoutingTable</code> registered with this server. */ public RoutingTable getRoutingTable() { return (RoutingTable) modules.get(RoutingTableImpl.class); } /** * Returns the <code>PacketDeliverer</code> registered with this server. The * <code>PacketDeliverer</code> was registered with the server as a module while starting up * the server. * * @return the <code>PacketDeliverer</code> registered with this server. */ public PacketDeliverer getPacketDeliverer() { return (PacketDeliverer) modules.get(PacketDelivererImpl.class); } /** * Returns the <code>RosterManager</code> registered with this server. The * <code>RosterManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>RosterManager</code> registered with this server. */ public RosterManager getRosterManager() { return (RosterManager) modules.get(RosterManager.class); } /** * Returns the <code>PresenceManager</code> registered with this server. The * <code>PresenceManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>PresenceManager</code> registered with this server. */ public PresenceManager getPresenceManager() { return (PresenceManager) modules.get(PresenceManagerImpl.class); } /** * Returns the <code>OfflineMessageStore</code> registered with this server. The * <code>OfflineMessageStore</code> was registered with the server as a module while starting up * the server. * * @return the <code>OfflineMessageStore</code> registered with this server. */ public OfflineMessageStore getOfflineMessageStore() { return (OfflineMessageStore) modules.get(OfflineMessageStore.class); } /** * Returns the <code>OfflineMessageStrategy</code> registered with this server. The * <code>OfflineMessageStrategy</code> was registered with the server as a module while starting * up the server. * * @return the <code>OfflineMessageStrategy</code> registered with this server. */ public OfflineMessageStrategy getOfflineMessageStrategy() { return (OfflineMessageStrategy) modules.get(OfflineMessageStrategy.class); } /** * Returns the <code>PacketRouter</code> registered with this server. The * <code>PacketRouter</code> was registered with the server as a module while starting up * the server. * * @return the <code>PacketRouter</code> registered with this server. */ public PacketRouter getPacketRouter() { return (PacketRouter) modules.get(PacketRouterImpl.class); } /** * Returns the <code>IQRegisterHandler</code> registered with this server. The * <code>IQRegisterHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>IQRegisterHandler</code> registered with this server. */ public IQRegisterHandler getIQRegisterHandler() { return (IQRegisterHandler) modules.get(IQRegisterHandler.class); } /** * Returns the <code>IQAuthHandler</code> registered with this server. The * <code>IQAuthHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>IQAuthHandler</code> registered with this server. */ public IQAuthHandler getIQAuthHandler() { return (IQAuthHandler) modules.get(IQAuthHandler.class); } /** * Returns the <code>PluginManager</code> instance registered with this server. * * @return the PluginManager instance. */ public PluginManager getPluginManager() { return pluginManager; } /** * Returns the <code>PubSubModule</code> registered with this server. The * <code>PubSubModule</code> was registered with the server as a module while starting up * the server. * * @return the <code>PubSubModule</code> registered with this server. */ public PubSubModule getPubSubModule() { return (PubSubModule) modules.get(PubSubModule.class); } /** * Returns a list with all the modules registered with the server that inherit from IQHandler. * * @return a list with all the modules registered with the server that inherit from IQHandler. */ public List<IQHandler> getIQHandlers() { List<IQHandler> answer = new ArrayList<IQHandler>(); for (Module module : modules.values()) { if (module instanceof IQHandler) { answer.add((IQHandler) module); } } return answer; } /** * Returns the <code>SessionManager</code> registered with this server. The * <code>SessionManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>SessionManager</code> registered with this server. */ public SessionManager getSessionManager() { return (SessionManager) modules.get(SessionManager.class); } /** * Returns the <code>TransportHandler</code> registered with this server. The * <code>TransportHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>TransportHandler</code> registered with this server. */ public TransportHandler getTransportHandler() { return (TransportHandler) modules.get(TransportHandler.class); } /** * Returns the <code>PresenceUpdateHandler</code> registered with this server. The * <code>PresenceUpdateHandler</code> was registered with the server as a module while starting * up the server. * * @return the <code>PresenceUpdateHandler</code> registered with this server. */ public PresenceUpdateHandler getPresenceUpdateHandler() { return (PresenceUpdateHandler) modules.get(PresenceUpdateHandler.class); } /** * Returns the <code>PresenceSubscribeHandler</code> registered with this server. The * <code>PresenceSubscribeHandler</code> was registered with the server as a module while * starting up the server. * * @return the <code>PresenceSubscribeHandler</code> registered with this server. */ public PresenceSubscribeHandler getPresenceSubscribeHandler() { return (PresenceSubscribeHandler) modules.get(PresenceSubscribeHandler.class); } /** * Returns the <code>IQRouter</code> registered with this server. The * <code>IQRouter</code> was registered with the server as a module while starting up * the server. * * @return the <code>IQRouter</code> registered with this server. */ public IQRouter getIQRouter() { return (IQRouter) modules.get(IQRouter.class); } /** * Returns the <code>MessageRouter</code> registered with this server. The * <code>MessageRouter</code> was registered with the server as a module while starting up * the server. * * @return the <code>MessageRouter</code> registered with this server. */ public MessageRouter getMessageRouter() { return (MessageRouter) modules.get(MessageRouter.class); } /** * Returns the <code>PresenceRouter</code> registered with this server. The * <code>PresenceRouter</code> was registered with the server as a module while starting up * the server. * * @return the <code>PresenceRouter</code> registered with this server. */ public PresenceRouter getPresenceRouter() { return (PresenceRouter) modules.get(PresenceRouter.class); } /** * Returns the <code>MulticastRouter</code> registered with this server. The * <code>MulticastRouter</code> was registered with the server as a module while starting up * the server. * * @return the <code>MulticastRouter</code> registered with this server. */ public MulticastRouter getMulticastRouter() { return (MulticastRouter) modules.get(MulticastRouter.class); } /** * Returns the <code>UserManager</code> registered with this server. The * <code>UserManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>UserManager</code> registered with this server. */ public UserManager getUserManager() { return UserManager.getInstance(); } /** * Returns the <code>UpdateManager</code> registered with this server. The * <code>UpdateManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>UpdateManager</code> registered with this server. */ public UpdateManager getUpdateManager() { return (UpdateManager) modules.get(UpdateManager.class); } /** * Returns the <code>AuditManager</code> registered with this server. The * <code>AuditManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>AuditManager</code> registered with this server. */ public AuditManager getAuditManager() { return (AuditManager) modules.get(AuditManagerImpl.class); } /** * Returns a list with all the modules that provide "discoverable" features. * * @return a list with all the modules that provide "discoverable" features. */ public List<ServerFeaturesProvider> getServerFeaturesProviders() { List<ServerFeaturesProvider> answer = new ArrayList<ServerFeaturesProvider>(); for (Module module : modules.values()) { if (module instanceof ServerFeaturesProvider) { answer.add((ServerFeaturesProvider) module); } } return answer; } /** * Returns a list with all the modules that provide "discoverable" items associated with * the server. * * @return a list with all the modules that provide "discoverable" items associated with * the server. */ public List<ServerItemsProvider> getServerItemsProviders() { List<ServerItemsProvider> answer = new ArrayList<ServerItemsProvider>(); for (Module module : modules.values()) { if (module instanceof ServerItemsProvider) { answer.add((ServerItemsProvider) module); } } return answer; } /** * Returns the <code>IQDiscoInfoHandler</code> registered with this server. The * <code>IQDiscoInfoHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>IQDiscoInfoHandler</code> registered with this server. */ public IQDiscoInfoHandler getIQDiscoInfoHandler() { return (IQDiscoInfoHandler) modules.get(IQDiscoInfoHandler.class); } /** * Returns the <code>IQDiscoItemsHandler</code> registered with this server. The * <code>IQDiscoItemsHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>IQDiscoItemsHandler</code> registered with this server. */ public IQDiscoItemsHandler getIQDiscoItemsHandler() { return (IQDiscoItemsHandler) modules.get(IQDiscoItemsHandler.class); } /** * Returns the <code>PrivateStorage</code> registered with this server. The * <code>PrivateStorage</code> was registered with the server as a module while starting up * the server. * * @return the <code>PrivateStorage</code> registered with this server. */ public PrivateStorage getPrivateStorage() { return (PrivateStorage) modules.get(PrivateStorage.class); } /** * Returns the <code>MultiUserChatServer</code> registered with this server. The * <code>MultiUserChatServer</code> was registered with the server as a module while starting up * the server. * * @return the <code>MultiUserChatServer</code> registered with this server. */ public MultiUserChatServer getMultiUserChatServer() { return (MultiUserChatServer) modules.get(MultiUserChatServerImpl.class); } /** * Returns the <code>AdHocCommandHandler</code> registered with this server. The * <code>AdHocCommandHandler</code> was registered with the server as a module while starting up * the server. * * @return the <code>AdHocCommandHandler</code> registered with this server. */ public AdHocCommandHandler getAdHocCommandHandler() { return (AdHocCommandHandler) modules.get(AdHocCommandHandler.class); } /** * Returns the <code>FileTransferProxy</code> registered with this server. The * <code>FileTransferProxy</code> was registered with the server as a module while starting up * the server. * * @return the <code>FileTransferProxy</code> registered with this server. */ public FileTransferProxy getFileTransferProxy() { return (FileTransferProxy) modules.get(FileTransferProxy.class); } /** * Returns the <code>FileTransferManager</code> registered with this server. The * <code>FileTransferManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>FileTransferProxy</code> registered with this server. */ public FileTransferManager getFileTransferManager() { return (FileTransferManager) modules.get(DefaultFileTransferManager.class); } /** * Returns the <code>MediaProxyService</code> registered with this server. The * <code>MediaProxyService</code> was registered with the server as a module while starting up * the server. * * @return the <code>MediaProxyService</code> registered with this server. */ public MediaProxyService getMediaProxyService() { return (MediaProxyService) modules.get(MediaProxyService.class); } /** * Returns the <code>STUNService</code> registered with this server. The * <code>MediaProxyService</code> was registered with the server as a module while starting up * the server. * * @return the <code>STUNService</code> registered with this server. */ public STUNService getSTUNService() { return (STUNService) modules.get(STUNService.class); } /** * Returns the <code>InternalComponentManager</code> registered with this server. The * <code>InternalComponentManager</code> was registered with the server as a module while starting up * the server. * * @return the <code>InternalComponentManager</code> registered with this server. */ private InternalComponentManager getComponentManager() { return (InternalComponentManager) modules.get(InternalComponentManager.class); } }
package hex.tree.xgboost; import hex.DataInfo; import hex.ModelBuilder; import hex.ModelCategory; import hex.ScoreKeeper; import hex.glm.GLMTask; import ml.dmlc.xgboost4j.java.Booster; import ml.dmlc.xgboost4j.java.DMatrix; import ml.dmlc.xgboost4j.java.XGBoostError; import water.H2O; import water.Job; import water.Key; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.Log; import water.util.Timer; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static hex.tree.SharedTree.createModelSummaryTable; import static hex.tree.SharedTree.createScoringHistoryTable; /** Gradient Boosted Trees * * Based on "Elements of Statistical Learning, Second Edition, page 387" */ public class XGBoost extends ModelBuilder<XGBoostModel,XGBoostModel.XGBoostParameters,XGBoostOutput> { @Override public boolean haveMojo() { return true; } static boolean haveBackend() { return true; } @Override public BuilderVisibility builderVisibility() { return haveBackend() ? BuilderVisibility.Stable : BuilderVisibility.Experimental; } /** * convert an H2O Frame to a sparse DMatrix * @param f H2O Frame * @param response name of the response column * @param weight name of the weight column * @param fold name of the fold assignment column * @param featureMap featureMap[0] will be populated with the column names and types * @return DMatrix * @throws XGBoostError */ public static DMatrix convertFrametoDMatrix(Key<DataInfo> dataInfoKey, Frame f, String response, String weight, String fold, String[] featureMap, boolean sparse) throws XGBoostError { DataInfo di = dataInfoKey.get(); // set the names for the (expanded) columns if (featureMap!=null) { String[] coefnames = di.coefNames(); StringBuilder sb = new StringBuilder(); assert(coefnames.length == di.fullN()); for (int i = 0; i < di.fullN(); ++i) { sb.append(i).append(" ").append(coefnames[i].replaceAll("\\s*","")).append(" "); int catCols = di._catOffsets[di._catOffsets.length-1]; if (i < catCols || f.vec(i-catCols).isBinary()) sb.append("i"); else if (f.vec(i-catCols).isInt()) sb.append("int"); else sb.append("q"); sb.append("\n"); } featureMap[0] = sb.toString(); } DMatrix trainMat; int nz = 0; int actualRows = 0; int nRows = (int) f.numRows(); Vec.Reader w = weight == null ? null : f.vec(weight).new Reader(); Vec.Reader[] vecs = new Vec.Reader[f.numCols()]; for (int i = 0; i < vecs.length; ++i) { vecs[i] = f.vec(i).new Reader(); } try { if (sparse) { Log.info("Treating matrix as sparse."); // 1 0 2 0 // 4 0 0 3 // 3 1 2 0 boolean csc = false; //di._cats == 0; // truly sparse matrix - no categoricals // collect all nonzeros column by column (in parallel), then stitch together into final data structures if (csc) { // CSC: // long[] colHeaders = new long[] {0, 3, 4, 6, 7}; //offsets // float[] data = new float[] {1f,4f,3f, 1f, 2f,2f, 3f}; //non-zeros down each column // int[] rowIndex = new int[] {0,1,2, 2, 0, 2, 1}; //row index for each non-zero class SparseItem { int pos; double val; } int nCols = di._nums; List<SparseItem>[] col = new List[nCols]; //TODO: use more efficient storage (no GC) // allocate for (int i=0;i<nCols;++i) { col[i] = new ArrayList<>(Math.min(nRows, 10000)); } // collect non-zeros int nzCount=0; for (int i=0;i<nCols;++i) { //TODO: parallelize over columns Vec v = f.vec(i); for (int c=0;c<v.nChunks();++c) { Chunk ck = v.chunkForChunkIdx(c); int[] nnz = new int[ck.sparseLenZero()]; int nnzCount = ck.nonzeros(nnz); for (int k=0;k<nnzCount;++k) { SparseItem item = new SparseItem(); int localIdx = nnz[k]; item.pos = (int)ck.start() + localIdx; // both 0 and NA are omitted in the sparse DMatrix if (w != null && w.at(item.pos) == 0) continue; if (ck.isNA(localIdx)) continue; item.val = ck.atd(localIdx); col[i].add(item); nzCount++; } } } long[] colHeaders = new long[nCols + 1]; float[] data = new float[nzCount]; int[] rowIndex = new int[nzCount]; // fill data for DMatrix for (int i=0;i<nCols;++i) { //TODO: parallelize over columns List sparseCol = col[i]; colHeaders[i] = nz; for (int j=0;j<sparseCol.size();++j) { SparseItem si = (SparseItem)sparseCol.get(j); rowIndex[nz] = si.pos; data[nz] = (float)si.val; assert(si.val != 0); assert(!Double.isNaN(si.val)); assert(w == null || w.at(si.pos) != 0); nz++; } } colHeaders[nCols] = nz; data = Arrays.copyOf(data, nz); rowIndex = Arrays.copyOf(rowIndex, nz); actualRows = countUnique(rowIndex); trainMat = new DMatrix(colHeaders, rowIndex, data, DMatrix.SparseType.CSC, actualRows); assert trainMat.rowNum() == actualRows; } else { // CSR: // long[] rowHeaders = new long[] {0, 2, 4, 7}; //offsets // float[] data = new float[] {1f,2f, 4f,3f, 3f,1f,2f}; //non-zeros across each row // int[] colIndex = new int[] {0, 2, 0, 3, 0, 1, 2}; //col index for each non-zero long[] rowHeaders = new long[nRows + 1]; int initial_size = 1 << 20; float[] data = new float[initial_size]; int[] colIndex = new int[initial_size]; // extract predictors rowHeaders[0] = 0; for (int i = 0; i < nRows; ++i) { if (w != null && w.at(i) == 0) continue; int nzstart = nz; // enlarge final data arrays by 2x if needed while (data.length < nz + di._cats + di._nums) { int newLen = (int) Math.min((long) data.length << 1L, (long) (Integer.MAX_VALUE - 10)); Log.info("Enlarging sparse data structure from " + data.length + " bytes to " + newLen + " bytes."); if (data.length == newLen) { throw new IllegalArgumentException("Data is too large to fit into the 32-bit Java float[] array that needs to be passed to the XGBoost C++ backend. Use H2O GBM instead."); } data = Arrays.copyOf(data, newLen); colIndex = Arrays.copyOf(colIndex, newLen); } for (int j = 0; j < di._cats; ++j) { if (!vecs[j].isNA(i)) { data[nz] = 1; //one-hot encoding colIndex[nz] = di.getCategoricalId(j, vecs[j].at8(i)); nz++; } else { // NA == 0 for sparse -> no need to fill // data[nz] = 1; //one-hot encoding // colIndex[nz] = di.getCategoricalId(j, Double.NaN); //Fill NA bucket } } for (int j = 0; j < di._nums; ++j) { float val = (float) vecs[di._cats + j].at(i); if (!Float.isNaN(val) && val != 0) { data[nz] = val; colIndex[nz] = di._catOffsets[di._catOffsets.length - 1] + j; nz++; } } if (nz == nzstart) { // for the corner case where there are no categorical values, and all numerical values are 0, we need to // assign a 0 value to any one column to have a consistent number of rows between the predictors and the special vecs (weight/response/etc.) data[nz] = 0; colIndex[nz] = 0; nz++; } rowHeaders[++actualRows] = nz; } data = Arrays.copyOf(data, nz); colIndex = Arrays.copyOf(colIndex, nz); rowHeaders = Arrays.copyOf(rowHeaders, actualRows + 1); trainMat = new DMatrix(rowHeaders, colIndex, data, DMatrix.SparseType.CSR, di.fullN()); assert trainMat.rowNum() == actualRows; } } else { Log.info("Treating matrix as dense."); // extract predictors float[] data = new float[1 << 20]; int cols = di.fullN(); int pos = 0; for (int i = 0; i < nRows; ++i) { if (w != null && w.at(i) == 0) continue; // enlarge final data arrays by 2x if needed while (data.length < (actualRows + 1) * cols) { int newLen = (int) Math.min((long) data.length << 1L, (long) (Integer.MAX_VALUE - 10)); Log.info("Enlarging dense data structure from " + data.length + " bytes to " + newLen + " bytes."); if (data.length == newLen) { throw new IllegalArgumentException("Data is too large to fit into the 32-bit Java float[] array that needs to be passed to the XGBoost C++ backend. Try setting dmatrix_type to 'sparse' or use H2O GBM instead."); } data = Arrays.copyOf(data, newLen); } for (int j = 0; j < di._cats; ++j) { if (vecs[j].isNA(i)) { data[pos + di.getCategoricalId(j, Double.NaN)] = 1; // fill NA bucket } else { data[pos + di.getCategoricalId(j, vecs[j].at8(i))] = 1; } } for (int j = 0; j < di._nums; ++j) { if (vecs[di._cats + j].isNA(i)) data[pos + di._catOffsets[di._catOffsets.length - 1] + j] = Float.NaN; else data[pos + di._catOffsets[di._catOffsets.length - 1] + j] = (float) vecs[di._cats + j].at(i); } assert di._catOffsets[di._catOffsets.length - 1] + di._nums == cols; pos += cols; actualRows++; } data = Arrays.copyOf(data, actualRows * cols); trainMat = new DMatrix(data, actualRows, cols, Float.NaN); assert trainMat.rowNum() == actualRows; } } catch (NegativeArraySizeException e) { throw new UnsupportedOperationException("Data is too large to fit into the 32-bit Java float[] array that needs to be passed to the XGBoost C++ backend. Use H2O GBM instead."); } // extract weight vector float[] weights = new float[actualRows]; if (w != null) { int j = 0; for (int i = 0; i < nRows; ++i) { if (w.at(i) == 0) continue; weights[j++] = (float) w.at(i); } assert (j == actualRows); } // extract response vector Vec.Reader respVec = f.vec(response).new Reader(); float[] resp = new float[actualRows]; int j = 0; for (int i = 0; i < nRows; ++i) { if (w != null && w.at(i) == 0) continue; resp[j++] = (float) respVec.at(i); } assert (j == actualRows); resp = Arrays.copyOf(resp, actualRows); weights = Arrays.copyOf(weights, actualRows); trainMat.setLabel(resp); if (w!=null) trainMat.setWeight(weights); // trainMat.setGroup(null); //fold //FIXME - only needed if CV is internally done in XGBoost return trainMat; } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ ModelCategory.Regression, ModelCategory.Binomial, ModelCategory.Multinomial, }; } // Called from an http request public XGBoost(XGBoostModel.XGBoostParameters parms ) { super(parms ); init(false); } public XGBoost(XGBoostModel.XGBoostParameters parms, Key<XGBoostModel> key) { super(parms, key); init(false); } public XGBoost(boolean startup_once) { super(new XGBoostModel.XGBoostParameters(),startup_once); } public boolean isSupervised(){return true;} @Override protected int nModelsInParallel() { return 2; } /** Start the XGBoost training Job on an F/J thread. */ @Override protected XGBoostDriver trainModelImpl() { return new XGBoostDriver(); } /** 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 learning rate and distribution family. */ @Override public void init(boolean expensive) { super.init(expensive); // Initialize response based on given distribution family. // Regression: initially predict the response mean // Binomial: just class 0 (class 1 in the exact inverse prediction) // Multinomial: Class distribution which is not a single value. // However there is this weird tension on the initial value for // classification: If you guess 0's (no class is favored over another), // then with your first GBM tree you'll typically move towards the correct // answer a little bit (assuming you have decent predictors) - and // immediately the Confusion Matrix shows good results which gradually // improve... BUT the Means Squared Error will suck for unbalanced sets, // even as the CM is good. That's because we want the predictions for the // common class to be large and positive, and the rare class to be negative // and instead they start around 0. Guessing initial zero's means the MSE // is so bad, that the R^2 metric is typically negative (usually it's // between 0 and 1). // If instead you guess the mean (reversed through the loss function), then // the zero-tree XGBoost model reports an MSE equal to the response variance - // and an initial R^2 of zero. More trees gradually improves the R^2 as // expected. However, all the minority classes have large guesses in the // wrong direction, and it takes a long time (lotsa trees) to correct that // - so your CM sucks for a long time. if (expensive) { if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(XGBoost.this); if (hasOffsetCol()) { error("_offset_column", "Offset is not supported for XGBoost."); } } if (H2O.CLOUD.size()>1) { throw new IllegalArgumentException("XGBoost is currently only supported in single-node mode."); } if ( _parms._backend == XGBoostModel.XGBoostParameters.Backend.gpu && !hasGPU()) { error("_backend", "GPU backend is not functional. Check CUDA_PATH and/or GPU installation."); } switch( _parms._distribution) { case bernoulli: if( _nclass != 2 /*&& !couldBeBool(_response)*/) error("_distribution", H2O.technote(2, "Binomial requires the response to be a 2-class categorical")); break; case modified_huber: if( _nclass != 2 /*&& !couldBeBool(_response)*/) error("_distribution", H2O.technote(2, "Modified Huber requires the response to be a 2-class categorical.")); break; case multinomial: if (!isClassifier()) error("_distribution", H2O.technote(2, "Multinomial requires an categorical response.")); break; case huber: if (isClassifier()) error("_distribution", H2O.technote(2, "Huber requires the response to be numeric.")); break; case poisson: if (isClassifier()) error("_distribution", H2O.technote(2, "Poisson requires the response to be numeric.")); break; case gamma: if (isClassifier()) error("_distribution", H2O.technote(2, "Gamma requires the response to be numeric.")); break; case tweedie: if (isClassifier()) error("_distribution", H2O.technote(2, "Tweedie requires the response to be numeric.")); break; case gaussian: if (isClassifier()) error("_distribution", H2O.technote(2, "Gaussian requires the response to be numeric.")); break; case laplace: if (isClassifier()) error("_distribution", H2O.technote(2, "Laplace requires the response to be numeric.")); break; case quantile: if (isClassifier()) error("_distribution", H2O.technote(2, "Quantile requires the response to be numeric.")); break; case AUTO: break; default: error("_distribution","Invalid distribution: " + _parms._distribution); } if( !(0. < _parms._learn_rate && _parms._learn_rate <= 1.0) ) error("_learn_rate", "learn_rate must be between 0 and 1"); if( !(0. < _parms._col_sample_rate && _parms._col_sample_rate <= 1.0) ) error("_col_sample_rate", "col_sample_rate must be between 0 and 1"); if (_parms._grow_policy== XGBoostModel.XGBoostParameters.GrowPolicy.lossguide && _parms._tree_method!= XGBoostModel.XGBoostParameters.TreeMethod.hist) error("_grow_policy", "must use tree_method=hist for grow_policy=lossguide"); } static DataInfo makeDataInfo(Frame train, Frame valid, XGBoostModel.XGBoostParameters parms, int nClasses) { DataInfo dinfo = new DataInfo( train, valid, 1, //nResponses true, //all factor levels DataInfo.TransformType.NONE, //do not standardize DataInfo.TransformType.NONE, //do not standardize response parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip, //whether to skip missing false, // do not replace NAs in numeric cols with mean true, // always add a bucket for missing values parms._weights_column != null, // observation weights parms._offset_column != null, parms._fold_column != null ); // Checks and adjustments: // 1) observation weights (adjust mean/sigmas for predictors and response) // 2) NAs (check that there's enough rows left) GLMTask.YMUTask ymt = new GLMTask.YMUTask(dinfo, nClasses,nClasses == 1, parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip, true).doAll(dinfo._adaptedFrame); if (ymt.wsum() == 0 && parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip) throw new H2OIllegalArgumentException("No rows left in the dataset after filtering out rows with missing values. Ignore columns with many NAs or set missing_values_handling to 'MeanImputation'."); if (parms._weights_column != null && parms._offset_column != null) { Log.warn("Combination of offset and weights can lead to slight differences because Rollupstats aren't weighted - need to re-calculate weighted mean/sigma of the response including offset terms."); } if (parms._weights_column != null && parms._offset_column == null /*FIXME: offset not yet implemented*/) { dinfo.updateWeightedSigmaAndMean(ymt.predictorSDs(), ymt.predictorMeans()); if (nClasses == 1) dinfo.updateWeightedSigmaAndMeanForResponse(ymt.responseSDs(), ymt.responseMeans()); } return dinfo; } private class XGBoostDriver extends Driver { @Override public void computeImpl() { init(true); //this can change the seed if it was set to -1 long cs = _parms.checksum(); // Something goes wrong if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(XGBoost.this); buildModel(); //check that _parms isn't changed during DL model training // long cs2 = _parms.checksum(); //they can change now (when the user specifies a parameter in XGBoost convention) - otherwise, need to check two different parameters everywhere... // assert(cs == cs2); } final void buildModel() { XGBoostModel model = new XGBoostModel(_result,_parms,new XGBoostOutput(XGBoost.this),_train,_valid); model.write_lock(_job); String[] featureMap = new String[]{""}; if (_parms._dmatrix_type == XGBoostModel.XGBoostParameters.DMatrixType.sparse) { model._output._sparse = true; } else if (_parms._dmatrix_type == XGBoostModel.XGBoostParameters.DMatrixType.dense) { model._output._sparse = false; } else { float fillRatio = 0; int col = 0; for (int i = 0; i < _train.numCols(); ++i) { if (_train.name(i).equals(_parms._response_column)) continue; if (_train.name(i).equals(_parms._weights_column)) continue; if (_train.name(i).equals(_parms._fold_column)) continue; if (_train.name(i).equals(_parms._offset_column)) continue; fillRatio += _train.vec(i).nzCnt() / _train.numRows(); col++; } fillRatio /= col; Log.info("fill ratio: " + fillRatio); model._output._sparse = fillRatio < 0.5 || ((_train.numRows() * (long) _train.numCols()) > Integer.MAX_VALUE); } try { DMatrix trainMat = convertFrametoDMatrix( model.model_info()._dataInfoKey, _train, _parms._response_column, _parms._weights_column, _parms._fold_column, featureMap, model._output._sparse); DMatrix validMat = _valid != null ? convertFrametoDMatrix(model.model_info()._dataInfoKey, _valid, _parms._response_column, _parms._weights_column, _parms._fold_column, featureMap, model._output._sparse) : null; // For feature importances - write out column info OutputStream os; try { os = new FileOutputStream("/tmp/featureMap.txt"); os.write(featureMap[0].getBytes()); os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } HashMap<String, DMatrix> watches = new HashMap<>(); if (validMat!=null) watches.put("valid", validMat); else watches.put("train", trainMat); // create the backend model.model_info()._booster = ml.dmlc.xgboost4j.java.XGBoost.train(trainMat, model.createParams(), 0, watches, null, null); // train the model scoreAndBuildTrees(model, trainMat, validMat); // final scoring doScoring(model, model.model_info()._booster, trainMat, validMat, true); // save the model to DKV model.model_info().nativeToJava(); } catch (XGBoostError xgBoostError) { xgBoostError.printStackTrace(); } model._output._boosterBytes = model.model_info()._boosterBytes; model.unlock(_job); } protected final void scoreAndBuildTrees(XGBoostModel model, DMatrix trainMat, DMatrix validMat) throws XGBoostError { for( int tid=0; tid< _parms._ntrees; tid++) { // During first iteration model contains 0 trees, then 1-tree, ... boolean scored = doScoring(model, model.model_info()._booster, trainMat, validMat, false); if (scored && ScoreKeeper.stopEarly(model._output.scoreKeepers(), _parms._stopping_rounds, _nclass > 1, _parms._stopping_metric, _parms._stopping_tolerance, "model's last", true)) { doScoring(model, model.model_info()._booster, trainMat, validMat, true); _job.update(_parms._ntrees-model._output._ntrees); //finish return; } Timer kb_timer = new Timer(); try { // model.model_info()._booster.setParam("eta", effective_learning_rate(model)); model.model_info()._booster.update(trainMat, tid); } catch (XGBoostError xgBoostError) { xgBoostError.printStackTrace(); } Log.info((tid + 1) + ". tree was built in " + kb_timer.toString()); _job.update(1); // Optional: for convenience // model.update(_job); // model.model_info().nativeToJava(); model._output._ntrees++; model._output._scored_train = ArrayUtils.copyAndFillOf(model._output._scored_train, model._output._ntrees+1, new ScoreKeeper()); model._output._scored_valid = model._output._scored_valid != null ? ArrayUtils.copyAndFillOf(model._output._scored_valid, model._output._ntrees+1, new ScoreKeeper()) : null; model._output._training_time_ms = ArrayUtils.copyAndFillOf(model._output._training_time_ms, model._output._ntrees+1, System.currentTimeMillis()); if (stop_requested() && !timeout()) throw new Job.JobCancelledException(); if (timeout()) { //stop after scoring if (!scored) doScoring(model, model.model_info()._booster, trainMat, validMat, true); _job.update(_parms._ntrees-model._output._ntrees); //finish break; } } doScoring(model, model.model_info()._booster, trainMat, validMat, true); } long _firstScore = 0; long _timeLastScoreStart = 0; long _timeLastScoreEnd = 0; private boolean doScoring(XGBoostModel model, Booster booster, DMatrix trainMat, DMatrix validMat, boolean finalScoring) throws XGBoostError { boolean scored = false; long now = System.currentTimeMillis(); if (_firstScore == 0) _firstScore = now; long sinceLastScore = now - _timeLastScoreStart; _job.update(0, "Built " + model._output._ntrees + " trees so far (out of " + _parms._ntrees + ")."); boolean timeToScore = (now - _firstScore < _parms._initial_score_interval) || // Score every time for 4 secs // Throttle scoring to keep the cost sane; limit to a 10% duty cycle & every 4 secs (sinceLastScore > _parms._score_interval && // Limit scoring updates to every 4sec (double) (_timeLastScoreEnd - _timeLastScoreStart) / sinceLastScore < 0.1); //10% duty cycle boolean manualInterval = _parms._score_tree_interval > 0 && model._output._ntrees % _parms._score_tree_interval == 0; // Now model already contains tid-trees in serialized form if (_parms._score_each_iteration || finalScoring || // always score under these circumstances (timeToScore && _parms._score_tree_interval == 0) || // use time-based duty-cycle heuristic only if the user didn't specify _score_tree_interval manualInterval) { _timeLastScoreStart = now; model.doScoring(booster, trainMat, validMat); _timeLastScoreEnd = System.currentTimeMillis(); model.computeVarImp(booster.getFeatureScore("/tmp/featureMap.txt")); XGBoostOutput out = model._output; out._model_summary = createModelSummaryTable(out._ntrees, null); out._scoring_history = createScoringHistoryTable(out, model._output._scored_train, out._scored_valid, _job, out._training_time_ms); out._variable_importances = hex.ModelMetrics.calcVarImp(out._varimp); model.update(_job); Log.info(model); scored = true; } return scored; } } private double effective_learning_rate(XGBoostModel model) { return _parms._learn_rate * Math.pow(_parms._learn_rate_annealing, (model._output._ntrees-1)); } // helper static boolean hasGPU() { DMatrix trainMat = null; try { trainMat = new DMatrix(new float[]{1,2,1,2},2,2); trainMat.setLabel(new float[]{1,0}); } catch (XGBoostError xgBoostError) { xgBoostError.printStackTrace(); } HashMap<String, Object> params = new HashMap<>(); params.put("updater", "grow_gpu"); params.put("silent", 1); HashMap<String, DMatrix> watches = new HashMap<>(); watches.put("train", trainMat); try { ml.dmlc.xgboost4j.java.XGBoost.train(trainMat, params, 1, watches, null, null); return true; } catch (XGBoostError xgBoostError) { return false; } } public static int countUnique(int[] unsortedArray) { if (unsortedArray.length == 0) { return 0; } int[] array = Arrays.copyOf(unsortedArray, unsortedArray.length); Arrays.sort(array); int count = 1; for (int i = 0; i < array.length - 1; i++) { if (array[i] != array[i + 1]) { count++; } } return count; } }
package com.hamishrickerby.http_server; public class App { public static void main(String[] args) { AppArguments arguments = new AppArguments(args); Integer port = Integer.parseInt(arguments.getOrDefault("-p", "5000")); String rootDirectory = arguments.get("-d"); if (rootDirectory == null) { System.err.println("Must provide a root directory with a -d argument."); System.exit(1); } SocketServer server = null; try { server = new SocketServer(port, rootDirectory); System.out.println("Mounted " + rootDirectory + " as the directory to serve from."); System.out.println("Server started on port " + port); while (true) { Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } finally { server.close(); } } }
package h2o.common.lang; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; public final class SNumber extends Number implements NullableValue, Comparable<SNumber> , java.io.Serializable { private static final long serialVersionUID = -2650821778406349289L; public static final SNumber NULL = new SNumber(); public static final SNumber ZERO = new SNumber("0",true); public static final SNumber ONE = new SNumber("1",true); private final String value; public SNumber() { this.value = null; } public SNumber( long value ) { this.value = BigDecimal.valueOf(value).toString(); } public SNumber( double value ) { this.value = BigDecimal.valueOf(value).toString(); } public SNumber( Number number ) { if ( number == null ) { this.value = null; } else if ( number instanceof Integer || number instanceof Double || number instanceof Long || number instanceof BigDecimal || number instanceof Float || number instanceof BigInteger || number instanceof Short ) { this.value = number.toString(); } else if ( number instanceof SNumber ) { this.value = ((SNumber)number).value; } else { this.value = new BigDecimal(number.toString().trim()).toString(); } } public SNumber( String num ) { this( num , false ); } public SNumber( String num , boolean direct ) { if ( direct ) { this.value = num; } else { this.value = num == null ? null : new BigDecimal(num).toString(); } } public SNumber( SNumber snumber ) { this.value = snumber.value; } @Override public boolean isPresent() { return value != null; } public String getValue() { return value; } public String get() { if ( this.isPresent() ) { return value; } throw new IllegalStateException(); } public String orElse(String other) { return this.isPresent() ? value : other; } public String fmt( String fmt ) { return new DecimalFormat(fmt).format( this.toBigDecimalExact() ); } public String fmt( String fmt , String def ) { return this.isPresent() ? this.fmt( fmt ) : def; } public BigDecimal toBigDecimal() { if ( this.isPresent() ) { return new BigDecimal( this.value ); } else { return null; } } public BigDecimal toBigDecimalExact() { if ( this.isPresent() ) { return new BigDecimal( this.value ); } else { throw new IllegalStateException(); } } public BigInteger toBigInteger() { if ( this.isPresent() ) { return new BigDecimal( this.value ).toBigInteger(); } else { return null; } } public BigInteger toBigIntegerExact() { if ( this.isPresent() ) { return new BigDecimal( this.value ).toBigIntegerExact(); } else { throw new IllegalStateException(); } } public Integer toInteger() { if ( this.isPresent() ) { return Integer.valueOf(new BigDecimal( this.value ).intValue()); } else { return null; } } public Integer toIntegerExact() { if ( this.isPresent() ) { return Integer.valueOf(new BigDecimal( this.value ).intValueExact()); } else { throw new IllegalStateException(); } } public Long toLong() { if ( this.isPresent() ) { return Long.valueOf(new BigDecimal( this.value ).longValue()); } else { return null; } } public Long toLongExact() { if ( this.isPresent() ) { return Long.valueOf(new BigDecimal( this.value ).longValueExact()); } else { throw new IllegalStateException(); } } public Float toFloat() { if ( this.isPresent() ) { return Float.valueOf(new BigDecimal( this.value ).floatValue()); } else { return null; } } public Float toFloatExact() { if ( this.isPresent() ) { return Float.valueOf(new BigDecimal( this.value ).floatValue()); } else { throw new IllegalStateException(); } } public Double toDouble() { if ( this.isPresent() ) { return Double.valueOf(new BigDecimal( this.value ).doubleValue()); } else { return null; } } public Double toDoubleExact() { if ( this.isPresent() ) { return Double.valueOf(new BigDecimal( this.value ).doubleValue()); } else { throw new IllegalStateException(); } } public Boolean toBoolean() { if ( this.isPresent() ) { return !(new BigDecimal( this.value ).toBigInteger().compareTo( BigInteger.ZERO ) == 0 ); } else { return null; } } public Boolean toBooleanExact() { if ( this.isPresent() ) { return !(new BigDecimal( this.value ).intValueExact() == 0); } else { throw new IllegalStateException(); } } public String toPlainString() { if ( this.isPresent() ) { return new BigDecimal(this.value).toPlainString(); } return null; } public String toPlainStringExact() { if ( this.isPresent() ) { return new BigDecimal(this.value).toPlainString(); } else { throw new IllegalStateException(); } } @Override public int intValue() { if ( this.isPresent() ) { return new BigDecimal( this.value ).intValue(); } else { throw new IllegalStateException(); } } @Override public long longValue() { if ( this.isPresent() ) { return new BigDecimal( this.value ).longValue(); } else { throw new IllegalStateException(); } } @Override public float floatValue() { if ( this.isPresent() ) { return new BigDecimal( this.value ).floatValue(); } else { throw new IllegalStateException(); } } @Override public double doubleValue() { if ( this.isPresent() ) { return new BigDecimal( this.value ).doubleValue(); } else { throw new IllegalStateException(); } } public SNumber add(SNumber augend) { if ( augend == null || ( !augend.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber(new BigDecimal(this.value).add( new BigDecimal(augend.value) ) ); } public SNumber subtract(SNumber subtrahend) { if ( subtrahend == null || ( !subtrahend.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).subtract( new BigDecimal(subtrahend.value) ) ); } public SNumber multiply(SNumber multiplicand) { if ( multiplicand == null || ( !multiplicand.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).multiply( new BigDecimal(multiplicand.value) ) ); } public SNumber divide(SNumber divisor) { if ( divisor == null || ( !divisor.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).divide( new BigDecimal(divisor.value) ) ); } public SNumber divide(SNumber divisor , RoundingMode roundingMode) { if ( divisor == null || ( !divisor.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).divide( new BigDecimal(divisor.value) , roundingMode ) ); } public SNumber divide(SNumber divisor, int scale, RoundingMode roundingMode) { if ( divisor == null || ( !divisor.isPresent() ) ) { throw new IllegalArgumentException(); } if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).divide( new BigDecimal(divisor.value) , scale, roundingMode ) ); } public SNumber toScale(int scale, RoundingMode roundingMode) { if ( !this.isPresent() ) { throw new IllegalStateException(); } return new SNumber( new BigDecimal(this.value).setScale( scale , roundingMode ) ); } @Override public int compareTo(SNumber o) { if ( this.isPresent() && o.isPresent() ) { return this.toBigDecimal().compareTo( o.toBigDecimal() ); } else if ( ( ! this.isPresent() ) && ( ! o.isPresent()) ) { return 0; } else { return this.isPresent() ? 1 : -1; } } public boolean valueEquals( SNumber o ) { if ( o == null ) { return ! this.isPresent(); } return this.compareTo( o ) == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof SNumber)) return false; SNumber sNumber = (SNumber) o; return new EqualsBuilder() .append(value, sNumber.value) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(value) .toHashCode(); } @Override public String toString() { return this.orElse("<null>"); } }
//@formatter:off @NamedQueries({ @NamedQuery(name = "Fragment.countAll", query = "select count(*) " + "from Fragment f" ), @NamedQuery(name = "Fragment.countAllNonTrashed", query = "select count(*) " + "from Fragment f " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " ), @NamedQuery(name = "Fragment.findById", query = "select distinct f " + "from Fragment f " + "where f.id = :id " ), @NamedQuery(name = "Fragment.findByIdWithAll", query = "select distinct f " + "from Fragment f " + " left join fetch f.tags " + " left join fetch f.relatedOnes " + "where f.id = :id " ), @NamedQuery(name = "Fragment.findByIdWithRelatedOnes", query = "select distinct f " + "from Fragment f " + " left join fetch f.relatedOnes " + "where f.id = :id " ), @NamedQuery(name = "Fragment.findByIdWithTags", query = "select distinct f " + "from Fragment f " + " left join fetch f.tags " + "where f.id = :id " ), @NamedQuery(name = "Fragment.findIds", query = "select f.id " + "from Fragment f " + "order by f.updateDatetime desc " ), @NamedQuery(name = "Fragment.findIdsNonTrashedOrderByUpdateDatetime", query = "select f.id " + "from Fragment f " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " + "order by f.updateDatetime desc " ), @NamedQuery(name = "Fragment.findIdsNonTrashedOrderByCreationDatetime", query = "select f.id " + "from Fragment f " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " + "order by f.creationDatetime desc " ), @NamedQuery(name = "Fragment.findIdsNonTrashedOrderByTitle", query = "select f.id " + "from Fragment f " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " + "order by lower(f.title) desc " ), @NamedQuery(name = "Fragment.findIdsNonTrashedOrderById", query = "select f.id " + "from Fragment f " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " + "order by f.id desc " ), @NamedQuery(name = "Fragment.findNonTrashedWithTagsOrderByUpdateDatetime", query = "from Fragment f " + " left join fetch f.tags " + "where f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " + "order by f.updateDatetime desc " ), @NamedQuery(name = "Tag.countAll", query = "select count(*) " + "from Tag t" ), @NamedQuery(name = "Tag.findIdsOrderByTagName", query = "select t.id " + "from Tag t " + "order by lower(t.tagName) asc " ), @NamedQuery(name = "Tag.findById", query = "select distinct t " + "from Tag t " + "where t.id = :id" ), @NamedQuery(name = "Tag.findByIdWithChildren", query = "select distinct t " + "from Tag t " + " left join fetch t.children " + "where t.id = :id " ), @NamedQuery(name = "Tag.findByIdWithFragments", query = "select distinct t " + "from Tag t " + " left join fetch t.fragments " + "where t.id = :id " ), // @NamedQuery(name = "Tag.countFragments", // query = "select count(f) " // + "from Tag t " // + " inner join t.fragments as f " // + "where t.id = :id " // @NamedQuery(name = "Tag.countNonTrashedFragments", // query = "select count(f) " // + "from Tag t " // + " inner join t.fragments as f " // + "where t.id = :id and f.id not in ( " // + " select t2f.fragmentId " // + " from Tag2Fragment t2f " // + " where t2f.tagId = 0 " @NamedQuery(name = "Tag.findFragments", query = "select distinct f " + "from Tag t " + " inner join t.fragments as f " + " left join fetch f.tags " + "where t.id = :id " ), @NamedQuery(name = "Tag.findNonTrashedFragments", query = "select distinct f " + "from Fragment f " + " inner join f.tags t " + " left join fetch f.tags " + "where t.id = :id and f.id not in ( " + " select t2f.fragmentId " + " from Tag2Fragment t2f " + " where t2f.tagId = 0 " + ") " ), @NamedQuery(name = "Tag.findFragmentsWithIdFilter", query = "select distinct f " + "from Tag t " + " inner join t.fragments as f " + " left join fetch f.tags " + "where t.id in (:ids) " ), @NamedQuery(name = "Tag.findParentTags", query = "select distinct t " + "from Tag t " + " inner join t.children child " + "where child.id = :id " ), @NamedQuery(name = "Tag2Fragment.findTrashedFragmentIds", query = "select t2f.fragmentId " + "from Tag2Fragment t2f " + "where t2f.tagId = 0 " ), }) package com.knowledgex.domain; import org.hibernate.annotations.NamedQueries; import org.hibernate.annotations.NamedQuery;
package com.legendzero.lzlib.util; import com.legendzero.lzlib.gui.GuiService; import com.legendzero.lzlib.service.Service; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.ServicePriority; import java.util.function.Function; import java.util.function.Supplier; public final class Services { private Services() {} public final void registerDefaultServiceProviders(Plugin plugin) { registerServiceProvider(plugin, GuiService.class, GuiService::new, ServicePriority.Lowest); } public static <T extends Service> T registerServiceProvider(Plugin plugin, Class<T> clazz, Supplier<T> supplier, ServicePriority priority) { if (plugin.getServer().getServicesManager().isProvidedFor(clazz)) { return plugin.getServer().getServicesManager().getRegistration(clazz).getProvider(); } else { T t = supplier.get(); t.initialize(); plugin.getServer().getServicesManager().register(clazz, t, plugin, priority); return t; } } public static <T extends Service> T registerServiceProvider(Plugin plugin, Class<T> clazz, Function<? super Plugin, T> function, ServicePriority priority) { return registerServiceProvider(plugin, clazz, () -> function.apply(plugin), priority); } }
package com.maxmind.geoip2.database; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.maxmind.geoip2.exception.AddressNotFoundException; import com.maxmind.geoip2.model.CountryLookup; import com.maxmind.geoip2.model.OmniLookup; /** * Instances of this class provide a reader for the GeoIP2 database format. IP * addresses can be looked up using the <code>get</code> method. */ public class Reader implements Closeable { // This is sort of annoying. Rename one of the two? private final com.maxmind.maxminddb.Reader reader; private final ObjectMapper om; /** * Constructs a Reader for the GeoIP2 database format. The file passed to it * must be a valid GeoIP2 database file. * * @param database * the GeoIP2 database file to use. * @throws IOException * if there is an error opening or reading from the file. */ public Reader(File database) throws IOException { this(database, Arrays.asList("en")); } /** * Constructs a Reader for the GeoIP2 database format. The file passed to it * must be a valid GeoIP2 database file. * * @param database * the GeoIP2 database file to use. * @param languages * List of language codes to use in name property from most * preferred to least preferred. * @throws IOException * if there is an error opening or reading from the file. */ public Reader(File database, List<String> languages) throws IOException { this.reader = new com.maxmind.maxminddb.Reader(database); this.om = new ObjectMapper(); this.om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); InjectableValues inject = new InjectableValues.Std().addValue( "languages", languages); this.om.setInjectableValues(inject); } /** * @param ipAddress * IPv4 or IPv6 address to lookup. * @return A <T> object with the data for the IP address * @throws IOException * if there is an error opening or reading from the file. * @throws AddressNotFoundException * if the IP address is not in our database */ public <T extends CountryLookup> T get(InetAddress ipAddress) throws IOException, AddressNotFoundException { ObjectNode node = (ObjectNode) this.reader.get(ipAddress); // XXX - I am not sure Java programmers would expect an exception here, // but the web service code does throw an exception in this case. If we // keep this exception, we should adjust the web service to throw the // same exception when it gets and IP_ADDRESS_NOT_FOUND error. if (node == null) { throw new AddressNotFoundException("The address " + ipAddress.getHostAddress() + " is not in the database."); } if (!node.has("traits")) { node.put("traits", this.om.createObjectNode()); } ObjectNode traits = (ObjectNode) node.get("traits"); traits.put("ip_address", ipAddress.getHostAddress()); // The cast and the OmniLookup.class are sort of ugly. There might be a // better way return (T) this.om.treeToValue(node, OmniLookup.class); } /** * Closes the GeoIP2 database and returns resources to the system. * * @throws IOException * if an I/O error occurs. */ @Override public void close() throws IOException { this.reader.close(); } }
package com.mikesamuel.cil.ptree; import java.util.List; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.RangeSet; import com.mikesamuel.cil.ast.MatchEvent; import com.mikesamuel.cil.ast.MatchEvent.LRSuffix; import com.mikesamuel.cil.ast.MatchEvent.PushMatchEvent; import com.mikesamuel.cil.ast.NodeType; import com.mikesamuel.cil.ast.NodeVariant; import com.mikesamuel.cil.parser.Chain; import com.mikesamuel.cil.parser.MatchErrorReceiver; import com.mikesamuel.cil.parser.MatchState; import com.mikesamuel.cil.parser.ParSer; import com.mikesamuel.cil.parser.ParSerable; import com.mikesamuel.cil.parser.ParseErrorReceiver; import com.mikesamuel.cil.parser.ParseState; import com.mikesamuel.cil.parser.RatPack; import com.mikesamuel.cil.parser.RatPack.ParseCacheEntry; import com.mikesamuel.cil.parser.SerialErrorReceiver; import com.mikesamuel.cil.parser.SerialState; final class Reference extends PTParSer { final String name; final NodeType nodeType; final ImmutableList<NodeVariant> variants; private GrowTheSeed growTheSeed; private LeftRecursionDone transferBackToStart; Reference( String name, Class<? extends Enum<? extends ParSerable>> variantClass) { this.name = name; ImmutableList.Builder<NodeVariant> variantsBuilder = ImmutableList.builder(); NodeType nt = null; for (Enum<?> e : variantClass.getEnumConstants()) { NodeVariant nv = (NodeVariant) e; variantsBuilder.add(nv); if (nt == null) { nt = nv.getNodeType(); } else { Preconditions.checkState(nt == nv.getNodeType()); } } this.nodeType = Preconditions.checkNotNull(nt); this.variants = variantsBuilder.build(); } @Override public String toString() { return name; } @Override Kind getKind() { return Kind.REF; } // HACK DEBUG: Not thread safe private static final boolean DEBUG = false; private static int depth = 0; private static String indent() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; ++i) { sb.append(" "); } return sb.toString(); } private static void indent(int delta) { Preconditions.checkState(depth + delta >= 0); depth += delta; } private static String lastInputSeen = ""; private static String dumpInput(String inp) { if (inp.equals(lastInputSeen)) { return null; } lastInputSeen = inp; return inp; } // END HACK private static ImmutableList<MatchEvent> lastOutputSeen = ImmutableList.of(); private static String dumpOutput(Chain<MatchEvent> out) { ImmutableList<MatchEvent> lastList = lastOutputSeen; ImmutableList<MatchEvent> outList = ImmutableList.copyOf( Chain.forward(out)); lastOutputSeen = outList; if (!lastList.isEmpty() && outList.size() >= lastList.size() && outList.subList(0, lastList.size()).equals(lastList)) { if (lastList.size() == outList.size()) { return null; } StringBuilder sb = new StringBuilder("[..."); for (MatchEvent e : outList.subList(lastList.size(), outList.size())) { sb.append(", ").append(e); } return sb.append(']').toString(); } return outList.toString(); } @Override public Optional<ParseState> parse(ParseState state, ParseErrorReceiver err) { ParseCacheEntry cachedParse = state.input.ratPack.getCachedParse( nodeType, state.index, RatPack.Kind.WHOLE); if (cachedParse.wasTried()) { if (cachedParse.passed()) { if (DEBUG) { System.err.println(indent() + "Using cached success for " + nodeType); } return Optional.of(cachedParse.apply(state)); } else { if (DEBUG) { System.err.println(indent() + "Using cached failure for " + nodeType); } return Optional.absent(); } } Profile.count(nodeType); if (DEBUG) { System.err.println(indent() + "Entered " + nodeType); String din = dumpInput(state.input.content.substring(state.index)); if (din != null) { System.err.println(indent() + ". . input=`" + din + "`"); } String dout = dumpOutput(state.output); if (dout != null) { System.err.println(indent() + ". . output=" + dout); } } int idx = state.indexAfterIgnorables(); int firstChar = idx < state.input.content.length() ? state.input.content.charAt(idx) : -1; boolean lookedForStartOfLeftRecursion = false; boolean leftRecursionFailed = false; for (NodeVariant variant : variants) { ParSer variantParSer = variant.getParSer(); if (firstChar >= 0 && variantParSer instanceof PTParSer) { RangeSet<Integer> la1 = ((PTParSer) variantParSer).getLookahead1(); if (la1 != null && !la1.contains(firstChar)) { continue; } } if (variant.isLeftRecursive()) { if (leftRecursionFailed) { continue; } boolean hasLeftRecursion = false; if (!lookedForStartOfLeftRecursion) { lookedForStartOfLeftRecursion = true; hasLeftRecursion = hasLeftRecursion(state); } if (hasLeftRecursion) { // We pre-parse the seed to make sure that the left-recursion // succeeds. Otherwise we just fail. // This allows us to fail-over to later non-LR options. // For example, there is a prefix ambiguity between // foo.new bar // foo.bar // foo.bar() // which is resolved by processing them in that order, but // the `new` operator production is left-recursive via Primary. if (this.parseSeed(state, err).isPresent()) { if (DEBUG) { System.err.println(indent() + "Throwing " + transferBackToStart); } if (transferBackToStart == null) { transferBackToStart = new LeftRecursionDone(nodeType); } throw transferBackToStart; } else { if (DEBUG) { System.err.println(indent() + variant + " had failing seed"); } leftRecursionFailed = true; continue; } } } else if (!lookedForStartOfLeftRecursion) { boolean foundAnLR = false; for (NodeVariant v : variants) { if (v.isLeftRecursive()) { foundAnLR = true; break; } } if (!foundAnLR) { lookedForStartOfLeftRecursion = true; if (hasLeftRecursion(state)) { throw new AssertionError(nodeType.name()); } } } ParseState result = null; if (DEBUG) { indent(1); } try { try { Optional<ParseState> next = variantParSer.parse( state.appendOutput(MatchEvent.push(variant)), err); if (next.isPresent()) { result = next.get().appendOutput(MatchEvent.pop()); } } finally { if (DEBUG) { indent(-1); } } } catch (LeftRecursionDone d) { if (d.leftRecursiveNodeType != nodeType) { if (DEBUG) { System.err.println( indent() + "LeftRecursing out of " + nodeType + " to " + d.leftRecursiveNodeType); } throw d; } if (DEBUG) { System.err.println(indent() + "Control returned to " + nodeType); } result = handleAsLeftRecursive(state, err).orNull(); if (DEBUG) { System.err.println( indent() + "handleAsLeftRecursive produced " + result); } } if (DEBUG) { System.err.println( indent() + "Result for " + variant + (result != null ? " @ " + result.index : " is <null>")); } if (result != null) { state.input.ratPack.cache( state.index, result.index, RatPack.Kind.WHOLE, result.output); if (nodeType == NodeType.AmbiguousName) { Thread.dumpStack(); } return Optional.of(result); } } if (DEBUG) { System.err.println(indent() + "Fail " + nodeType); } state.input.ratPack.cacheFailure(state.index, nodeType, RatPack.Kind.WHOLE); return Optional.absent(); } private Optional<ParseState> parseSeed( ParseState beforeRecursing, ParseErrorReceiver err) { RatPack ratPack = beforeRecursing.input.ratPack; RatPack.ParseCacheEntry e = ratPack.getCachedParse( nodeType, beforeRecursing.index, RatPack.Kind.SEED); if (e.wasTried()) { if (e.passed()) { ParseState afterSeed = e.apply(beforeRecursing); if (DEBUG) { System.err.println( indent() + "Using cached seed @ " + afterSeed.index); } return Optional.of(afterSeed); } else { if (DEBUG) { System.err.println(indent() + "Seed failure cached"); } return Optional.absent(); } } GrowTheSeed gts = getGrowTheSeed(); if (DEBUG) { System.err.println(indent() + ". . seed=" + gts.seed); System.err.println(indent() + ". . suffix=" + gts.suffix); } ParseState atStartOfLeftRecursion = beforeRecursing .appendOutput(MatchEvent.leftRecursionStart(nodeType)); Optional<ParseState> afterSeedOpt = gts.seed.getParSer().parse(atStartOfLeftRecursion, err); // Since we apply the seed before popping the stack back to the initial // invocation which has to reapply the seed, storage of a successful result // here is guaranteed to be used. if (afterSeedOpt.isPresent()) { ParseState afterSeed = afterSeedOpt.get(); ratPack.cache( beforeRecursing.index, afterSeed.index, RatPack.Kind.SEED, afterSeed.output); } else { ratPack.cacheFailure( beforeRecursing.index, nodeType, RatPack.Kind.SEED); } return afterSeedOpt; } private Optional<ParseState> handleAsLeftRecursive( ParseState beforeRecursing, ParseErrorReceiver err) { // Grow the seed instead of calling into it. GrowTheSeed gts = getGrowTheSeed(); Optional<ParseState> afterSeedOpt = parseSeed(beforeRecursing, err); if (!afterSeedOpt.isPresent()) { return Optional.absent(); } ParseState afterSeed = afterSeedOpt.get(); if (DEBUG) { System.err.println( indent() + "AfterSeed " + nodeType + "\n" + indent() + ". . input=`" + afterSeed.input.content.substring(afterSeed.index) + "`" + "\n" + indent() + ". . output=" + ImmutableList.copyOf(Chain.forward(afterSeed.output))); } ParseState afterSuffix = Repetition.parseRepeatedly( gts.suffix, afterSeed, err); if (DEBUG) { System.err.println(indent() + "LR passed"); } return Optional.of( afterSuffix.withOutput(rewriteLRMatchEvents(afterSuffix.output))); } private boolean hasLeftRecursion(ParseState state) { int nUnpushedPops = 0; boolean sawLookaheadMarker = false; for (Chain<? extends MatchEvent> o = state.output; o != null; o = o.prev) { if (o.x.nCharsConsumed() > 0) { break; } else if (o.x instanceof MatchEvent.PopMatchEvent) { ++nUnpushedPops; } else if (o.x instanceof MatchEvent.PushMatchEvent) { if (nUnpushedPops == 0) { MatchEvent.PushMatchEvent push = (PushMatchEvent) o.x; if (push.variant.getNodeType() == nodeType) { if (sawLookaheadMarker) { // Lookaheads should not be on a left-call-cycle. throw new IllegalStateException( "Left-recursion of " + nodeType + " ends up crossing lookahead boundary to " + push.variant); } return true; } } else { --nUnpushedPops; } } else if (o.x == Lookahead.LOOKAHEAD_START) { sawLookaheadMarker = true; } } return false; } private static Chain<MatchEvent> rewriteLRMatchEvents(Chain<MatchEvent> out) { List<MatchEvent> pushback = Lists.newArrayList(); List<MatchEvent> pops = Lists.newArrayList(); Chain<MatchEvent> withPushbackAndPops = doPushback(out, pushback, pops); for (MatchEvent pop : pops) { withPushbackAndPops = Chain.append(withPushbackAndPops, pop); } return withPushbackAndPops; } private static Chain<MatchEvent> doPushback( Chain<? extends MatchEvent> out, List<MatchEvent> pushback, List<MatchEvent> pops) { Preconditions.checkNotNull(out, "Did not find LRStart"); if (out.x instanceof MatchEvent.LRStart) { Chain<MatchEvent> withPushback = Chain.copyOf(out.prev); for (MatchEvent pb : pushback) { withPushback = Chain.append(withPushback, pb); } return withPushback; } else if (out.x instanceof MatchEvent.LRSuffix) { Chain<MatchEvent> processed = Chain.copyOf(out.prev); MatchEvent.LRSuffix suffix = (LRSuffix) out.x; for (NodeVariant nv : suffix.variants) { pushback.add(MatchEvent.push(nv)); } Chain<MatchEvent> withPushbackAndPops = doPushback( processed, pushback, pops); for (MatchEvent pop : pops) { withPushbackAndPops = Chain.append(withPushbackAndPops, pop); } pops.clear(); for (@SuppressWarnings("unused") NodeVariant nv : suffix.variants) { // Pop corresponding to pushback added above. pops.add(MatchEvent.pop()); } return withPushbackAndPops; } else { return Chain.append(doPushback(out.prev, pushback, pops), out.x); } } private GrowTheSeed getGrowTheSeed() { if (this.growTheSeed == null) { this.growTheSeed = GrowTheSeed.of(nodeType); } return this.growTheSeed; } @Override public Optional<SerialState> unparse( SerialState state, SerialErrorReceiver err) { return Alternation.of(variants).getParSer().unparse(state, err); } @Override public Optional<MatchState> match( MatchState state, MatchErrorReceiver err) { return Alternation.of(variants).getParSer().match(state, err); } @Override RangeSet<Integer> computeLookahead1() { if (variants.get(0).isLeftRecursive()) { GrowTheSeed gts = this.getGrowTheSeed(); // TODO: This is probably not sound. ParSer seed = gts.seed.getParSer(); if (seed != Alternation.NULL_LANGUAGE) { if (seed instanceof PTParSer) { return ((PTParSer) seed).getLookahead1(); } } } return ((PTParSer) (Alternation.of(variants).getParSer())) .getLookahead1(); } /** * Thrown to do a non-local transfer of control from where left-recursion is * detected to where it started. */ static final class LeftRecursionDone extends Error { private static final long serialVersionUID = 1L; final NodeType leftRecursiveNodeType; LeftRecursionDone(NodeType nt) { this.setStackTrace(new StackTraceElement[0]); this.leftRecursiveNodeType = nt; } @Override public String toString() { return getClass().getSimpleName() + "(" + leftRecursiveNodeType + ")"; } } }
package com.hazelcast.impl; import com.hazelcast.query.Expression; import java.util.*; public class Index<T> { final Map<Long, Set<T>> mapIndex; final String indexName; final Expression expression; final boolean ordered; public Index(String indexName, Expression expression, boolean ordered) { this.indexName = indexName; this.ordered = ordered; this.expression = expression; this.mapIndex = (ordered) ? new TreeMap<Long, Set<T>>() : new HashMap<Long, Set<T>>(1000); } public long extractLongValue(Object value) { return QueryService.getLongValue(expression.getValue(value)); } void addNewIndex(long value, T record) { Set<T> lsRecords = mapIndex.get(value); if (lsRecords == null) { lsRecords = new LinkedHashSet<T>(); mapIndex.put(value, lsRecords); } lsRecords.add(record); } void updateIndex(long oldValue, long newValue, T record) { if (oldValue == Long.MIN_VALUE) { addNewIndex(newValue, record); } else { if (oldValue != newValue) { removeIndex(oldValue, record); addNewIndex(newValue, record); } } } void removeIndex(long value, T record) { Set<T> lsRecords = mapIndex.get(value); if (lsRecords != null && lsRecords.size() > 0) { lsRecords.remove(record); if (lsRecords.size() == 0) { mapIndex.remove(value); } } } Set<T> getRecords(long value) { return mapIndex.get(value); } Set<T> getSubRecords(boolean equal, boolean lessThan, long value) { TreeMap<Long, Set<T>> treeMap = (TreeMap<Long, Set<T>>) mapIndex; Set<T> results = new HashSet<T>(); Map<Long, Set<T>> sub = (lessThan) ? treeMap.headMap(value) : treeMap.tailMap(value); Set<Map.Entry<Long, Set<T>>> entries = sub.entrySet(); for (Map.Entry<Long, Set<T>> entry : entries) { if (equal || entry.getKey() != value) { results.addAll(entry.getValue()); } } return results; } Set<T> getSubRecords(long from, long to) { TreeMap<Long, Set<T>> treeMap = (TreeMap<Long, Set<T>>) mapIndex; Set<T> results = new HashSet<T>(); Collection<Set<T>> sub = treeMap.subMap(from, to).values(); for (Set<T> records : sub) { results.addAll(records); } return results; } }
package com.rarchives.ripme.ui; import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.rarchives.ripme.utils.Utils; public class UpdateUtils { private static final Logger logger = Logger.getLogger(UpdateUtils.class); private static final String DEFAULT_VERSION = "1.7.69"; private static final String REPO_NAME = "ripmeapp/ripme"; private static final String updateJsonURL = "https://raw.githubusercontent.com/" + REPO_NAME + "/master/ripme.json"; private static final String mainFileName = "ripme.jar"; private static final String updateFileName = "ripme.jar.update"; private static JSONObject ripmeJson; private static String getUpdateJarURL(String latestVersion) { return "https://github.com/" + REPO_NAME + "/releases/download/" + latestVersion + "/ripme.jar"; } public static String getThisJarVersion() { String thisVersion = UpdateUtils.class.getPackage().getImplementationVersion(); if (thisVersion == null) { // Version is null if we're not running from the JAR thisVersion = DEFAULT_VERSION; // Super-high version number } return thisVersion; } private static String getChangeList(JSONObject rj) { JSONArray jsonChangeList = rj.getJSONArray("changeList"); StringBuilder changeList = new StringBuilder(); for (int i = 0; i < jsonChangeList.length(); i++) { String change = jsonChangeList.getString(i); if (change.startsWith(UpdateUtils.getThisJarVersion() + ":")) { break; } changeList.append("\n").append(change); } return changeList.toString(); } public static void updateProgramCLI() { logger.info("Checking for update..."); Document doc = null; try { logger.debug("Retrieving " + UpdateUtils.updateJsonURL); doc = Jsoup.connect(UpdateUtils.updateJsonURL) .timeout(10 * 1000) .ignoreContentType(true) .get(); } catch (IOException e) { logger.error("Error while fetching update: ", e); JOptionPane.showMessageDialog(null, "<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>", "RipMe Updater", JOptionPane.ERROR_MESSAGE); return; } finally { logger.info("Current version: " + getThisJarVersion()); } String jsonString = doc.body().html().replaceAll("&quot;", "\""); ripmeJson = new JSONObject(jsonString); String changeList = getChangeList(ripmeJson); logger.info("Change log: \n" + changeList); String latestVersion = ripmeJson.getString("latestVersion"); if (UpdateUtils.isNewerVersion(latestVersion)) { logger.info("Found newer version: " + latestVersion); logger.info("Downloading new version..."); logger.info("New version found, downloading..."); try { UpdateUtils.downloadJarAndLaunch(getUpdateJarURL(latestVersion), false); } catch (IOException e) { logger.error("Error while updating: ", e); } } else { logger.debug("This version (" + UpdateUtils.getThisJarVersion() + ") is the same or newer than the website's version (" + latestVersion + ")"); logger.info("v" + UpdateUtils.getThisJarVersion() + " is the latest version"); logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion()); } } public static void updateProgramGUI(JLabel configUpdateLabel) { configUpdateLabel.setText("Checking for update..."); Document doc = null; try { logger.debug("Retrieving " + UpdateUtils.updateJsonURL); doc = Jsoup.connect(UpdateUtils.updateJsonURL) .timeout(10 * 1000) .ignoreContentType(true) .get(); } catch (IOException e) { logger.error("Error while fetching update: ", e); JOptionPane.showMessageDialog(null, "<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>", "RipMe Updater", JOptionPane.ERROR_MESSAGE); return; } finally { configUpdateLabel.setText("Current version: " + getThisJarVersion()); } String jsonString = doc.body().html().replaceAll("&quot;", "\""); ripmeJson = new JSONObject(jsonString); String changeList = getChangeList(ripmeJson); String latestVersion = ripmeJson.getString("latestVersion"); if (UpdateUtils.isNewerVersion(latestVersion)) { logger.info("Found newer version: " + latestVersion); int result = JOptionPane.showConfirmDialog( null, String.format("<html><font color=\"green\">New version (%s) is available!</font>" + "<br><br>Recent changes: %s" + "<br><br>Do you want to download and run the newest version?</html>", latestVersion, changeList.replaceAll("\n", "")), "RipMe Updater", JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) { configUpdateLabel.setText("<html>Current Version: " + getThisJarVersion() + "<br><font color=\"green\">Latest version: " + latestVersion + "</font></html>"); return; } configUpdateLabel.setText("<html><font color=\"green\">Downloading new version...</font></html>"); logger.info("New version found, downloading..."); try { UpdateUtils.downloadJarAndLaunch(getUpdateJarURL(latestVersion), true); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error while updating: " + e.getMessage(), "RipMe Updater", JOptionPane.ERROR_MESSAGE); configUpdateLabel.setText(""); logger.error("Error while updating: ", e); } } else { logger.debug("This version (" + UpdateUtils.getThisJarVersion() + ") is the same or newer than the website's version (" + latestVersion + ")"); configUpdateLabel.setText("<html><font color=\"green\">v" + UpdateUtils.getThisJarVersion() + " is the latest version</font></html>"); logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion()); } } private static boolean isNewerVersion(String latestVersion) { // If we're testing the update utils we want the program to always try to update if (Utils.getConfigBoolean("testing.always_try_to_update", false)) { logger.info("isNewerVersion is returning true because the key \"testing.always_try_to_update\" is true"); return true; } int[] oldVersions = versionStringToInt(getThisJarVersion()); int[] newVersions = versionStringToInt(latestVersion); if (oldVersions.length < newVersions.length) { logger.error("Calculated: " + getThisJarVersion() + " < " + latestVersion); return true; } for (int i = 0; i < oldVersions.length; i++) { if (newVersions[i] > oldVersions[i]) { logger.debug("oldVersion " + getThisJarVersion() + " < latestVersion" + latestVersion); return true; } else if (newVersions[i] < oldVersions[i]) { logger.debug("oldVersion " + getThisJarVersion() + " > latestVersion " + latestVersion); return false; } } // At this point, the version numbers are exactly the same. // Assume any additional changes to the version text means a new version return !(latestVersion.equals(getThisJarVersion())); } private static int[] versionStringToInt(String version) { String strippedVersion = version.split("-")[0]; String[] strVersions = strippedVersion.split("\\."); int[] intVersions = new int[strVersions.length]; for (int i = 0; i < strVersions.length; i++) { intVersions[i] = Integer.parseInt(strVersions[i]); } return intVersions; } public static String createSha256(File file) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); InputStream fis = new FileInputStream(file); int n = 0; byte[] buffer = new byte[8192]; while (n != -1) { n = fis.read(buffer); if (n > 0) { digest.update(buffer, 0, n); } } byte[] hash = digest.digest(); StringBuilder sb = new StringBuilder(2 * hash.length); for (byte b : hash) { sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4)); sb.append("0123456789ABCDEF".charAt((b & 0x0F))); } // As patch.py writes the hash in lowercase this must return the has in lowercase return sb.toString().toLowerCase(); } catch (NoSuchAlgorithmException e) { logger.error("Got error getting file hash " + e.getMessage()); } catch (FileNotFoundException e) { logger.error("Could not find file: " + file.getName()); } catch (IOException e) { logger.error("Got error getting file hash " + e.getMessage()); } return null; } private static void downloadJarAndLaunch(String updateJarURL, Boolean shouldLaunch) throws IOException { Response response; response = Jsoup.connect(updateJarURL) .ignoreContentType(true) .timeout(Utils.getConfigInteger("download.timeout", 60 * 1000)) .maxBodySize(1024 * 1024 * 100) .execute(); try (FileOutputStream out = new FileOutputStream(updateFileName)) { out.write(response.bodyAsBytes()); } // Only check the hash if the user hasn't disabled hash checking if (Utils.getConfigBoolean("security.check_update_hash", true)) { String updateHash = createSha256(new File(updateFileName)); logger.info("Download of new version complete; saved to " + updateFileName); logger.info("Checking hash of update"); if (!ripmeJson.getString("currentHash").equals(updateHash)) { logger.error("Error: Update has bad hash"); logger.debug("Expected hash: " + ripmeJson.getString("currentHash")); logger.debug("Actual hash: " + updateHash); throw new IOException("Got bad file hash"); } else { logger.info("Hash is good"); } } if (shouldLaunch) { // Setup updater script final String batchFile, script; final String[] batchExec; String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { // Windows batchFile = "update_ripme.bat"; String batchPath = new File(batchFile).getAbsolutePath(); script = "@echo off\r\n" + "timeout 1" + "\r\n" + "copy " + updateFileName + " " + mainFileName + "\r\n" + "del " + updateFileName + "\r\n" + "ripme.jar" + "\r\n" + "del " + batchPath + "\r\n"; batchExec = new String[]{batchPath}; } else { // Mac / Linux batchFile = "update_ripme.sh"; String batchPath = new File(batchFile).getAbsolutePath(); script = "#!/bin/sh\n" + "sleep 1" + "\n" + "cd " + new File(mainFileName).getAbsoluteFile().getParent() + "\n" + "cp -f " + updateFileName + " " + mainFileName + "\n" + "rm -f " + updateFileName + "\n" + "java -jar \"" + new File(mainFileName).getAbsolutePath() + "\" &\n" + "sleep 1" + "\n" + "rm -f " + batchPath + "\n"; batchExec = new String[]{"sh", batchPath}; } // Create updater script try (BufferedWriter bw = new BufferedWriter(new FileWriter(batchFile))) { bw.write(script); bw.flush(); } logger.info("Saved update script to " + batchFile); // Run updater script on exit Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { logger.info("Executing: " + batchFile); Runtime.getRuntime().exec(batchExec); } catch (IOException e) { //TODO implement proper stack trace handling this is really just intented as a placeholder until you implement proper error handling e.printStackTrace(); } })); logger.info("Exiting older version, should execute update script (" + batchFile + ") during exit"); System.exit(0); } else { new File(mainFileName).delete(); new File(updateFileName).renameTo(new File(mainFileName)); } } }
package com.sandbox.runtime.config; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.sandbox.runtime.converters.HttpServletConverter; import com.sandbox.runtime.js.models.Console; import com.sandbox.runtime.js.services.JSEngineQueue; import com.sandbox.runtime.js.services.RuntimeService; import com.sandbox.runtime.js.utils.INashornUtils; import com.sandbox.runtime.js.utils.NashornRuntimeUtils; import com.sandbox.runtime.js.utils.NashornValidationUtils; import com.sandbox.runtime.models.Cache; import com.sandbox.runtime.models.SandboxScriptEngine; import com.sandbox.runtime.services.CommandLineProcessor; import com.sandbox.runtime.services.InMemoryCache; import com.sandbox.runtime.services.LiquidRenderer; import com.pivotal.cf.mobile.ats.json.ScriptObjectMirrorSerializer; import com.pivotal.cf.mobile.ats.json.ScriptObjectSerializer; import com.pivotal.cf.mobile.ats.json.UndefinedSerializer; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.core.env.SimpleCommandLinePropertySource; import javax.script.ScriptEngine; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathFactory; @Configuration @ComponentScan(basePackages = {"com.sandbox.runtime"}, excludeFilters = { @ComponentScan.Filter( Configuration.class ) } ) public class Context { @Autowired private ApplicationContext applicationContext; @Autowired private Environment environment; private static Logger logger = LoggerFactory.getLogger(Context.class); public static void main(String[] args) { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Context.class); context.getEnvironment().getPropertySources().addLast(new SimpleCommandLinePropertySource(args)); context.refresh(); context.start(); //process command line args and kick off CommandLineProcessor command = context.getBean(CommandLineProcessor.class); command.process(); }catch(Throwable e){ logger.error("Error starting runtime - " + unwrapException(e).getMessage()); System.exit(1); } } private static Throwable unwrapException(Throwable e){ if(e.getCause() != null) return unwrapException(e.getCause()); return e; } @Bean public ObjectMapper objectMapper(){ return getObjectMapper(); } public static ObjectMapper getObjectMapper(){ ObjectMapper mapper = new ObjectMapper(); SimpleModule nashornModule = new SimpleModule("nashornModule", new Version(1, 0, 0, null, null, null)); nashornModule.addSerializer(new ScriptObjectSerializer()); nashornModule.addSerializer(new ScriptObjectMirrorSerializer()); nashornModule.addSerializer(new UndefinedSerializer()); mapper.registerModule(nashornModule); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES); mapper.disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } @Bean @Scope("prototype") @Lazy public Console instanceConsole() { return new Console(); } @Bean(name = "nashornUtils") @Scope("prototype") @Lazy public NashornRuntimeUtils nashornUtils(String sandboxId) { return new NashornRuntimeUtils(sandboxId); } @Bean(name = "nashornValidationUtils") @Scope("prototype") @Lazy public INashornUtils nashornValidationUtils() { return new NashornValidationUtils(); } @Bean @Lazy public JSEngineQueue engineQueue(){ JSEngineQueue JSEngineQueue = new JSEngineQueue(50, applicationContext); JSEngineQueue.start(); return JSEngineQueue; } @Bean @Lazy public ScriptEngine scriptEngine() { NashornScriptEngineFactory engineFactory = applicationContext.getBean(NashornScriptEngineFactory.class); ScriptEngine engine = createScriptEngine(engineFactory); return engine; } public static ScriptEngine createScriptEngine(NashornScriptEngineFactory factory){ ScriptEngine engine = factory.getScriptEngine(new String[]{"--no-java"}); return engine; } @Bean @Scope("prototype") @Lazy public RuntimeService droneService() { SandboxScriptEngine engine = applicationContext.getBean(JSEngineQueue.class).get(); return new RuntimeService(engine); } @Bean public CommandLineProcessor getCommandLineProcessor() { return new CommandLineProcessor(); } @Bean @Lazy public Cache getCache(){ return new InMemoryCache(); } @Bean public HttpServletConverter httpServletConverter(){ return new HttpServletConverter(); } @Bean public NashornScriptEngineFactory nashornScriptEngineFactory(){ return new NashornScriptEngineFactory(); } //keep docuemnt factories around in thread local context private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); private static ThreadLocal<DocumentBuilder> documentBuilderThreadLocal = new ThreadLocal<>(); @Bean public static DocumentBuilder xmlDocumentBuilder() { documentBuilderFactory.setValidating(false); DocumentBuilder db = null; try { db = documentBuilderThreadLocal.get(); if(db == null){ db = documentBuilderFactory.newDocumentBuilder(); documentBuilderThreadLocal.set(db); }else{ db.reset(); } } catch (ParserConfigurationException e) { e.printStackTrace(); db = null; } return db; } //keep xpathfactories around in thread local context private static ThreadLocal<XPathFactory> xPathBuilderThreadLocal = new ThreadLocal<>(); @Bean public static XPathFactory xPathFactory() { XPathFactory xPathFactory = xPathBuilderThreadLocal.get(); if(xPathFactory == null){ xPathFactory = XPathFactory.newInstance(); xPathBuilderThreadLocal.set(xPathFactory); } return xPathFactory; } @Bean public LiquidRenderer liquidRenderer(){ return new LiquidRenderer(); } }
// @checkstyle HeaderCheck (1 line) package com.timepath.maven; import com.timepath.maven.model.Coordinate; import java.util.concurrent.TimeUnit; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.regex.Pattern; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; // @checkstyle JavadocTagsCheck (5 lines) /** * Centralised cache class. * * @author TimePath * @version $Id$ */ public final class PersistentCache { @NonNls private static final String CACHE_EXPIRES = "expires"; @NonNls private static final String CACHE_URL = "url"; private static final long META_LIFETIME = TimeUnit.DAYS.toMillis(7); private static final Preferences PREFERENCES = Preferences.userNodeForPackage(MavenResolver.class); private static final Pattern RE_COORD_SPLIT = Pattern.compile("[.:-]"); /** * Private ctor. */ private PersistentCache() { } /** * Drops all cached lookups. * * @throws java.util.prefs.BackingStoreException If something went wrong */ public static void drop() throws BackingStoreException { for (final String key : PREFERENCES.keys()) { PREFERENCES.remove(key); } for (final String child : PREFERENCES.childrenNames()) { PREFERENCES.node(child).removeNode(); } PREFERENCES.flush(); } /** * Check for cached coordinate. * * @param key The coordinate * @return The valid cached value, or null if expired * @checkstyle ReturnCountCheck (1 line) */ @Nullable public static String get(@NotNull final Coordinate key) { final Preferences cached = getNode(key); final boolean expired = System.currentTimeMillis() >= cached.getLong(CACHE_EXPIRES, 0); String ret = null; if (!expired) { ret = cached.get(CACHE_URL, null); } return ret; } /** * Save a URL to the persistent cache. * * @param key The key * @param url The URL */ public static void set(@NotNull final Coordinate key, @NotNull final String url) { final Preferences cachedNode = getNode(key); cachedNode.put(CACHE_URL, url); final long future = System.currentTimeMillis() + META_LIFETIME; cachedNode.putLong(CACHE_EXPIRES, future); try { cachedNode.flush(); // @checkstyle EmptyBlockCheck (1 line) } catch (final BackingStoreException ignored) { } } /** * Get the {@link java.util.prefs.Preferences} node for a coordinate. * * @param coordinate The maven coordinate * @return The node */ private static Preferences getNode(@NotNull final Coordinate coordinate) { Preferences cachedNode = PREFERENCES; for (final String nodeName : RE_COORD_SPLIT.split(coordinate.toString())) { cachedNode = cachedNode.node(nodeName); } return cachedNode; } }
package com.game.classes; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObjects; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.game.classes.network.Client.Client; import com.game.classes.pathing.aStarPathing; import com.game.classes.network.GameEvents; import com.game.classes.network.Server.Server; import java.util.ArrayList; import java.util.Random; public class Game { private ArrayList<Player> players; private Map map; private Chat chat; private Boolean inGame; private Client client; private Server server; private Player clientPlayer; private aStarPathing pathing; /** * The game. * Handles everything that happens in the game. * @param client Requires a client. */ public Game(Client client) { this.client = client; players = new ArrayList<Player>(); inGame = false; pathing = new aStarPathing(getMap()); } public Game(Server server){ this.server = server; //this.server.start(); players = new ArrayList<Player>(); inGame = false; pathing = new aStarPathing(getMap()); } /** * Gets all the players currently in the game. * @return Returns an array list of players. */ public ArrayList<Player> getPlayers() { return this.players; } public void setPlayers(ArrayList<Player> players){ this.players = players; } /** * Add a player to the game. * @param Player The player to add to the game. */ public void addPlayer(Player Player) { players.add(Player); } /** * Remove a player from the game. * @param player The player to remove from the game. */ public void removePlayer(Player player) { Player temp = player; for (Player current:players) { if(current.equals(player)) { temp = current; } } players.remove(temp); } /** * If a player needs to be removed without having a player object * @param name of the player to remove */ public void removePlayer(String name){ Player temp = null; for (Player current:players) { if(current.getName().equals(name)) { temp = current; } } if (temp == null){ return; } players.remove(temp); } /** * Gets the current map that the game is using. * @return A map object. */ public Map getMap() { return this.map; } /** * Sets the map that the game should use. * (cannot be used while the game is running.) * @param map The map the game should use. */ public void setMap(Map map) { this.map = map; } /** * Adds a chat to the game. * @param chat The chat that should be added to the game. */ public void setChat(Chat chat) { this.chat = chat; } /** * Get the chat that is added to the game. * @return The chat that is added to the game. */ public Chat getChat() { return this.chat; } /** * Checks whether the game is running. * @return True if the game is running, false if not. */ public boolean getInGame() { return inGame; } /** * Sets the status of the game. * @param inGame Set true if the game is running, false if not. */ public void setInGame(boolean inGame) { this.inGame = inGame; } /** * Get the connection with the server. * @return Returns a client object. */ public synchronized Client getClient() { return client; } /** * get the Hosting player of the game (client player) * @return Returns a Player Object Host */ public Player getClientPlayer() { return clientPlayer; } /** * * @param clientPlayer */ public void setClientPlayer(Player clientPlayer) { this.clientPlayer = clientPlayer; } public aStarPathing getPathing() { return pathing; } public boolean establishConnection(String name){ try { if (client.isConnected() == null) { client.start(); while (true) { Thread.sleep(10); if (client.isConnected() != null){ if (client.isConnected()){ break; } client.setConnected(null); return false; } } //TODO betere oplossing getClient().sendMessageSetName(name); getClient().sendMessageGetPlayers(); } } catch (InterruptedException e){ e.printStackTrace(); } return true; } /** * Generates characters for the clientplayer * @param name * @param manager */ public void generateCharacters(String name, AssetManager manager){ updateClientPlayer(); int enemy = 1; for (int i = 0; i < players.size(); i++){ if (players.get(i).getName() == clientPlayer.getName()){ enemy = i + 1; } } String textureFile; Character character; Texture texture; Sprite sprite; int[] ints = new Random().ints(0,60).distinct().limit(15).toArray(); for (int i = 0; i < 5; i ++){ int x = ints[i] % 20 + 10; int y = enemy == 1 ? ints[i] / 20 : ints[i] / 20 + 37; System.out.println(x + " "+ y); Terrain terrain = getMap().getTerrains()[x][y]; switch (i){ case 1: textureFile = "Sprites/bowman-" + enemy + ".png"; texture = manager.get(textureFile, Texture.class); sprite = new Sprite(texture); character = new Character("Bowman", 8, 4, 0, 6, 3, sprite, terrain,textureFile,clientPlayer); break; case 2: textureFile = "Sprites/heavy-" + enemy + ".png"; texture = manager.get(textureFile, Texture.class); sprite = new Sprite(texture); character = new Character("Heavy Dude", 10, 3, 2, 4, 1, sprite, terrain,textureFile,clientPlayer); break; case 3: textureFile = "Sprites/horseman-" + enemy + ".png"; texture = manager.get(textureFile, Texture.class); sprite = new Sprite(texture); character = new Character("Man with donkey", 8, 4, 0, 10, 1, sprite, terrain,textureFile,clientPlayer); break; case 4: textureFile = "Sprites/wizard-" + enemy + ".png"; texture = manager.get(textureFile, Texture.class); sprite = new Sprite(texture); character = new Character("Merrrlijn", 7, 5, 0, 5, 2, sprite, terrain,textureFile,clientPlayer); break; default: textureFile = "Sprites/swordsman-" + enemy + ".png"; texture = manager.get(textureFile, Texture.class); sprite = new Sprite(texture); character = new Character("Zwaardvechter", 10, 4, 1, 6, 1, sprite, terrain,textureFile,clientPlayer); break; } clientPlayer.addCharacter(character); } if (client.isConnected() == null) return; getClient().sendGameMessagePlayer(clientPlayer); } public void loadMap(String fileName){ //TODO zet deel in map class TiledMap tiledMap = new TmxMapLoader().load(fileName); TiledMapTileLayer tileLayer = (TiledMapTileLayer)tiledMap.getLayers().get(0); int tileWidth = tiledMap.getProperties().get("tilewidth", Integer.class); int tileHeight = tiledMap.getProperties().get("tileheight", Integer.class); // Add objects MapLayer mapLayer = tiledMap.getLayers().get("Impassable Terrain"); MapObjects mapObjects = mapLayer.getObjects(); ArrayList<RectangleMapObject> mapObjectList = new ArrayList<RectangleMapObject>(); for (int i = 0; i < mapObjects.getCount(); i++){ RectangleMapObject rmo = (RectangleMapObject) mapObjects.get(i); rmo.getRectangle().setX((rmo.getRectangle().x ) / tileWidth ); rmo.getRectangle().setY((rmo.getRectangle().y ) / tileHeight); mapObjectList.add(rmo); } map = new Map(tileLayer.getWidth(), tileLayer.getHeight(), tileHeight, tileWidth, mapObjectList); map.setTiledMap(tiledMap); if (getClient().isConnected() != null){ getClient().sendGameMap(map); } } /** * Sends a message to the server to send everyone new players */ public void updatePlayers(){ updateClientPlayer(); getClient().sendGameMessagePlayer(clientPlayer); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } getClient().sendMessageGetPlayers(); } /** * Sends an end turn message to the server */ public void endTurn(){ updateClientPlayer(); for (Player player : getPlayers()){ getClient().sendGameMessagePlayer(player); try { Thread.sleep(100); // Server crashes if it gets too many messages... } catch (InterruptedException e) { e.printStackTrace(); } } getClient().sendGameEndTurn(); } public void endTurnLocal() { clientPlayer.setHasTurn(true); for (Character character : clientPlayer.getCharacters()) { character.setCurrentMovementPoints(character.getMovementPoints()); character.setHasAttacked(false); } } public boolean characterAttack(Character attacker, Character defender){ if (defender == null) return false; if (!attacker.hasAttacked() && attacker.canAttack(defender.getCurrentTerrain())){ defender.takeDamage(attacker.getAttackPoints()); attacker.setHasAttacked(true); if (defender.isDead()){ defender.getCurrentTerrain().setCharacter(null); } return true; } return false; } public boolean moveCharacter(Character character, Terrain tile, Terrain oldTile){ if (tile.getY() == oldTile.getY() && tile.getX() == oldTile.getX()){ return false; } else { pathing.findPath(oldTile, tile); } if (pathing.getPath().size() > character.getMovementPoints()){ return false; } if (character.setCurrentTerrain(tile, pathing.getPath().size())){ map.getTerrains() [oldTile.getX()] [oldTile.getY()].setCharacter(null); tile.setCharacter(character); if (client.isConnected() != null){ client.sendCharacterMove( tile.getX(), tile.getY(), character.getName(), character.getPlayer().getName()); } return true; } return false; } public void forceMoveCharacter(int x, int y, String charName, String playerName){ for (Player player : players) { if (player.getName().equals(playerName)){ for (Character character : player.getCharacters()) { if (character.getName().equals(charName)){ character.forceSetCurrentTerrain(map.getTerrains()[x][y]); } } } } } public void addGameListener(GameEvents listener){ client.addGameListener(listener); } public Player checkTurn(ArrayList<Player> players){ for (Player player:players) { if (clientPlayer.getName().equals(player.getName())){ clientPlayer = player; } if (player.hasTurn()){ return player; } } return null; } public int getTotalCharacters(){ int count = 0; for (Player player : players) { for (Character character : player.getCharacters()) { if (!character.isDead()){ count++; } } } return count; } private void updateClientPlayer(){ for (Player player:getPlayers()) { if (clientPlayer.getName().equals(player.getName())){ clientPlayer = player; } } } }
package com.yahoo.wildwest.jnih; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.yahoo.example.test.DumpTest; /** * Given an SIMPLE object on the classpath Generate all of the stub code to copy it into a long/long (address, length) * combo that can be passed to jni and the static c function to decode it. * * @author areese * */ public class ObjectJniH { static final String GET_LONG_VALUE_STRING = "MUnsafe.unsafe.getLong(address + offset);"; static final String FOUR_SPACE_TAB = " "; private final Set<String> blacklistedMethods = generateBlackList(); private final Class<?> objectClass; private final String objectClassName; private final String shortObjectName; public ObjectJniH(Class<?> objectClass) { this.objectClass = objectClass; this.objectClassName = this.objectClass.getName(); String[] temp = objectClassName.split("\\."); this.shortObjectName = temp[temp.length - 1]; } private static Set<String> generateBlackList() { Set<String> blacklistedMethods = new HashSet<>(); for (Method m : Object.class.getMethods()) { blacklistedMethods.add(m.getName()); } for (Method m : Class.class.getMethods()) { blacklistedMethods.add(m.getName()); } return blacklistedMethods; } boolean isBlacklisted(String methodName, Class<?> returnType, AccessorType methodType) { if (blacklistedMethods.contains(methodName)) { System.err.println(methodName + " is from Object"); return true; } if (returnType.isPrimitive() && returnType.equals(Void.TYPE)) { System.err.println(methodName + " returns void"); return true; } if (null != methodType) { return methodType.isBlacklisted(methodName); } return false; } public List<Method> findGetters() { // first we need to find all of it's fields, since we're generating code. // I'm only looking for getters. If you don't have getters, it won't be written. List<Method> getters = new LinkedList<>(); for (Method m : objectClass.getMethods()) { String methodName = m.getName(); if (isBlacklisted(methodName, m.getReturnType(), AccessorType.GETTER)) { continue; } System.out.println("added " + methodName); getters.add(m); } return getters; } public List<Method> findSetters() { // first we need to find all of it's fields, since we're generating code. // I'm only looking for getters. If you don't have getters, it won't be written. List<Method> setters = new LinkedList<>(); for (Method m : objectClass.getMethods()) { String methodName = m.getName(); if (isBlacklisted(methodName, m.getReturnType(), AccessorType.SETTER)) { continue; } System.out.println("added " + methodName); setters.add(m); } return setters; } public String createCStruct() { // first we need to find all of it's fields, since we're generating code. // I'm only looking for getters. If you don't have getters, it won't be written. // List<Field> fields = new LinkedList<>(); StringBuilder structString = new StringBuilder(); String structName = shortObjectName + "Struct"; structString.append("typedef struct " + structName + " {\n"); parseObject(objectClass, (ctype, field, type) -> { switch (ctype) { case STRING: structString.append(FOUR_SPACE_TAB + "uint64_t " + field.getName() + "Bytes;\n"); structString.append(FOUR_SPACE_TAB + "uint64_t " + field.getName() + "Len;\n"); break; case LONG: case INT: // yes we waste 32 bits. case BYTE: // yes we waste 56 bits. structString.append(FOUR_SPACE_TAB + "uint64_t " + field.getName() + "; // " + type.getName() + "\n"); break; default: structString.append(FOUR_SPACE_TAB + "DATASTRUCT " + field.getName() + "; // " + type.getName() + "\n"); break; } // System.out.println("field " + ctype + " " + fieldName + " " + f.isAccessible()); // fields.add(f); }); structString.append("} " + structName + ";\n"); return structString.toString(); // return fields; } public String createJavaCodeBlock() throws IOException { try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { pw.println("public " + objectClassName + " create" + shortObjectName + "(long address, long len) {"); setupJavaVariablesBlock(pw); createBitSpitter(pw); createConstructorInvocation(pw); pw.println("}"); return sw.toString(); } } private void setupJavaVariablesBlock(PrintWriter pw) { // first we need to find all of it's fields, since we're generating code. // I'm only looking for getters. If you don't have getters, it won't be written. // List<Field> fields = new LinkedList<>(); parseObject(objectClass, (ctype, field, type) -> { switch (ctype) { case STRING: pw.println(FOUR_SPACE_TAB + "// TOOD: support String"); pw.println(FOUR_SPACE_TAB + "long " + field.getName() + "Len;"); pw.println(FOUR_SPACE_TAB + "byte[] " + field.getName() + "Bytes;"); // = new byte["+ field.getName() + "Len];\n"); pw.println(FOUR_SPACE_TAB + "String " + field.getName() + ";"); // pw.println(" = new String(" + field.getName() // + "Bytes, StandardCharsets.UTF_8);\n"); break; case LONG: pw.println(FOUR_SPACE_TAB + "long " + field.getName() + "; // " + type.getName()); break; case INT: pw.println(FOUR_SPACE_TAB + "int " + field.getName() + "; // " + type.getName()); break; case BYTE: pw.println(FOUR_SPACE_TAB + "byte " + field.getName() + "; // " + type.getName()); break; default: pw.println(FOUR_SPACE_TAB + "// TOOD: support " + type.getName()); break; } }); pw.println(); } private void createConstructorInvocation(PrintWriter pw) { StringBuilder constructorString = new StringBuilder(); // really shouldn't name things so terribly constructorString.append(FOUR_SPACE_TAB + objectClassName + " newObject = new " + objectClassName + "("); constructorString.append("\n"); String trailer = ", parseObject(objectClass, (ctype, field, type) -> { // how many bytes do we skip? Strings are long,long so 16, everything else is 8 byte longs until we stop // wasting bits. constructorString.append(FOUR_SPACE_TAB + FOUR_SPACE_TAB + field.getName()).append(trailer); }); // remove the extra comma int index = constructorString.lastIndexOf(","); if (-1 != index) { constructorString.delete(index, constructorString.length()); } constructorString.append(");\n"); pw.println(constructorString.toString()); pw.println(FOUR_SPACE_TAB + "return newObject;"); } private void createBitSpitter(PrintWriter pw) { // assume address, len pw.println("long offset = 0;"); // how many bytes do we skip? Strings are long,long so 16, everything else is 8 byte longs until we stop // wasting bits. parseObject(objectClass, (ctype, field, type) -> { String fieldName = field.getName(); int offsetBy = 0; switch (ctype) { case STRING: offsetBy = 8; pw.println(FOUR_SPACE_TAB + fieldName + "Bytes = " + GET_LONG_VALUE_STRING); pw.println(FOUR_SPACE_TAB + "offset += " + offsetBy + "; // just read " + fieldName + " type " + type.getName()); pw.println(); pw.println(FOUR_SPACE_TAB + fieldName + "Len = " + GET_LONG_VALUE_STRING); pw.println(FOUR_SPACE_TAB + "offset += " + offsetBy + "; // just read " + fieldName + " type " + type.getName()); pw.println(); pw.println(FOUR_SPACE_TAB + "if (null != " + fieldName + "Bytes && null != " + fieldName + "Len) {"); pw.println(FOUR_SPACE_TAB + FOUR_SPACE_TAB + fieldName + " = new String(" + fieldName + "Bytes, 0, " + fieldName + "Len, StandardCharsets.UTF_8);"); pw.println(FOUR_SPACE_TAB + "} else {"); pw.println(FOUR_SPACE_TAB + FOUR_SPACE_TAB + fieldName + " = null;"); pw.println(FOUR_SPACE_TAB + "}"); pw.println(); break; case LONG: offsetBy = 8; pw.println(FOUR_SPACE_TAB + fieldName + " = " + GET_LONG_VALUE_STRING); pw.println(FOUR_SPACE_TAB + "offset += " + offsetBy + "; // just read " + fieldName + " type " + type.getName()); break; case INT: offsetBy = 8; pw.println(FOUR_SPACE_TAB + fieldName + " = (int)" + GET_LONG_VALUE_STRING); pw.println("offset += " + offsetBy + "; // just read " + fieldName + " type " + type.getName()); break; case BYTE: offsetBy = 8; pw.println(FOUR_SPACE_TAB + fieldName + " = (byte)" + GET_LONG_VALUE_STRING); pw.println(FOUR_SPACE_TAB + "offset += " + offsetBy + "; // just read " + fieldName + " type " + type.getName()); break; } pw.println(); // System.out.println("field " + ctype + " " + fieldName + " " + f.isAccessible()); // fields.add(f); }); pw.println(); } /** * Helper function to walk the fields of a class and write out either jni or java wrapper bits we'll need. * * @param objectClass Class to operate on, expects primitives + strings, no arrays * @param pt lambda to invoke on each field that is a primitive or string. */ public static void parseObject(Class<?> objectClass, ProcessType pt) { for (Field field : objectClass.getDeclaredFields()) { Class<?> type = field.getType(); if (!type.isPrimitive() && !type.isInstance("") || type.isArray()) { continue; } CTYPES ctype = CTYPES.getCType(type); pt.process(ctype, field, type); } } public static void main(String[] args) throws Exception { Class<?> classToDump; boolean generateCCode = false; boolean generateJavaCode = false; if (args.length > 0) { classToDump = Class.forName(args[0]); } else { classToDump = new DumpTest().getClass(); } if (args.length > 1) { if ("-cstruct".equals(args[1])) { generateCCode = true; } if ("-java".equals(args[1])) { generateJavaCode = true; } } ObjectJniH ojh = new ObjectJniH(classToDump); if (generateCCode) { // create the c struct String cstructString = ojh.createCCodeBlock(); System.out.println(cstructString); } if (generateJavaCode) { String javaString = ojh.createJavaCodeBlock(); System.out.println(javaString); } // create the java read code, we can use the setters we've found // some people take constructors. // we can do that by making either: // a) a list of getLongs() // b) a list of longs assigned from getLong } private String createCCodeBlock() { // TODO Auto-generated method stub return null; } }
package de.ddb.pdc.metadata; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; @JsonIgnoreProperties(ignoreUnknown = true) class EntitiesResult { @JsonProperty private ArrayList<EntitiesResultList> results; public EntitiesResultItem getResultItem() { if (results == null || results.size() == 0 || results.get(0).getDocs().size() == 0) { return null; } else { return results.get(0).getDocs().get(0); } } }
package de.ids_mannheim.korap.web; import com.sun.grizzly.http.embed.GrizzlyWebServer; import com.sun.grizzly.http.servlet.ServletAdapter; import com.sun.jersey.spi.container.servlet.ServletContainer; import de.ids_mannheim.korap.config.BeanConfiguration; import de.ids_mannheim.korap.utils.KorAPLogger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author hanl * @date 01/06/2015 */ public class Kustvakt { private static Integer PORT = -1; private static String CONFIG = null; public static void main(String[] args) throws Exception { attributes(args); BeanConfiguration.loadClasspathContext(); if (CONFIG != null) { BeanConfiguration.getConfiguration() .setPropertiesAsStream(new FileInputStream(new File(CONFIG))); } grizzlyServer(PORT); } public static void grizzlyServer(int port) throws IOException { if (port == -1) port = BeanConfiguration.getConfiguration().getPort(); System.out.println("Starting grizzly on port " + port + " ..."); GrizzlyWebServer gws = new GrizzlyWebServer(port); ServletAdapter jerseyAdapter = new ServletAdapter(); jerseyAdapter .addInitParameter("com.sun.jersey.config.property.packages", "de.ids_mannheim.korap.web.service"); jerseyAdapter.setContextPath("/api"); jerseyAdapter.setServletInstance(new ServletContainer()); gws.addGrizzlyAdapter(jerseyAdapter, new String[] { "/api" }); gws.start(); } private static void attributes(String[] args) { for (int i = 0; i < args.length; i++) { switch ((args[i])) { case "--debug": KorAPLogger.DEBUG = true; break; case "--config": CONFIG = args[i + 1]; break; case "--port": PORT = Integer.valueOf(args[i + 1]); break; } } } }
package de.otto.flummi.query; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.util.List; import static de.otto.flummi.request.GsonHelper.object; import static java.util.Arrays.asList; public class QueryBuilders { public static QueryBuilder matchAll() { return () -> { JsonObject query = new JsonObject(); query.add("match_all", new JsonObject()); return query; }; } public static QueryBuilder filteredQuery(QueryBuilder query, JsonObject filter) { return () -> { JsonObject outerQuery = new JsonObject(); JsonObject filtered = new JsonObject(); outerQuery.add("filtered", filtered); filtered.add("query", query.build()); filtered.add("filter", filter); return outerQuery; }; } public static TermsQueryBuilder termsQuery(String name, String... values) { return new TermsQueryBuilder(name, asList(values)); } public static TermsQueryBuilder termsQuery(String name, List<String> values) { return new TermsQueryBuilder(name, values); } public static TermQueryBuilder termQuery(String name, String value) { return new TermQueryBuilder(name, new JsonPrimitive(value)); } public static TermQueryBuilder termQuery(String name, Boolean value) { return new TermQueryBuilder(name, new JsonPrimitive(value)); } public static TermQueryBuilder termQuery(String name, Number value) { return new TermQueryBuilder(name, new JsonPrimitive(value)); } public static WildcardQueryBuilder wildcardQuery(String name, String value) { return wildcardQuery(name, new JsonPrimitive(value)); } public static WildcardQueryBuilder wildcardQuery(String name, JsonElement value) { return new WildcardQueryBuilder(name, value); } public static RegexpQueryBuilder regexpQuery(String name, String value) { return regexpQuery(name, new JsonPrimitive(value)); } public static RegexpQueryBuilder regexpQuery(String name, JsonElement value) { return new RegexpQueryBuilder(name, value); } public static BoolQueryBuilder bool() { return new BoolQueryBuilder(); } public static QueryBuilder notQuery(QueryBuilder nestedFilter) { return () -> object("not", nestedFilter.build()); } public static QueryBuilder nestedQuery(String path, QueryBuilder queryBuilder) { return () -> { JsonObject jsonObject = new JsonObject(); JsonObject nested = new JsonObject(); nested.add("filter", queryBuilder.build()); nested.add("path", new JsonPrimitive(path)); jsonObject.add("nested", nested); return jsonObject; }; } public static QueryBuilder prefixFilter(String name, String prefix) { return () -> { JsonObject jsonObject = new JsonObject(); JsonObject value = new JsonObject(); value.add(name, new JsonPrimitive(prefix)); jsonObject.add("prefix", value); return jsonObject; }; } public static JsonObject existsFilter(String fieldName) { JsonObject jsonObject = new JsonObject(); JsonObject existsObject = new JsonObject(); jsonObject.add("exists", existsObject); existsObject.add("field", new JsonPrimitive(fieldName)); return jsonObject; } public static AndQueryBuilder andQuery(QueryBuilder... queries) { return new AndQueryBuilder(queries); } public static AndQueryBuilder andQuery(List<QueryBuilder> queries) { return new AndQueryBuilder(queries); } public static NumberRangeQueryBuilder numberRangeFilter(String fieldName) { return new NumberRangeQueryBuilder(fieldName); } public static DateRangeQueryBuilder dateRangeFilter(String fieldName) { return new DateRangeQueryBuilder(fieldName); } public static HasParentQueryBuilder hasParent(String type, QueryBuilder query) { return new HasParentQueryBuilder(type, query); } public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder innerQuery) { return new FunctionScoreQueryBuilder(innerQuery); } }
package de.predic8.routes; import de.predic8.util.AttachLogfile; import de.predic8.util.PropertyFile; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Predicate; import org.apache.camel.builder.PredicateBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; public class HashNotification extends RouteBuilder { private String fileName = ""; public HashNotification() { super(); } public HashNotification(String fileName) { this.fileName = fileName; } @Override public void configure() throws Exception { Endpoint smtp = getContext().getEndpoint( String.format("smtp://%s?password=%s&username=%s&to=%s&from=%s" , PropertyFile.getInstance().getProperty("email_smtp") , PropertyFile.getInstance().getProperty("email_password") , PropertyFile.getInstance().getProperty("email_username") , PropertyFile.getInstance().getProperty("email_recipient") , PropertyFile.getInstance().getProperty("email_username"))); from("file:document-archive/logs?fileName=log.txt&noop=true") .choice() .when(method(HashNotification.class, "error")) .log("SENDING HASH ERROR MAIL") .setHeader("subject", simple("Hash Error Detected")) .setHeader("firstName", simple(PropertyFile.getInstance().getProperty("user_name"))) .setBody(simple(fileName)) .to("freemarker:/email-templates/verify_fail.ftl") .otherwise() .log("SENDING EVERYTHING OK MAIL") .setHeader("subject", simple("Everything OK!")) .setHeader("firstName", simple(PropertyFile.getInstance().getProperty("user_name"))) .setBody(simple("No files in your document archive have been changed")) .to("freemarker:/email-templates/verify_ok.ftl") .end() .process(new AttachLogfile()) .to(smtp) .log("HASH MAIL SEND"); } public boolean error(Object body) { return !fileName.equals(""); } public void start(String fileName) throws Exception { CamelContext ctx = new DefaultCamelContext(); ctx.addRoutes(new HashNotification(fileName)); ctx.start(); Thread.sleep(5000); } public void start() throws Exception { this.start(null); } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.AuthenticationProvider; import edu.harvard.iq.dataverse.authorization.AuthenticationProviderDisplayInfo; import edu.harvard.iq.dataverse.authorization.AuthenticationRequest; import edu.harvard.iq.dataverse.authorization.AuthenticationResponse; import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean; import edu.harvard.iq.dataverse.authorization.CredentialsAuthenticationProvider; import edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException; import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUserServiceBean; import edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.util.BundleUtil; import edu.harvard.iq.dataverse.util.JsfHelper; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.validator.ValidatorException; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author xyang * @author Michael Bar-Sinai */ @ViewScoped @Named("LoginPage") public class LoginPage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(LoginPage.class.getName()); public static class FilledCredential { CredentialsAuthenticationProvider.Credential credential; String value; public FilledCredential() { } public FilledCredential(CredentialsAuthenticationProvider.Credential credential, String value) { this.credential = credential; this.value = value; } public CredentialsAuthenticationProvider.Credential getCredential() { return credential; } public void setCredential(CredentialsAuthenticationProvider.Credential credential) { this.credential = credential; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public enum EditMode {LOGIN, SUCCESS, FAILED}; @Inject DataverseSession session; @EJB DataverseServiceBean dataverseService; @EJB BuiltinUserServiceBean dataverseUserService; @EJB UserServiceBean userService; @EJB AuthenticationServiceBean authSvc; @EJB SettingsServiceBean settingsService; @EJB SystemConfig systemConfig; @Inject DataverseRequestServiceBean dvRequestService; private String credentialsAuthProviderId; private List<FilledCredential> filledCredentials; private String redirectPage = "dataverse.xhtml"; private AuthenticationProvider authProvider; private int numFailedLoginAttempts; Random random; long op1; long op2; Long userSum; public void init() { Iterator<String> credentialsIterator = authSvc.getAuthenticationProviderIdsOfType( CredentialsAuthenticationProvider.class ).iterator(); if ( credentialsIterator.hasNext() ) { setCredentialsAuthProviderId(credentialsIterator.next()); } resetFilledCredentials(null); authProvider = authSvc.getAuthenticationProvider(systemConfig.getDefaultAuthProvider()); random = new Random(); } public List<AuthenticationProviderDisplayInfo> listCredentialsAuthenticationProviders() { List<AuthenticationProviderDisplayInfo> infos = new LinkedList<>(); for ( String id : authSvc.getAuthenticationProviderIdsOfType( CredentialsAuthenticationProvider.class ) ) { AuthenticationProvider authenticationProvider = authSvc.getAuthenticationProvider(id); infos.add( authenticationProvider.getInfo()); } return infos; } public List<AuthenticationProviderDisplayInfo> listAuthenticationProviders() { List<AuthenticationProviderDisplayInfo> infos = new LinkedList<>(); for (String id : authSvc.getAuthenticationProviderIdsSorted()) { AuthenticationProvider authenticationProvider = authSvc.getAuthenticationProvider(id); if (authenticationProvider != null) { if (ShibAuthenticationProvider.PROVIDER_ID.equals(authenticationProvider.getId())) { infos.add(authenticationProvider.getInfo()); } else { infos.add(authenticationProvider.getInfo()); } } } return infos; } public CredentialsAuthenticationProvider selectedCredentialsProvider() { return (CredentialsAuthenticationProvider) authSvc.getAuthenticationProvider(getCredentialsAuthProviderId()); } public boolean validatePassword(String username, String password) { return false; } public String login() throws Exception { AuthenticationRequest authReq = new AuthenticationRequest(); List<FilledCredential> filledCredentialsList = getFilledCredentials(); if ( filledCredentialsList == null ) { logger.info("Credential list is null!"); return null; } for ( FilledCredential fc : filledCredentialsList ) { if(fc.getValue()==null || fc.getValue().isEmpty()){ JH.addMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("login."+fc.getCredential().getKey())); } authReq.putCredential(fc.getCredential().getKey(), fc.getValue()); } authReq.setIpAddress( dvRequestService.getDataverseRequest().getSourceAddress() ); try { AuthenticatedUser r = authSvc.getUpdateAuthenticatedUser(credentialsAuthProviderId, authReq); logger.log(Level.FINE, "User authenticated: {0}", r.getEmail()); session.setUser(r); String affiliation = r.getAffiliation(); logger.log(Level.FINE, "affiliation: {0}", affiliation); String alias = ""; String json_url = null; String dataverseSiteUrl = SystemConfig.getDataverseSiteUrlStatic(); if (dataverseSiteUrl.contains("localhost")) { json_url = "http://localhost:8080/affiliation"; } else { json_url = dataverseSiteUrl+"/affiliation"; } System.out.println("edu.harvard.iq.dataverse.LoginPage.login(): json_url = "+json_url); logger.log(Level.FINE, "calling readUrl: {0}", json_url); JSONObject json_obj; try { json_obj = new JSONObject("{ \"affiliates\":" + readUrl(json_url) + "}"); //note the saved affiliation is the "title" of the affiliates.json file JSONArray json_array = json_obj.getJSONArray("affiliates"); for (int i = 0; i < json_array.length(); i++) { String[] array = json_array.getJSONArray(i).toString().split(","); String title = array[2].replace("\"", ""); if (title.equals(affiliation)) { alias = array[1].replace("\"", ""); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(affiliation + " Redirect to " + alias + " " + redirectPage); //redirect to the alias if there is one and the user came from the homepage if (!alias.equals("") && (redirectPage.contains("dataverse.xhtml") || redirectPage.contains("dataverseuser.xhtml"))) { redirectPage = "%2Fdataverse.xhtml%3Falias%3D" + alias; logger.log(Level.FINE, "redirect to affiliate dataverse", redirectPage); } if ("dataverse.xhtml".equals(redirectPage)) { redirectPage = redirectToRoot(); } try { redirectPage = URLDecoder.decode(redirectPage, "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex); redirectPage = redirectToRoot(); } logger.log(Level.FINE, "Sending user to = {0}", redirectPage); return redirectPage + (!redirectPage.contains("?") ? "?" : "&") + "faces-redirect=true"; } catch (AuthenticationFailedException ex) { numFailedLoginAttempts++; op1 = new Long(random.nextInt(10)); op2 = new Long(random.nextInt(10)); AuthenticationResponse response = ex.getResponse(); switch ( response.getStatus() ) { case FAIL: JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("login.builtin.invalidUsernameEmailOrPassword")); return null; case ERROR: JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("login.error")); logger.log( Level.WARNING, "Error logging in: " + response.getMessage(), response.getError() ); return null; case BREAKOUT: return response.getMessage(); default: JsfHelper.addErrorMessage("INTERNAL ERROR"); return null; } } } private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } } private String redirectToRoot(){ return "dataverse.xhtml?alias=" + dataverseService.findRootDataverse().getAlias(); } public String getCredentialsAuthProviderId() { return credentialsAuthProviderId; } public void resetFilledCredentials( AjaxBehaviorEvent event) { if ( selectedCredentialsProvider()==null ) return; filledCredentials = new LinkedList<>(); for ( CredentialsAuthenticationProvider.Credential c : selectedCredentialsProvider().getRequiredCredentials() ) { filledCredentials.add( new FilledCredential(c, "")); } } public void setCredentialsAuthProviderId(String authProviderId) { this.credentialsAuthProviderId = authProviderId; } public List<FilledCredential> getFilledCredentials() { return filledCredentials; } public void setFilledCredentials(List<FilledCredential> filledCredentials) { this.filledCredentials = filledCredentials; } public boolean isMultipleProvidersAvailable() { return authSvc.getAuthenticationProviderIds().size()>1; } public String getRedirectPage() { return redirectPage; } public void setRedirectPage(String redirectPage) { this.redirectPage = redirectPage; } public AuthenticationProvider getAuthProvider() { return authProvider; } public void setAuthProviderById(String authProviderId) { logger.fine("Setting auth provider to " + authProviderId); this.authProvider = authSvc.getAuthenticationProvider(authProviderId); } public String getLoginButtonText() { if (authProvider != null) { // Note that for ORCID we do not want the normal "Log In with..." text. There is special logic in the xhtml. return BundleUtil.getStringFromBundle("login.button", Arrays.asList(authProvider.getInfo().getTitle())); } else { return BundleUtil.getStringFromBundle("login.button", Arrays.asList("???")); } } public int getNumFailedLoginAttempts() { return numFailedLoginAttempts; } public boolean isRequireExtraValidation() { if (numFailedLoginAttempts > 2) { return true; } else { return false; } } public long getOp1() { return op1; } public long getOp2() { return op2; } public Long getUserSum() { return userSum; } public void setUserSum(Long userSum) { this.userSum = userSum; } // TODO: Consolidate with SendFeedbackDialog.validateUserSum? public void validateUserSum(FacesContext context, UIComponent component, Object value) throws ValidatorException { // The FacesMessage text is on the xhtml side. FacesMessage msg = new FacesMessage(""); ValidatorException validatorException = new ValidatorException(msg); if (value == null) { throw validatorException; } if (op1 + op2 != (Long) value) { throw validatorException; } } }
package frc.team4215.stronghold; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.Timer; /** * The class for Autonomous. * * @author James */ public class Autonomous { private Victor frontLeft, frontRight, backLeft, backRight, armMotor, intake; private Interface choiceAuto; public Autonomous(Victor frontLeft_, Victor frontRight_, Victor backLeft_, Victor backRight_, Victor armMotor_, Victor intake_) throws RobotException { this(new Victor[] { frontLeft_, frontRight_, backLeft_, backRight_, armMotor_, intake_ }); } public Autonomous(Victor[] sixVictors) throws RobotException { if (sixVictors.length < 6) throw new RobotException( "Victor array's length is less than 6"); // Point to the other constructor. Victor[] a = sixVictors; // a nickname this.frontLeft = a[0]; this.frontRight = a[1]; this.backLeft = a[2]; this.backRight = a[3]; this.armMotor = a[4]; this.intake = a[5]; } public void chooseAuto(int num) { if (num == 1) this.choiceAuto = () -> this.autoLowBar(); else if (num == 2) this.choiceAuto = () -> this.autoSpyBotLowGoal(); else if (num == 3) this.choiceAuto = () -> this.autoChevalDeFrise(); else if (num == 4) this.choiceAuto = () -> this.autoPortcullis(); else this.choiceAuto = null; } public void autoChoice() throws RobotException { if (null != this.choiceAuto) throw new RobotException("There is not a method chosen."); this.choiceAuto.runAuto(); } /* working variables */ long lastTime; double Input, Output, Setpoint; double errSum, lastErr; double kp, ki, kd; /** * PID controller * * @author Jack Rausch */ public double errorCompute() { /* How long since we last calculated */ long now = millis(); double timeChange = now - this.lastTime; /* Compute all the working error variables */ double error = this.Setpoint - this.Input; this.errSum += (error * timeChange); double dErr = (error - this.lastErr) / timeChange; /* Compute PID Output */ this.Output = this.kp * error + this.ki * this.errSum + this.kd * dErr; /* Remember some variables for next time */ this.lastErr = error; this.lastTime = now; return this.Output; } void SetTunings(double Kp, double Ki, double Kd) { this.kp = Kp; this.ki = Ki; this.kd = Kd; } /** * Method called to set the Setpoint so the PID controller has the * capability to calculate errors and correct them. * * @param double * @author Jack Rausch */ public void static setSetpoint( double defSetpoint){ Timer timer = new Timer(); timer.start(); double Setpoint = defSetpoint; } /** * All constants. * * @author James */ private static final class Constant { /** * Const shared. * * @author James */ public static final class Shared { static final double armMoveMaxTime = 2d; static final double armDown = -1, armUp = 1, armStop = 0; public static final double intakeDelay = 1d; } /** * Const for autoLowBar. * * @author James */ private static final class ConstLowBar { public static final double driveThroughDelay = 5d; } /** * Const for autoSpyBotLowGoal. * * @author James */ private static final class ConstSpyBotLowGoal { public static final double driveToDelay = 5d; } /** * Const for autoChevalDeFrise. * * @author James */ private static final class ConstChevalDeFrise { public static final double driveToDelay = 5d; public static final double driveThroughDelay = 5d; } /** * Const for autoPortcullis. * * @author James */ public static final class ConstPortcullis { public static final double driveDelay = 5d; public static final double driveThroughDelay = 5d; } } /** * The interface for programs outside to run the chosen autonomous * function. * * @author James */ public interface Interface { public void runAuto(); } /** * to lower arm. Need more info. * * @author James */ private void armLowerBottom() { this.armMotor.set(Constant.Shared.armDown); Autonomous.delay(Constant.Shared.armMoveMaxTime); this.armMotor.set(Constant.Shared.armStop); } /** * to delay for some time. Need more info. * * @author James * @param delayTime * delay time in seconds */ private static void delay(double delayTime) { // Just realized there is a delay thing in Timer. But I'd just // stick to using Autonomous.delay. edu.wpi.first.wpilibj.Timer.delay(delayTime); } /** * to lift arm. Need more info * * @author James */ private void armLifterTop() { this.armMotor.set(Constant.Shared.armUp); Autonomous.delay(Constant.Shared.armMoveMaxTime); this.armMotor.set(Constant.Shared.armStop); } /** * To drive straight some distance. * * @author James * @param driveDistance * Meters of driving * @param PLACEHOLDER * This is just a placeholder and does not do anything. * You can just use empty string "" for this. */ private void driveStraight(double driveDistance, Object PLACEHOLDER) { PLACEHOLDER = ""; } /** * Place Holder. To drive straight. Need more info. * * @author James * @param driveTime * Seconds of driving */ private void driveStraight(double driveTime) { // getting the victor[] array. Victor[] vicList = new Victor[] { this.frontLeft, this.frontRight, this.backLeft, this.backRight }; // command starts Autonomous.setVictorArray(vicList, Const.Motor.Run.Forward); DriveTrain dT = new DriveTrain(this.frontLeft, this.backLeft, this.frontRight, this.backRight); // command starts dT.drive(Const.Motor.Run.Forward); Autonomous.delay(driveTime); dT.drive(Const.Motor.Run.Stop); } private static void setVictorArray(Victor[] vicList, double setValue) { for (Victor v : vicList) v.set(setValue); } /** * throw ball out. Yet tested. * * @author James */ private void throwBall() { this.intake.set(Const.Motor.Run.Forward); Autonomous.delay(Constant.Shared.intakeDelay); this.intake.set(Const.Motor.Run.Stop); } /** * Autonomous function No.1 * * @author James */ public void autoLowBar() { this.armLowerBottom(); this.driveStraight(Constant.ConstLowBar.driveThroughDelay); } /** * Autonomous function No.2 * * @author James */ public void autoSpyBotLowGoal() { this.armLowerBottom(); this.driveStraight(Constant.ConstSpyBotLowGoal.driveToDelay); this.throwBall(); } /** * Autonomous function No.3 * * @author James */ public void autoChevalDeFrise() { this.driveStraight(Constant.ConstChevalDeFrise.driveToDelay); this.armLowerBottom(); this.driveStraight( Constant.ConstChevalDeFrise.driveThroughDelay); } /** * Autonomous function No.4 * * @author James */ public void autoPortcullis() { this.armLowerBottom(); this.driveStraight(Constant.ConstPortcullis.driveDelay); this.armLifterTop(); this.driveStraight( Constant.ConstPortcullis.driveThroughDelay); } /** * Should be equivalent to a method called getAccel of another * class I2CAccelerometer which isn't here yet. * * @author James * @return Accelerations, double[] with length of 3 */ private static double[] I2CAccelerometer_getAccel() { double[] accel = new double[3]; return accel; // placeholder } /** * Calculates distance traveled based on information from the * accelerometer. * * @author Joey * @return */ private static double[] I2CDistanceTraveled() { while (true) { double[] acceleration = Autonomous.I2CAccelerometer_getAccel(); double[] vtx = acceleration[0] * dt; double[] xt = v * dt; } } /** * Should be equivalent to a method called getAngles of another * class I2CGyro which isn't here yet. * * @author James * @return Angles, double[] with length of 3 */ private static double[] I2CGyro_getAngles() { double[] angles = new double[3]; return angles; // placeholder } }
package gov.nasa.jpl.mbee.mdk.ems; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.nomagic.ci.persistence.IProject; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.core.ProjectUtilities; import com.nomagic.magicdraw.esi.EsiUtils; import com.nomagic.task.ProgressStatus; import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import gov.nasa.jpl.mbee.mdk.MDKPlugin; import gov.nasa.jpl.mbee.mdk.api.incubating.MDKConstants; import gov.nasa.jpl.mbee.mdk.api.incubating.convert.Converters; import gov.nasa.jpl.mbee.mdk.ems.actions.MMSLoginAction; import gov.nasa.jpl.mbee.mdk.ems.actions.MMSLogoutAction; import gov.nasa.jpl.mbee.mdk.json.JacksonUtils; import gov.nasa.jpl.mbee.mdk.lib.MDUtils; import gov.nasa.jpl.mbee.mdk.lib.TicketUtils; import gov.nasa.jpl.mbee.mdk.lib.Utils; import gov.nasa.jpl.mbee.mdk.options.MDKOptionsGroup; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import javax.swing.*; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicReference; // TODO Use URI builder or similar @donbot public class MMSUtils { private static final int CHECK_CANCEL_DELAY = 100; private static String developerUrl = ""; public enum HttpRequestType { GET, POST, PUT, DELETE } private enum ThreadRequestExceptionType { IO_EXCEPTION, SERVER_EXCEPTION, URI_SYNTAX_EXCEPTION } public enum JsonBlobType { ELEMENT_JSON, ELEMENT_ID, PROJECT, REF, ORG } public static ObjectNode getElement(Project project, String elementId, ProgressStatus progressStatus) throws IOException, ServerException, URISyntaxException { Collection<String> elementIds = new ArrayList<>(1); elementIds.add(elementId); ObjectNode response = getElementsRecursively(project, elementIds, 0, progressStatus); JsonNode value; if (((value = response.get("elements")) != null) && value.isArray() && (value = ((ArrayNode) value).remove(1)) != null && (value instanceof ObjectNode)) { return (ObjectNode) value; } return response; } public static ObjectNode getElementRecursively(Project project, String elementId, int depth, ProgressStatus progressStatus) throws IOException, ServerException, URISyntaxException { Collection<String> elementIds = new ArrayList<>(1); elementIds.add(elementId); return getElementsRecursively(project, elementIds, depth, progressStatus); } /** * * @param elementIds collection of elements to get mms data for * @param project project to check * @param progressStatus progress status object, can be null * @return object node response * @throws ServerException * @throws IOException * @throws URISyntaxException */ public static ObjectNode getElements(Project project, Collection<String> elementIds, ProgressStatus progressStatus) throws IOException, ServerException, URISyntaxException { return getElementsRecursively(project, elementIds, 0, progressStatus); } /** * * @param elementIds collection of elements to get mms data for * @param depth depth to recurse through child elements. takes priority over recurse field * @param project project to check * @param progressStatus progress status object, can be null * @return object node response * @throws ServerException * @throws IOException * @throws URISyntaxException */ public static ObjectNode getElementsRecursively(Project project, Collection<String> elementIds, int depth, ProgressStatus progressStatus) throws ServerException, IOException, URISyntaxException { // verify elements if (elementIds == null || elementIds.isEmpty()) { return JacksonUtils.getObjectMapper().createObjectNode(); } // build uri URIBuilder requestUri = getServiceProjectsRefsElementsUri(project); if (requestUri == null) { return null; } if (depth == -1 || depth > 0) { requestUri.setParameter("depth", java.lang.Integer.toString(depth)); } // create request file File sendData = createEntityFile(MMSUtils.class, ContentType.APPLICATION_JSON, elementIds, JsonBlobType.ELEMENT_ID); //do cancellable request if progressStatus exists Utils.guilog("[INFO] Searching for " + elementIds.size() + " elements from server..."); if (progressStatus != null) { return sendCancellableMMSRequest(project, MMSUtils.buildRequest(MMSUtils.HttpRequestType.PUT, requestUri, sendData, ContentType.APPLICATION_JSON), progressStatus); } return sendMMSRequest(project, MMSUtils.buildRequest(MMSUtils.HttpRequestType.PUT, requestUri, sendData, ContentType.APPLICATION_JSON)); } /** * General purpose method for making http requests for file upload. * * @param requestUri URI to send the request to. Methods to generate this URI are available in the class. * @param sendFile File to send as an entity/body along with the request * @return * @throws IOException * @throws URISyntaxException */ public static HttpRequestBase buildRequest(URIBuilder requestUri, File sendFile) throws IOException, URISyntaxException { URI requestDest = requestUri.build(); HttpPost requestUpload = new HttpPost(requestDest); MultipartEntityBuilder uploadBuilder = MultipartEntityBuilder.create(); uploadBuilder.addBinaryBody( "file", new FileInputStream(sendFile), ContentType.APPLICATION_OCTET_STREAM, sendFile.getName() ); HttpEntity multiPart = uploadBuilder.build(); requestUpload.setEntity(multiPart); return requestUpload; } /** * General purpose method for making http requests for JSON objects. Type of request is specified in method call. * * @param type Type of request, as selected from one of the options in the inner enum. * @param requestUri URI to send the request to. Methods to generate this URI are available in the class. * @param sendData Data to send as an entity/body along with the request, if desired. Support for GET and DELETE * with body is included. * @return * @throws IOException * @throws URISyntaxException */ public static HttpRequestBase buildRequest(HttpRequestType type, URIBuilder requestUri, File sendData, ContentType contentType) throws IOException, URISyntaxException { // build specified request type // assume that any request can have a body, and just build the appropriate one URI requestDest = requestUri.build(); HttpRequestBase request = null; // bulk GETs are not supported in MMS, but bulk PUTs are. checking and and throwing error here in case if (type == HttpRequestType.GET && sendData != null) { throw new IOException("GETs with body are not supported"); } switch (type) { case DELETE: request = new HttpDeleteWithBody(requestDest); break; case GET: // request = new HttpGetWithBody(requestDest); request = new HttpGet(requestDest); break; case POST: request = new HttpPost(requestDest); break; case PUT: request = new HttpPut(requestDest); break; } request.addHeader("charset", (contentType != null ? contentType.getCharset() : Consts.UTF_8).displayName()); if (sendData != null) { if (contentType != null) { request.addHeader("Content-Type", contentType.getMimeType()); } InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(sendData), sendData.length(), contentType); //reqEntity.setChunked(true); ((HttpEntityEnclosingRequest) request).setEntity(reqEntity); } return request; } /** * Convenience / clarity method for making http requests for JSON objects withoout body. Type of request is * specified in method call. * * @param type Type of request, as selected from one of the options in the inner enum. * @param requestUri URI to send the request to. Methods to generate this URI are available in the class. * @return * @throws IOException * @throws URISyntaxException */ public static HttpRequestBase buildRequest(HttpRequestType type, URIBuilder requestUri) throws IOException, URISyntaxException { return buildRequest(type, requestUri, null, null); } public static File createEntityFile(Class<?> clazz, ContentType contentType, Collection nodes, JsonBlobType jsonBlobType) throws IOException { File file = File.createTempFile(clazz.getSimpleName() + "-" + contentType.getMimeType().replace('/', '.'), null); file.deleteOnExit(); String arrayName = "elements"; if (jsonBlobType == JsonBlobType.PROJECT) { arrayName = "projects"; } else if (jsonBlobType == JsonBlobType.REF) { arrayName = "refs"; } FileOutputStream outputStream = new FileOutputStream(file); JsonGenerator jsonGenerator = JacksonUtils.getJsonFactory().createGenerator(outputStream); jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart(arrayName); for (Object node : nodes) { if (node instanceof ObjectNode && jsonBlobType == JsonBlobType.ELEMENT_JSON) { jsonGenerator.writeObject((ObjectNode) node); } else if (node instanceof String && jsonBlobType == JsonBlobType.ELEMENT_ID) { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField(MDKConstants.ID_KEY, (String) node); jsonGenerator.writeEndObject(); } else { // unsupported collection type return null; } } jsonGenerator.writeEndArray(); jsonGenerator.writeStringField("source", "magicdraw"); jsonGenerator.writeStringField("mdkVersion", MDKPlugin.VERSION); jsonGenerator.writeEndObject(); jsonGenerator.close(); System.out.println(file.getPath()); return file; } /** * General purpose method for sending a constructed http request via http client. * * @param request * @return * @throws IOException * @throws ServerException */ public static ObjectNode sendMMSRequest(Project project, HttpRequestBase request) throws IOException, ServerException, URISyntaxException { HttpEntityEnclosingRequest httpEntityEnclosingRequest = null; boolean logBody = MDKOptionsGroup.getMDKOptions().isLogJson(); logBody = logBody && request instanceof HttpEntityEnclosingRequest; logBody = logBody && ((httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request).getEntity() != null); logBody = logBody && httpEntityEnclosingRequest.getEntity().isRepeatable(); System.out.println("MMS Request [" + request.getMethod() + "] " + request.getURI().toString()); if (logBody) { try (InputStream inputStream = httpEntityEnclosingRequest.getEntity().getContent()) { String requestBody = IOUtils.toString(inputStream); System.out.println(requestBody); } } // create client, execute request, parse response, store in thread safe buffer to return as string later // client, response, and reader are all auto closed after block ObjectNode responseJson = JacksonUtils.getObjectMapper().createObjectNode(); try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(request); InputStream inputStream = response.getEntity().getContent()) { // get data out of the response int responseCode = response.getStatusLine().getStatusCode(); String responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : ""); String responseType = ((response.getEntity().getContentType() != null) ? response.getEntity().getContentType().getValue() : ""); // debug / logging output from response System.out.println("MMS Response [" + request.getMethod() + "] " + request.getURI().toString() + " - Code: " + responseCode); if (MDKOptionsGroup.getMDKOptions().isLogJson()) { if (!responseBody.isEmpty() && !responseType.equals("application/json;charset=UTF-8")) { responseBody = "<span>" + responseBody + "</span>"; } System.out.println(" - Body: " + responseBody); } // flag for later server exceptions; they will be thrown after printing any available server messages to the gui log boolean throwServerException = false; // assume that 404s with json response bodies are "missing resource" 404s, which are expected for some cases and should not break normal execution flow if (responseCode == 404 && responseType.equals("application/json;charset=UTF-8")) { // do nothing, note in log System.out.println("[INFO] \"Missing Resource\" 404 processed."); } // allow re-attempt of request if credentials have expired or are invalid else if (responseCode == 401) { Utils.guilog("[ERROR] MMS authentication is missing or invalid. Closing connections. Please log in again and your request will be retried. Server code: " + responseCode); MMSLogoutAction.logoutAction(project); if (MMSLoginAction.loginAction(project)) { URIBuilder newRequestUri = new URIBuilder(request.getURI()); newRequestUri.setParameter("alf_ticket", TicketUtils.getTicket(project)); request.setURI(newRequestUri.build()); return sendMMSRequest(project, request); } else { throwServerException = true; } } // if it's anything else outside of the 200 range, assume failure and break normal flow else if (responseCode < 200 || responseCode >= 300) { Utils.guilog("[ERROR] Operation failed due to server error. Server code: " + responseCode); throwServerException = true; } // print server message if possible if (!responseBody.isEmpty() && responseType.equals("application/json;charset=UTF-8")) { responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class); JsonNode value; // display single response message if (responseJson != null && (value = responseJson.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) { Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText()); } // display multiple response messages if (responseJson != null && (value = responseJson.get("messages")) != null && value.isArray()) { ArrayNode msgs = (ArrayNode) value; for (JsonNode msg : msgs) { if (msg != null && (value = msg.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) { Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText()); } } } } if (throwServerException) { // big flashing red letters that the action failed, or as close as we're going to get Utils.showPopupMessage("Action failed. See notification window for details."); // throw is done last, after printing the error and any messages that might have been returned throw new ServerException(responseBody, responseCode); } } return responseJson; } /** * General purpose method for running a cancellable request. Builds a new thread to run the request, and passes * any relevant exception information back out via atomic references and generates new exceptions in calling thread * * @param request * @param progressStatus * @return * @throws IOException * @throws URISyntaxException * @throws ServerException contains both response code and response body */ public static ObjectNode sendCancellableMMSRequest(final Project project, HttpRequestBase request, ProgressStatus progressStatus) throws IOException, ServerException, URISyntaxException { final AtomicReference<ObjectNode> resp = new AtomicReference<>(); final AtomicReference<Integer> ecode = new AtomicReference<>(); final AtomicReference<ThreadRequestExceptionType> etype = new AtomicReference<>(); final AtomicReference<String> emsg = new AtomicReference<>(); Thread t = new Thread(() -> { ObjectNode response = JacksonUtils.getObjectMapper().createObjectNode(); try { response = sendMMSRequest(project, request); etype.set(null); ecode.set(200); emsg.set(""); } catch (ServerException ex) { etype.set(ThreadRequestExceptionType.SERVER_EXCEPTION); ecode.set(ex.getCode()); emsg.set(ex.getMessage()); ex.printStackTrace(); } catch (IOException e) { etype.set(ThreadRequestExceptionType.IO_EXCEPTION); emsg.set(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { etype.set(ThreadRequestExceptionType.URI_SYNTAX_EXCEPTION); emsg.set(e.getMessage()); e.printStackTrace(); } resp.set(response); }); t.start(); try { t.join(CHECK_CANCEL_DELAY); while (t.isAlive()) { if (progressStatus != null && progressStatus.isCancel()) { Application.getInstance().getGUILog().log("[INFO] Request to server for elements cancelled."); //clean up thread? return null; } t.join(CHECK_CANCEL_DELAY); } } catch (Exception e) { e.printStackTrace(); } if (etype.get() == ThreadRequestExceptionType.SERVER_EXCEPTION) { throw new ServerException(emsg.get(), ecode.get()); } else if (etype.get() == ThreadRequestExceptionType.IO_EXCEPTION) { throw new IOException(emsg.get()); } else if (etype.get() == ThreadRequestExceptionType.URI_SYNTAX_EXCEPTION) { throw new URISyntaxException("", emsg.get()); } return resp.get(); } public static String sendCredentials(Project project, String username, String password) throws ServerException, IOException, URISyntaxException { URIBuilder requestUri = MMSUtils.getServiceUri(project); if (requestUri == null) { return null; } requestUri.setPath(requestUri.getPath() + "/api/login"); requestUri.clearParameters(); ObjectNode credentials = JacksonUtils.getObjectMapper().createObjectNode(); credentials.put("username", username); credentials.put("password", password); //build request ContentType contentType = ContentType.APPLICATION_JSON; URI requestDest = requestUri.build(); HttpRequestBase request = new HttpPost(requestDest); request.addHeader("Content-Type", "application/json"); request.addHeader("charset", (Consts.UTF_8).displayName()); String data = JacksonUtils.getObjectMapper().writeValueAsString(credentials); ((HttpEntityEnclosingRequest)request).setEntity(new StringEntity(data, ContentType.APPLICATION_JSON)); // do request System.out.println("MMS Request [POST] " + requestUri.toString()); ObjectNode responseJson = null; try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(request); InputStream inputStream = response.getEntity().getContent()) { // get data out of the response int responseCode = response.getStatusLine().getStatusCode(); String responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : ""); String responseType = ((response.getEntity().getContentType() != null) ? response.getEntity().getContentType().getValue() : ""); // debug / logging output from response System.out.println("MMS Response [POST] " + requestUri.toString() + " - Code: " + responseCode); // if (MDKOptionsGroup.getMDKOptions().isLogJson()) { // if (!responseBody.isEmpty() && !responseType.equals("application/json;charset=UTF-8")) { // responseBody = "<span>" + responseBody + "</span>"; // System.out.println(" - Body: " + responseBody); // flag for later server exceptions; they will be thrown after printing any available server messages to the gui log boolean throwServerException = false; // if it's anything else outside of the 200 range, assume failure and break normal flow if (responseCode != 200) { Application.getInstance().getGUILog().log("[ERROR] Operation failed due to server error. Server code: " + responseCode); throwServerException = true; } // print server message if possible if (!responseBody.isEmpty() && responseType.equals("application/json;charset=UTF-8")) { responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class); JsonNode value; // display single response message if (responseJson != null && (value = responseJson.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) { Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText()); } // display multiple response messages if (responseJson != null && (value = responseJson.get("messages")) != null && value.isArray()) { ArrayNode msgs = (ArrayNode) value; for (JsonNode msg : msgs) { if (msg != null && (value = msg.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) { Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText()); } } } } if (throwServerException) { // big flashing red letters that the action failed, or as close as we're going to get Utils.showPopupMessage("Action failed. See notification window for details."); // throw is done last, after printing the error and any messages that might have been returned throw new ServerException(responseBody, responseCode); } } // parse response JsonNode value; if (responseJson != null && (value = responseJson.get("data")) != null && (value = value.get("ticket")) != null && value.isTextual()) { return value.asText(); } return null; } public static String getServerUrl(Project project) throws IllegalStateException { String urlString = null; if (project == null) { throw new IllegalStateException("Project is null."); } Element primaryModel = project.getPrimaryModel(); if (primaryModel == null) { throw new IllegalStateException("Model is null."); } if (StereotypesHelper.hasStereotype(primaryModel, "ModelManagementSystem")) { urlString = (String) StereotypesHelper.getStereotypePropertyFirst(primaryModel, "ModelManagementSystem", "MMS URL"); } else { Utils.showPopupMessage("Your project root element doesn't have ModelManagementSystem Stereotype!"); return null; } if ((urlString == null || urlString.isEmpty())) { Utils.showPopupMessage("Your project root element doesn't have ModelManagementSystem MMS URL stereotype property set!"); if (MDUtils.isDeveloperMode()) { urlString = JOptionPane.showInputDialog("[DEVELOPER MODE] Enter the server URL:", developerUrl); developerUrl = urlString; } } if (urlString == null || urlString.isEmpty()) { return null; } return urlString.trim(); } public static String getOrg(Project project) throws IOException, URISyntaxException, ServerException { // String siteString = ""; // if (StereotypesHelper.hasStereotype(project.getPrimaryModel(), "ModelManagementSystem")) { // siteString = (String) StereotypesHelper.getStereotypePropertyFirst(project.getPrimaryModel(), "ModelManagementSystem", "MMS Org"); // return siteString; URIBuilder uriBuilder = getServiceProjectsUri(project); ObjectNode response = sendMMSRequest(project, buildRequest(HttpRequestType.GET, uriBuilder)); JsonNode arrayNode; if (((arrayNode = response.get("projects")) != null) && arrayNode.isArray()) { JsonNode value; for (JsonNode projectNode : arrayNode) { if (((value = projectNode.get(MDKConstants.ID_KEY)) != null ) && value.isTextual() && value.asText().equals(project.getID()) && ((value = projectNode.get(MDKConstants.ORG_ID_KEY)) != null ) && value.isTextual() && !value.asText().isEmpty()) { return value.asText(); } } } return null; } public static boolean isProjectOnMms(Project project) throws IOException, URISyntaxException, ServerException { // build request for bulk project GET URIBuilder requestUri = MMSUtils.getServiceProjectsUri(project); if (requestUri == null) { return false; } // do request, check return for project ObjectNode response; response = MMSUtils.sendMMSRequest(project, MMSUtils.buildRequest(MMSUtils.HttpRequestType.GET, requestUri)); JsonNode projectsJson; if ((projectsJson = response.get("projects")) != null && projectsJson.isArray()) { JsonNode value; for (JsonNode projectJson : projectsJson) { if ((value = projectJson.get(MDKConstants.ID_KEY)) != null && value.isTextual() && value.asText().equals(Converters.getIProjectToIdConverter().apply(project.getPrimaryProject()))) { return true; } } } return false; } public static boolean isBranchOnMms(Project project, String branch) throws IOException, URISyntaxException, ServerException { // build request for project element URIBuilder requestUri = MMSUtils.getServiceProjectsRefsUri(project); if (requestUri == null) { return false; } // do request for ref element ObjectNode response; response = MMSUtils.sendMMSRequest(project, MMSUtils.buildRequest(MMSUtils.HttpRequestType.GET, requestUri)); JsonNode projectsJson; if ((projectsJson = response.get("refs")) != null && projectsJson.isArray()) { JsonNode value; for (JsonNode projectJson : projectsJson) { if ((value = projectJson.get(MDKConstants.NAME_KEY)) != null && value.isTextual() && value.asText().equals(branch)) { return true; } } } return false; } public static String getProjectOrg(Project project) throws IOException, URISyntaxException, ServerException { URIBuilder uriBuilder = getServiceProjectsUri(project); ObjectNode response = sendMMSRequest(project, buildRequest(HttpRequestType.GET, uriBuilder)); JsonNode arrayNode; if (((arrayNode = response.get("projects")) != null) && arrayNode.isArray()) { JsonNode value; for (JsonNode projectNode : arrayNode) { if (((value = projectNode.get(MDKConstants.ID_KEY)) != null ) && value.isTextual() && value.asText().equals(project.getID()) && ((value = projectNode.get(MDKConstants.ORG_ID_KEY)) != null ) && value.isTextual() && !value.asText().isEmpty()) { return value.asText(); } } } return null; } /** * Returns a URIBuilder object with a path = "/alfresco/service". Used as the base for all of the rest of the * URIBuilder generating convenience classes. * * @param project The project to gather the mms url and site name information from * @return URIBuilder * @throws URISyntaxException */ public static URIBuilder getServiceUri(Project project) { String urlString = getServerUrl(project); if (urlString == null) { return null; } // [scheme:][//host][path][?query][#fragment] URIBuilder uri; try { uri = new URIBuilder(urlString); } catch (URISyntaxException e) { Application.getInstance().getGUILog().log("[ERROR] Unexpected error in generation of MMS URL for project. Reason: " + e.getMessage()); e.printStackTrace(); return null; } uri.setPath("/alfresco/service"); if (TicketUtils.isTicketSet(project)) { uri.setParameter("alf_ticket", TicketUtils.getTicket(project)); } return uri; } /** * Returns a URIBuilder object with a path = "/alfresco/service/orgs" * * @param project The project to gather the mms url and site name information from * @return URIBuilder */ public static URIBuilder getServiceOrgsUri(Project project) { URIBuilder siteUri = getServiceUri(project); if (siteUri == null) { return null; } siteUri.setPath(siteUri.getPath() + "/orgs"); return siteUri; } /** * Returns a URIBuilder object with a path = "/alfresco/service/projects/{$PROJECT_ID}" * * @param project The project to gather the mms url and site name information from * @return URIBuilder */ public static URIBuilder getServiceProjectsUri (Project project) { URIBuilder projectUri = getServiceUri(project); if (projectUri == null) { return null; } projectUri.setPath(projectUri.getPath() + "/projects"); return projectUri; } /** * Returns a URIBuilder object with a path = "/alfresco/service/projects/{$PROJECT_ID}/refs/{$WORKSPACE_ID}" * * @param project The project to gather the mms url and site name information from * @return URIBuilder */ public static URIBuilder getServiceProjectsRefsUri (Project project) { URIBuilder refsUri = getServiceProjectsUri(project); if (refsUri == null) { return null; } refsUri.setPath(refsUri.getPath() + "/" + Converters.getIProjectToIdConverter().apply(project.getPrimaryProject()) + "/refs"); return refsUri; } /** * Returns a URIBuilder object with a path = "/alfresco/service/projects/{$PROJECT_ID}/refs/{$WORKSPACE_ID}/elements/${ELEMENT_ID}" * if element is not null * * @param project The project to gather the mms url and site name information from * @return URIBuilder * */ public static URIBuilder getServiceProjectsRefsElementsUri(Project project) { URIBuilder elementUri = getServiceProjectsRefsUri(project); if (elementUri == null) { return null; } // TODO review MDUtils.getWorkspace() to make sure it's returning the appropriate thing for branches elementUri.setPath(elementUri.getPath() + "/" + MDUtils.getWorkspace(project) + "/elements"); return elementUri; } public static String getDefaultSiteName(IProject iProject) { String name = iProject.getName().trim().replaceAll("\\W+", "-"); if (name.endsWith("-")) { name = name.substring(0, name.length() - 1); } return name; } public static ObjectNode getProjectObjectNode(Project project) { return getProjectObjectNode(project.getPrimaryProject()); } public static ObjectNode getProjectObjectNode(IProject iProject) { ObjectNode projectObjectNode = JacksonUtils.getObjectMapper().createObjectNode(); projectObjectNode.put(MDKConstants.TYPE_KEY, "Project"); projectObjectNode.put(MDKConstants.NAME_KEY, iProject.getName()); projectObjectNode.put(MDKConstants.ID_KEY, Converters.getIProjectToIdConverter().apply(iProject)); String resourceId = ""; if (ProjectUtilities.getProject(iProject).isRemote()) { resourceId = ProjectUtilities.getResourceID(iProject.getLocationURI()); } projectObjectNode.put(MDKConstants.TWC_ID_KEY, resourceId); String categoryId = ""; if (ProjectUtilities.getProject(iProject).getPrimaryProject() == iProject && !resourceId.isEmpty()) { categoryId = EsiUtils.getCategoryID(resourceId); } projectObjectNode.put(MDKConstants.CATEGORY_ID_KEY, categoryId); projectObjectNode.put(MDKConstants.PROJECT_URI_KEY, iProject.getProjectDescriptor().getLocationUri().toString()); return projectObjectNode; } }
package info.faceland.loot.math; import java.util.Random; public final class LootRandom extends Random { public LootRandom() { } public LootRandom(long seed) { super(seed); } @Override public double nextDouble() { long significand = 0; double divisor = 1; while (true) { int leadingZeros = Long.numberOfLeadingZeros(significand); int usefulBits = 64 - leadingZeros; int pendingBits = 53 - usefulBits; if (pendingBits == 0) { break; } int bits = Math.min(pendingBits, 30); significand = (significand << bits) + next(bits); divisor = divisor / (1 << bits); } return significand * divisor; } public int nextIntRange(int i1, int i2) { int min = Math.min(i1, i2); int max = Math.max(i1, i2); int diff = max - min; if (diff <= 0) { return min; } return min + nextInt(diff); } }
package io.github.mzmine.util; import com.google.common.collect.Range; import io.github.mzmine.datamodel.DataPoint; import io.github.mzmine.datamodel.FeatureIdentity; import io.github.mzmine.datamodel.FeatureStatus; import io.github.mzmine.datamodel.MobilityType; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.datamodel.features.Feature; import io.github.mzmine.datamodel.features.FeatureListRow; import io.github.mzmine.datamodel.features.ModularFeature; import io.github.mzmine.datamodel.features.ModularFeatureList; import io.github.mzmine.datamodel.features.ModularFeatureListRow; import io.github.mzmine.datamodel.features.compoundannotations.CompoundDBAnnotation; import io.github.mzmine.datamodel.features.types.DataType; import io.github.mzmine.datamodel.features.types.ListWithSubsType; import io.github.mzmine.datamodel.features.types.modifiers.AnnotationType; import io.github.mzmine.datamodel.impl.SimpleDataPoint; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.dataprocessing.featdet_manual.ManualFeature; import io.github.mzmine.util.scans.ScanUtils; import java.text.Format; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; /** * Utilities for feature lists */ public class FeatureUtils { private static final FeatureListRowSorter ascMzRowSorter = new FeatureListRowSorter( SortingProperty.MZ, SortingDirection.Ascending); /** * Common utility method to be used as Feature.toString() method in various Feature * implementations * * @param feature Feature to be converted to String * @return String representation of the feature */ public static String featureToString(Feature feature) { StringBuffer buf = new StringBuffer(); Format mzFormat = MZmineCore.getConfiguration().getMZFormat(); buf.append("m/z "); buf.append(mzFormat.format(feature.getMZ())); final Float averageRT = feature.getRT(); if (averageRT != null) { Format timeFormat = MZmineCore.getConfiguration().getRTFormat(); buf.append(" ("); buf.append(timeFormat.format(averageRT)); buf.append(" min)"); } final Float mobility = feature.getMobility(); if (mobility != null) { Format mobilityFormat = MZmineCore.getConfiguration().getMobilityFormat(); buf.append(" ["); buf.append(mobilityFormat.format(mobility)); buf.append(" "); final MobilityType unit = feature.getMobilityUnit(); if (unit != null) { buf.append(unit.getUnit()); } buf.append("]"); } buf.append(" : "); buf.append(feature.getRawDataFile().getName()); return buf.toString(); } public static String rowToString(FeatureListRow row) { StringBuffer buf = new StringBuffer(); Format mzFormat = MZmineCore.getConfiguration().getMZFormat(); buf.append(" buf.append(row.getID()); buf.append(" m/z "); buf.append(mzFormat.format(row.getAverageMZ())); final Float averageRT = row.getAverageRT(); if (averageRT != null) { Format timeFormat = MZmineCore.getConfiguration().getRTFormat(); buf.append(" ("); buf.append(timeFormat.format(averageRT)); buf.append(" min)"); } final Float mobility = row.getAverageMobility(); if (mobility != null) { Format mobilityFormat = MZmineCore.getConfiguration().getMobilityFormat(); buf.append(" ["); buf.append(mobilityFormat.format(mobility)); buf.append(" "); final MobilityType unit = row.getBestFeature().getMobilityUnit(); if (unit != null) { buf.append(unit.getUnit()); } buf.append("]"); } return buf.toString(); } /** * Compares identities of two feature list rows. 1) if preferred identities are available, they * must be same 2) if no identities are available on both rows, return true 3) otherwise all * identities on both rows must be same * * @return True if identities match between rows */ public static boolean compareIdentities(FeatureListRow row1, FeatureListRow row2) { if ((row1 == null) || (row2 == null)) { return false; } // If both have preferred identity available, then compare only those FeatureIdentity row1PreferredIdentity = row1.getPreferredFeatureIdentity(); FeatureIdentity row2PreferredIdentity = row2.getPreferredFeatureIdentity(); if ((row1PreferredIdentity != null) && (row2PreferredIdentity != null)) { return row1PreferredIdentity.getName().equals(row2PreferredIdentity.getName()); } // If no identities at all for both rows, then return true List<FeatureIdentity> row1Identities = row1.getPeakIdentities(); List<FeatureIdentity> row2Identities = row2.getPeakIdentities(); if ((row1Identities.isEmpty()) && (row2Identities.isEmpty())) { return true; } // Otherwise compare all against all and require that each identity has // a matching identity on the other row if (row1Identities.size() != row2Identities.size()) { return false; } boolean sameID = false; for (FeatureIdentity row1Identity : row1Identities) { sameID = false; for (FeatureIdentity row2Identity : row2Identities) { if (row1Identity.getName().equals(row2Identity.getName())) { sameID = true; break; } } if (!sameID) { break; } } return sameID; } /** * Compare charge state of the best MS/MS precursor masses * * @param row1 FeatureListRow 1 * @param row2 FeatureListRow 2 * @return true, same charge state */ public static boolean compareChargeState(FeatureListRow row1, FeatureListRow row2) { assert ((row1 != null) && (row2 != null)); int firstCharge = row1.getBestFeature().getCharge(); int secondCharge = row2.getBestFeature().getCharge(); return (firstCharge == 0) || (secondCharge == 0) || (firstCharge == secondCharge); } /** * Returns true if feature list row contains a compound identity matching to id */ public static boolean containsIdentity(FeatureListRow row, FeatureIdentity id) { for (FeatureIdentity identity : row.getPeakIdentities()) { if (identity.getName().equals(id.getName())) { return true; } } return false; } /** * Finds a combined m/z range that covers all given features */ public static Range<Double> findMZRange(Feature[] features) { Range<Double> mzRange = null; for (Feature p : features) { if (mzRange == null) { mzRange = p.getRawDataPointsMZRange(); } else { mzRange = mzRange.span(p.getRawDataPointsMZRange()); } } return mzRange; } /** * Integrates over a given m/z and rt range within a raw data file. * * @param dataFile * @param rtRange * @param mzRange * @return The result of the integration. */ public static double integrateOverMzRtRange(RawDataFile dataFile, Range<Float> rtRange, Range<Double> mzRange) { ManualFeature newFeature = new ManualFeature(dataFile); boolean dataPointFound = false; Scan[] scanNumbers = dataFile.getScanNumbers(1, rtRange); for (Scan scan : scanNumbers) { // Find most intense m/z feature DataPoint basePeak = ScanUtils.findBasePeak(scan, mzRange); if (basePeak != null) { if (basePeak.getIntensity() > 0) { dataPointFound = true; } newFeature.addDatapoint(scan, basePeak); } else { final double mzCenter = (mzRange.lowerEndpoint() + mzRange.upperEndpoint()) / 2.0; DataPoint fakeDataPoint = new SimpleDataPoint(mzCenter, 0); newFeature.addDatapoint(scan, fakeDataPoint); } } if (dataPointFound) { newFeature.finalizeFeature(); return newFeature.getArea(); } else { return 0.0; } } /** * @param row The row. * @return The average retention time range of all features contained in this feature list row * across all raw data files. Empty range (0,0) if the row is null or has no feature assigned to * it. */ public @NotNull static Range<Float> getFeatureListRowAvgRtRange(FeatureListRow row) { if (row == null || row.getBestFeature() == null) { return Range.closed(0.f, 0.f); } int size = row.getFeatures().size(); double[] lower = new double[size]; double[] upper = new double[size]; Feature[] f = row.getFeatures().toArray(new Feature[0]); for (int i = 0; i < size; i++) { if (f[i] == null) { continue; } Range<Float> r = f[i].getRawDataPointsRTRange(); lower[i] = r.lowerEndpoint(); upper[i] = r.upperEndpoint(); } float avgL = 0, avgU = 0; for (int i = 0; i < size; i++) { avgL += (float) lower[i]; avgU += (float) upper[i]; } avgL /= size; avgU /= size; return Range.closed(avgL, avgU); } /** * Creates a copy of a FeatureListRow. * * @param row A row. * @return A copy of row. */ public static ModularFeatureListRow copyFeatureRow(final ModularFeatureListRow row) { return copyFeatureRow(row.getFeatureList(), row, true); } /** * Create a copy of a feature list row. * * @param newFeatureList * @param row the row to copy. * @return the newly created copy. */ private static ModularFeatureListRow copyFeatureRow(ModularFeatureList newFeatureList, final ModularFeatureListRow row, boolean copyFeatures) { // Copy the feature list row. final ModularFeatureListRow newRow = new ModularFeatureListRow(newFeatureList, row, copyFeatures); // TODO this should actually be already copied in the feature list row constructor (all DataTypes are) // if (row.getFeatureInformation() != null) { // SimpleFeatureInformation information = // new SimpleFeatureInformation(new HashMap<>(row.getFeatureInformation().getAllProperties())); // newRow.setFeatureInformation(information); return newRow; } /** * Creates a copy of an array of FeatureListRows. * * @param rows The rows to be copied. * @return A copy of rows. */ public static ModularFeatureListRow[] copyFeatureRows(final ModularFeatureListRow[] rows) { ModularFeatureListRow[] newRows = new ModularFeatureListRow[rows.length]; for (int i = 0; i < newRows.length; i++) { newRows[i] = copyFeatureRow(rows[i]); } return newRows; } public static ModularFeatureListRow[] copyFeatureRows(ModularFeatureList newFeatureList, final ModularFeatureListRow[] rows, boolean copyFeatures) { ModularFeatureListRow[] newRows = new ModularFeatureListRow[rows.length]; for (int i = 0; i < newRows.length; i++) { newRows[i] = copyFeatureRow(newFeatureList, rows[i], copyFeatures); } return newRows; } public static List<ModularFeatureListRow> copyFeatureRows( final List<ModularFeatureListRow> rows) { return rows.stream().map(row -> copyFeatureRow(row)).collect(Collectors.toList()); } public static List<ModularFeatureListRow> copyFeatureRows(ModularFeatureList newFeatureList, final List<ModularFeatureListRow> rows, boolean copyFeatures) { return rows.stream().map(row -> copyFeatureRow(newFeatureList, row, copyFeatures)) .collect(Collectors.toList()); } /** * Convenience method to sort an array of FeatureListRows by ascending m/z * * @param rows * @return Array sorted by ascending m/z. */ public static FeatureListRow[] sortRowsMzAsc(FeatureListRow[] rows) { Arrays.sort(rows, ascMzRowSorter); return rows; } /** * Builds simple modular feature from manual feature using mz and rt range. * * @param featureList * @param dataFile * @param rtRange * @param mzRange * @return The result of the integration. */ public static ModularFeature buildSimpleModularFeature(ModularFeatureList featureList, RawDataFile dataFile, Range<Float> rtRange, Range<Double> mzRange) { // Get MS1 scans in RT range. Scan[] scanRange = dataFile.getScanNumbers(1, rtRange); // Feature parameters. DataPoint targetDP[] = new DataPoint[scanRange.length]; double targetMZ; float targetRT, targetHeight, targetArea; targetMZ = (mzRange.lowerEndpoint() + mzRange.upperEndpoint()) / 2; targetRT = (float) (rtRange.upperEndpoint() + rtRange.lowerEndpoint()) / 2; targetHeight = targetArea = 0; Scan representativeScan = null; List<Scan> allMS2fragmentScanNumbers = ScanUtils.streamAllMS2FragmentScans(dataFile, rtRange, mzRange).toList(); // Get target data points, height, and estimated area over range. for (int i = 0; i < scanRange.length; i++) { Scan scan = scanRange[i]; double mz = targetMZ; double intensity = 0; // Get base peak for target. DataPoint basePeak = ScanUtils.findBasePeak(scan, mzRange); // If peak exists, get data point values. if (basePeak != null) { mz = basePeak.getMZ(); intensity = basePeak.getIntensity(); } // Add data point to array. targetDP[i] = new SimpleDataPoint(mz, intensity); // Update feature height and scan. if (intensity > targetHeight) { targetHeight = (float) intensity; representativeScan = scan; } // Skip area calculation for last datapoint. if (i == scanRange.length - 1) { break; } // Get next scan for area calculation. Scan nextScan = scanRange[i + 1]; DataPoint nextBasePeak = ScanUtils.findBasePeak(scan, mzRange); double nextIntensity = 0; if (nextBasePeak != null) { nextIntensity = nextBasePeak.getIntensity(); } // Naive area under the curve calculation. double rtDifference = nextScan.getRetentionTime() - scan.getRetentionTime(); rtDifference *= 60; targetArea += (float) (rtDifference * (intensity + nextIntensity) / 2); } if (targetHeight != 0) { // Set intensity range with maximum height in range. Range intensityRange = Range.open((float) 0.0, targetHeight); // Build new feature for target. ModularFeature newPeak = new ModularFeature(featureList, dataFile, targetMZ, targetRT, targetHeight, targetArea, scanRange, targetDP, FeatureStatus.DETECTED, representativeScan, allMS2fragmentScanNumbers, rtRange, mzRange, intensityRange); return newPeak; } else { return null; } } /** * Loops over all {@link DataType}s in a {@link FeatureListRow}. Extracts all annotations derived * from a {@link CompoundDBAnnotation} in all {@link AnnotationType}s derived from the * {@link ListWithSubsType} within the {@link FeatureListRow}'s {@link * io.github.mzmine.datamodel.features.ModularDataModel}. * * @param selectedRow The row * @return List of all annotations. */ @NotNull public static List<CompoundDBAnnotation> extractAllCompoundAnnotations( FeatureListRow selectedRow) { final List<CompoundDBAnnotation> compoundAnnotations = new ArrayList<>(); final Collection<DataType> dataTypes = selectedRow.getTypes().values(); for (DataType dataType : dataTypes) { if (dataType instanceof ListWithSubsType<?> listType && dataType instanceof AnnotationType) { final List<?> list = selectedRow.get(listType); if (list != null && !list.isEmpty()) { list.stream().filter(c -> c instanceof CompoundDBAnnotation) .forEach(c -> compoundAnnotations.add((CompoundDBAnnotation) c)); } } } return compoundAnnotations; } }
package mariculture.core.tile; import java.util.ArrayList; import mariculture.api.core.Environment.Temperature; import mariculture.api.core.FuelInfo; import mariculture.api.core.MaricultureHandlers; import mariculture.api.core.RecipeSmelter; import mariculture.core.config.Machines.MachineSettings; import mariculture.core.gui.ContainerMariculture; import mariculture.core.gui.feature.FeatureEject.EjectSetting; import mariculture.core.gui.feature.FeatureNotifications.NotificationType; import mariculture.core.gui.feature.FeatureRedstone.RedstoneMode; import mariculture.core.helpers.FluidHelper; import mariculture.core.lib.MachineMultiMeta; import mariculture.core.lib.MachineSpeeds; import mariculture.core.lib.MetalRates; import mariculture.core.network.PacketHandler; import mariculture.core.tile.base.TileMultiMachineTank; import mariculture.core.util.IHasNotification; import net.minecraft.inventory.ICrafting; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; public class TileCrucible extends TileMultiMachineTank implements IHasNotification { private static final int MAX_TEMP = 25000; private int temp; private boolean canFuel; private int cooling; private double melting_modifier = 1.0D; public TileCrucible() { max = MachineSpeeds.getCrucibleSpeed(); inventory = new ItemStack[9]; needsInit = true; } private static final int liquid_in = 3; private static final int liquid_out = 4; private static final int[] in = new int[] { 5, 6 }; private static final int fuel = 7; private static final int out = 8; @Override public int[] getInputSlots() { return in; } @Override public int[] getAccessibleSlotsFromSide(int side) { return new int[] { 3, 4, 5, 6, 7, 8 }; } @Override public void setInventorySlotContents(int slot, ItemStack stack) { super.setInventorySlotContents(slot, stack); canWork = canWork(); } @Override public boolean canInsertItem(int slot, ItemStack stack, int side) { if (FluidHelper.isFluidOrEmpty(stack)) return slot == liquid_in; if (MaricultureHandlers.crucible.getFuelInfo(stack) != null) return slot == fuel; return slot == 5 || slot == 6; } @Override public boolean canExtractItem(int slot, ItemStack stack, int side) { return slot == out || slot == liquid_out; } @Override public EjectSetting getEjectType() { return EjectSetting.ITEMNFLUID; } @Override public boolean isNotificationVisible(NotificationType type) { return false; } @Override public boolean canWork() { return hasTemperature() && hasItem() && rsAllowsWork() && hasRoom(); } private boolean hasTemperature() { return temp > 0; } private boolean hasItem() { return inventory[in[0]] != null || inventory[in[1]] != null; } private boolean hasRoom() { return canMelt(0) || canMelt(1); } private boolean areStacksEqual(ItemStack stack1, ItemStack stack2) { return stack1.getItem() == stack2.getItem() && stack1.getItemDamage() == stack2.getItemDamage(); } @Override public void updateMasterMachine() { if (!worldObj.isRemote) { heatUp(); coolDown(); if (canWork) { processed += speed * 50 * melting_modifier; if (processed >= max) { processed = 0; if (canWork()) { if (canMelt(0)) { melt(0); } if (canMelt(1)) { melt(1); } } canWork = canWork(); } } else { processed = 0; } if (processed <= 0) { processed = 0; } if (onTick(100) && tank.getFluidAmount() > 0 && RedstoneMode.canWork(this, mode) && EjectSetting.canEject(setting, EjectSetting.FLUID)) { helper.ejectFluid(new int[] { 5000, MetalRates.BLOCK, 1000, MetalRates.ORE, MetalRates.INGOT, MetalRates.NUGGET, 1 }); } } } @Override public void updateSlaveMachine() { if (onTick(100)) { TileCrucible mstr = (TileCrucible) getMaster(); if (mstr != null && mstr.tank.getFluidAmount() > 0 && RedstoneMode.canWork(this, mstr.mode) && EjectSetting.canEject(mstr.setting, EjectSetting.FLUID)) { helper.ejectFluid(new int[] { 5000, MetalRates.BLOCK, 1000, MetalRates.ORE, MetalRates.INGOT, MetalRates.NUGGET, 1 }); } } } private class FuelHandler { private int usedHeat; private int tick; private FuelInfo info; private void read(NBTTagCompound nbt) { if (nbt.getBoolean("HasHandler")) { info = new FuelInfo(); info.read(nbt); } } private void write(NBTTagCompound nbt) { if (info != null) { nbt.setBoolean("HasHandler", true); info.write(nbt); } } private void set(FuelInfo info) { this.info = info; tick = 0; usedHeat = 0; } private int getMaxTempPer(int purity) { return info.maxTempPer * (purity + 1); } private int tick(int temp, int purity) { int realUsed = usedHeat * 2000 / MAX_TEMP; int realTemp = temp * 2000 / MAX_TEMP; tick++; if (realUsed < getMaxTempPer(purity) && realTemp < info.maxTemp) { temp += heat / 3 + 1; usedHeat += heat / 3 + 1; } if (realUsed >= getMaxTempPer(purity) || tick >= info.ticksPer) { info = null; if (canFuel()) { fuelHandler.set(getInfo()); } else { fuelHandler.set(null); } } return temp; } } private FuelHandler fuelHandler; private boolean canFuel() { if (fuelHandler.info != null) return false; if (!rsAllowsWork()) return false; if (MaricultureHandlers.crucible.getFuelInfo(inventory[fuel]) != null) return true; if (worldObj.getTileEntity(xCoord, yCoord - 1, zCoord) instanceof IFluidHandler) { IFluidHandler handler = (IFluidHandler) worldObj.getTileEntity(xCoord, yCoord - 1, zCoord); FluidTankInfo[] info = handler.getTankInfo(ForgeDirection.UP); if (info != null && info[0].fluid != null && info[0].fluid.amount >= 10) return MaricultureHandlers.crucible.getFuelInfo(info[0].fluid) != null; } return false; } private void heatUp() { if (fuelHandler == null) { fuelHandler = new FuelHandler(); } if (onTick(20)) { canFuel = canFuel(); } if (canFuel) { fuelHandler.set(getInfo()); canFuel = false; } if (fuelHandler.info != null) { temp = Math.min(MAX_TEMP, fuelHandler.tick(temp, purity)); if (temp >= MAX_TEMP) { temp = MAX_TEMP; } } } private void coolDown() { if (cooling <= 0) { cooling = Math.max(1, Temperature.getCoolingSpeed(MaricultureHandlers.environment.getBiomeTemperature(worldObj, xCoord, yCoord, zCoord))); } if (onTick(20)) { temp -= cooling; if (temp <= 0) { temp = 0; } } } public FuelInfo getInfo() { FuelInfo info = MaricultureHandlers.crucible.getFuelInfo(inventory[fuel]); if (info == null) { IFluidHandler handler = (IFluidHandler) worldObj.getTileEntity(xCoord, yCoord - 1, zCoord); FluidTankInfo[] tank = handler.getTankInfo(ForgeDirection.UP); if (tank.length > 0 && tank[0] != null && tank[0].fluid != null) { info = MaricultureHandlers.crucible.getFuelInfo(tank[0].fluid); handler.drain(ForgeDirection.UP, new FluidStack(tank[0].fluid.fluidID, 10), true); } } else { decrStackSize(fuel, 1); } return info; } private boolean canMelt(int slot) { int other = slot == 0 ? 1 : 0; RecipeSmelter recipe = MaricultureHandlers.crucible.getResult(inventory[in[slot]], inventory[in[other]], getTemperatureScaled(2000), MaricultureHandlers.upgrades.hasUpgrade("ethereal", this)); if (recipe == null) return false; int fluidAmount = recipe.fluid.amount; FluidStack fluid = recipe.fluid.copy(); fluid.amount = fluidAmount; if (tank.fill(fluid, false) < fluid.amount) return false; boolean ret = recipe.output == null || setting.canEject(EjectSetting.ITEM); if (ret == false) { ret = inventory[out] == null || areStacksEqual(inventory[out], recipe.output) && inventory[out].stackSize + recipe.output.stackSize <= inventory[out].getMaxStackSize(); } if (ret == true) { int realTemp = temp * 2000 / MAX_TEMP; int max_temp = 2000 - recipe.temp; melting_modifier = 1.0D + Math.min(realTemp, max_temp) * 3.333333D / 2000; return true; } else return false; } private void melt(int slot) { int other = slot == 0 ? 1 : 0; RecipeSmelter recipe = MaricultureHandlers.crucible.getResult(inventory[in[slot]], inventory[in[other]], getTemperatureScaled(2000), MaricultureHandlers.upgrades.hasUpgrade("ethereal", this)); if (recipe == null) return; decrStackSize(in[slot], recipe.input.stackSize); int fluidAmount = recipe.fluid.amount; FluidStack fluid = recipe.fluid.copy(); fluid.amount = fluidAmount; tank.fill(fluid, true); if (recipe.output != null && recipe.chance > 0) if (worldObj.rand.nextInt(recipe.chance) == 0) { helper.insertStack(recipe.output.copy(), new int[] { out }); } } // Gui Data @Override public void getGUINetworkData(int id, int value) { super.getGUINetworkData(id, value); int realID = id - offset; switch (realID) { case 0: temp = value; case 1: burnHeight = value; } } private int burnHeight = 0; public int getBurnTimeRemainingScaled() { return burnHeight; } @Override public void sendGUINetworkData(ContainerMariculture container, ICrafting crafting) { super.sendGUINetworkData(container, crafting); crafting.sendProgressBarUpdate(container, 0 + offset, temp); if (fuelHandler.info != null) { burnHeight = 11 - fuelHandler.tick * 12 / fuelHandler.info.ticksPer; crafting.sendProgressBarUpdate(container, 1 + offset, burnHeight); } else { crafting.sendProgressBarUpdate(container, 1 + offset, 0); } } public int getTemperatureScaled(int i) { return temp * i / MAX_TEMP; } public String getRealTemperature() { return "" + temp * 2000 / MAX_TEMP; } public int getFluidAmount(String name, int amount) { if (name.startsWith("ore")) { amount += (purity * MachineSettings.PURITY); } return amount; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); temp = nbt.getInteger("Temperature"); canFuel = nbt.getBoolean("CanFuel"); fuelHandler = new FuelHandler(); fuelHandler.read(nbt); cooling = nbt.getInteger("CoolingSpeed"); melting_modifier = nbt.getDouble("MeltingModifier"); } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger("CoolingSpeed", cooling); nbt.setInteger("Temperature", temp); nbt.setDouble("MeltingModifier", melting_modifier); nbt.setBoolean("CanFuel", canFuel); if (fuelHandler != null) { fuelHandler.write(nbt); } } // Master stuff @Override public void onBlockPlaced() { onBlockPlaced(xCoord, yCoord, zCoord); PacketHandler.updateRender(this); } private void onBlockPlaced(int x, int y, int z) { if (isPart(xCoord, yCoord + 1, zCoord) && !isPart(xCoord, yCoord - 1, zCoord) && !isPart(xCoord, yCoord + 2, zCoord)) { MultiPart mstr = new MultiPart(xCoord, yCoord, zCoord); ArrayList<MultiPart> parts = new ArrayList<MultiPart>(); parts.add(setAsSlave(mstr, xCoord, yCoord + 1, zCoord)); setAsMaster(mstr, parts); } if (isPart(xCoord, yCoord - 1, zCoord) && !isPart(xCoord, yCoord + 1, zCoord) && !isPart(xCoord, yCoord - 2, zCoord)) { MultiPart mstr = new MultiPart(xCoord, yCoord - 1, zCoord); ArrayList<MultiPart> parts = new ArrayList<MultiPart>(); parts.add(setAsSlave(mstr, xCoord, yCoord, zCoord)); setAsMaster(mstr, parts); } } @Override public boolean isPart(int x, int y, int z) { return worldObj.getBlock(x, y, z) == getBlockType() && worldObj.getBlockMetadata(x, y, z) == MachineMultiMeta.CRUCIBLE & !isPartnered(x, y, z); } }
package me.zp4rker.discord.jitters; import me.zp4rker.discord.core.command.handler.CommandHandler; import me.zp4rker.discord.core.logger.ZLogger; import me.zp4rker.discord.jitters.lstnr.*; import me.zp4rker.discord.jitters.util.ExceptionHandler; import me.zp4rker.discord.jitters.util.JSONUtil; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.hooks.AnnotatedEventManager; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; /** * @author ZP4RKER */ public class Jitters { public static ExecutorService async = Executors.newCachedThreadPool(); public static JDA jda; public static CommandHandler handler; public static final String VERSION = "v1.0"; // Roles public static Role staff, flash, arrow, supergirl, legends; public static void main(String[] args) throws Exception { handler = new CommandHandler("!"); jda = new JDABuilder(AccountType.BOT).setToken(args[0]) .setEventManager(new AnnotatedEventManager()) .addEventListener(handler) .addEventListener(new ReadyListener()) .addEventListener(new JoinListener()) .addEventListener(new LeaveListener()) .addEventListener(new SpamListener()) .addEventListener(new RoleListener()) .buildAsync(); ZLogger.initialise(); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); } public static String getWelcomeMessage(User user) { String message = "Welcome to Jitters, " + user.getAsMention() + "! Head on over to " + "<#312817696578469888> and run the command `!assign` to start adding your roles."; try { if (!configValid()) { generateConfig(); } JSONObject data = JSONUtil.readFile(new File(getDirectory(), "conf.json")); String[] messages = toStringArray(data.getJSONArray("join-messages")); int max = messages.length; int rand = ThreadLocalRandom.current().nextInt(0, max); message = messages[rand].replace("%user%", user.getAsMention()); } catch (Exception e) { ExceptionHandler.handleException(e); } return message; } private static String[] toStringArray(JSONArray array) { List<String> list = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { list.add(array.getString(i)); } return list.toArray(new String[0]); } private static void generateConfig() throws Exception { File configFile = new File(getDirectory(), "conf.json"); if (!configFile.getParentFile().exists()) configFile.getParentFile().mkdir(); if (!configFile.exists()) configFile.createNewFile(); // Generate default config JSONArray array = new JSONArray(); // Flash array.put("My name is %user%. And I am the fastest man alive. To the outside world, I'm an ordinary forensic scientist. " + "But secretly, with the help of my friends at S.T.A.R. Labs, I fight crime and find other metahumans like me."); // Arrow array.put("My name is %user%. After five years in hell, I came home with only one goal: To save my city. Today I " + "fight that war on two fronts. By day, I lead Star City as its mayor. But by night, I am someone else. I " + "am something else."); // Supergirl array.put("When I was a child, my planet Krypton was dying. I was sent to Earth to protect my cousin. But my pod got " + "knocked off-course and by the time I got here, my cousin had already grown up and become... Superman. I hid " + "who I really was until one day when an accident forced me to reveal myself to the world. I am %user%."); // Legends array.put("Seriously, you idiots haven't figured this out by now? It all started when we blew up the time pigs, the " + "Time Masters. Now history's all screwed up, but it's up to us to un-screw it up. But half the time we screw " + "things up even worse. So don't call us heroes, we're something else. We're %user%."); // Constantine array.put("My name is %user%. I am the one who steps on the shadows, all trench coat and arrogance. I'll drive your demons " + "away, kick 'em in the bullocks, and spit on them when they're down, leaving only a nod and a wink and a wisecrack. " + "I walk my path alone because, let's be honest... who would be crazy enough to walk it with me?"); JSONObject root = new JSONObject(); root.put("join-messages", array); JSONUtil.writeFile(root.toString(2), configFile); } private static boolean configValid() { try { File configFile = new File(getDirectory(), "conf.json"); if (!configFile.exists()) return false; JSONObject data = JSONUtil.readFile(configFile); return data.keySet().contains("join-messages") && data.get("join-messages") instanceof JSONArray; } catch (Exception e) { return false; } } public static File getDirectory() throws Exception { return new File(Jitters.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile(); } }
package net.databinder.components; import wicket.Component; import wicket.PageParameters; import wicket.markup.html.WebPage; import wicket.markup.html.basic.Label; import wicket.markup.html.panel.FeedbackPanel; import wicket.model.IModel; import wicket.model.Model; /** * Simple page with a default stylesheet, page title, and feedback component in its * HTML template. Will not likely serve as a base for complicated layouts. * @author Nathan Hamblen */ public abstract class DataPage extends WebPage { /** * If this constructor is public in a subclass, the page will be bookmarkable and a valid default page. */ protected DataPage() { super(); init(); } /** * If this constructor is public in a subclass, the page will be bookmarkable and a valid default page. * When this and a no argument constructor are both public, this one will be used by default. */ protected DataPage(PageParameters params) { super(params); // nothing is done with params in WebPage init(); } /** * Construct the page with an existing model. * @param model presumably created in another page or component */ protected DataPage(IModel model) { super(model); init(); } /** * Adds title, stylesheet, and feedback components. */ private void init() { add(new Label("pageTitle", new Model() { @Override public Object getObject(Component component) { return getName(); } }).setRenderBodyOnly(true)); add(new StyleLink("dataStylesheet", DataPage.class)); add(new FeedbackPanel("feedback")); } /** * Name to be used as a title in the page header. * @return */ protected abstract String getName(); }
package net.imagej.trouble.hidden; /** * STOP LOOKING AT THIS CLASS!! IT'S OFF LIMITS! * * @author Mark Hiner <hinerm@gmail.com> */ public class MathDoer { public static int doMaths() { return 1+5*100/20%2+42; } }
package net.imagej.trouble.hidden; /** * STOP LOOKING AT THIS CLASS!! IT'S OFF LIMITS! * * @author Mark Hiner <hinerm@gmail.com> */ public class MathDoer { public static int doMaths() { int i; return (i=(i=(i=(i=(i=(i=(1+5*100/20%2+42*56-25))*i)*i)*i)*i)*i)+100*73; } }
package net.imagej.updater; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.GZIPOutputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import net.imagej.updater.Conflicts.Conflict; import net.imagej.updater.FileObject.Action; import net.imagej.updater.FileObject.Status; import net.imagej.updater.action.InstallOrUpdate; import net.imagej.updater.action.KeepAsIs; import net.imagej.updater.action.Remove; import net.imagej.updater.action.Uninstall; import net.imagej.updater.action.Upload; import net.imagej.updater.util.DependencyAnalyzer; import net.imagej.updater.util.Progress; import net.imagej.updater.util.UpdateCanceledException; import net.imagej.updater.util.UpdaterUtil; import org.scijava.log.LogService; import org.xml.sax.SAXException; /** * This class represents the database of available {@link FileObject}s. * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class FilesCollection extends LinkedHashMap<String, FileObject> implements Iterable<FileObject> { public final static String DEFAULT_UPDATE_SITE = "ImageJ"; private File imagejRoot; public final LogService log; protected Set<FileObject> ignoredConflicts = new HashSet<FileObject>(); protected List<Conflict> conflicts = new ArrayList<Conflict>(); private Map<String, UpdateSite> updateSites; private boolean updateSitesChanged = false; private DependencyAnalyzer dependencyAnalyzer; public final UpdaterUtil util; /** * This constructor takes the imagejRoot primarily for testing purposes. * * @param imagejRoot the ImageJ directory */ public FilesCollection(final File imagejRoot) { this(UpdaterUtil.getLogService(), imagejRoot); } /** * This constructor takes the imagejRoot primarily for testing purposes. * * @param log the log service * @param imagejRoot the ImageJ directory */ public FilesCollection(final LogService log, final File imagejRoot) { this.log = log; this.imagejRoot = imagejRoot; util = new UpdaterUtil(imagejRoot); updateSites = new LinkedHashMap<String, UpdateSite>(); addUpdateSite(DEFAULT_UPDATE_SITE, UpdaterUtil.MAIN_URL, null, null, imagejRoot == null ? 0 : UpdaterUtil.getTimestamp(prefix(UpdaterUtil.XML_COMPRESSED))); } public UpdateSite addUpdateSite(final String name, final String url, final String sshHost, final String uploadDirectory, final long timestamp) { final UpdateSite site = new UpdateSite(name, url, sshHost, uploadDirectory, null, null, timestamp); site.setActive(true); return addUpdateSite(site); } public UpdateSite addUpdateSite(UpdateSite site) { addUpdateSite(site.getName(), site); setUpdateSitesChanged(true); return site; } protected void addUpdateSite(final String name, final UpdateSite updateSite) { UpdateSite already = updateSites.get(name); updateSite.rank = already != null ? already.rank : updateSites.size(); updateSites.put(name, updateSite); } public void renameUpdateSite(final String oldName, final String newName) { if (getUpdateSite(newName, true) != null) throw new RuntimeException( "Update site " + newName + " exists already!"); if (getUpdateSite(oldName, true) == null) throw new RuntimeException( "Update site " + oldName + " does not exist!"); // handle all files for (final FileObject file : this) if (oldName.equals(file.updateSite)) file.updateSite = newName; // preserve order final Map<String, UpdateSite> oldMap = updateSites; updateSites = new LinkedHashMap<String, UpdateSite>(); for (final String name : oldMap.keySet()) { final UpdateSite site = oldMap.get(name); if (name.equals(oldName)) site.setName(newName); addUpdateSite(site.getName(), site); } } public void removeUpdateSite(final String name) { for (final FileObject file : forUpdateSite(name)) { file.removeFromUpdateSite(name, this); } updateSites.remove(name); setUpdateSitesChanged(true); // update rank int counter = 1; for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) { entry.getValue().rank = counter++; } } /** @deprecated use {@link #getUpdateSite(String, boolean)} instead */ @Deprecated public UpdateSite getUpdateSite(final String name) { return getUpdateSite(name, false); } public UpdateSite getUpdateSite(final String name, final boolean evenDisabled) { if (name == null) return null; final UpdateSite site = updateSites.get(name); return evenDisabled || site == null || site.isActive() ? site : null; } /** @deprecated use {@link #getUpdateSiteNames(boolean)} instead */ @Deprecated public Collection<String> getUpdateSiteNames() { return getUpdateSiteNames(false); } /** Gets the names of known update sites. */ public Collection<String> getUpdateSiteNames(final boolean evenDisabled) { if (evenDisabled) return updateSites.keySet(); final List<String> result = new ArrayList<String>(); final Iterator<java.util.Map.Entry<String, UpdateSite>> it = updateSites.entrySet().iterator(); while (it.hasNext()) { java.util.Map.Entry<String, UpdateSite> entry = it.next(); if (entry.getValue().isActive()) result.add(entry.getKey()); } return result; } /** Gets the list of known update sites. */ public Collection<UpdateSite> getUpdateSites(final boolean evenDisabled) { if (evenDisabled) return updateSites.values(); final List<UpdateSite> result = new ArrayList<UpdateSite>(); for (final UpdateSite site : updateSites.values()) { if (site.isActive()) result.add(site); } return result; } public Collection<String> getSiteNamesToUpload() { final Collection<String> set = new HashSet<String>(); for (final FileObject file : toUpload(false)) set.add(file.updateSite); for (final FileObject file : toRemove()) set.add(file.updateSite); // keep the update sites' order final List<String> result = new ArrayList<String>(); for (final String name : getUpdateSiteNames(false)) if (set.contains(name)) result.add(name); if (result.size() != set.size()) throw new RuntimeException( "Unknown update site in " + set.toString() + " (known: " + result.toString() + ")"); return result; } public boolean hasUploadableSites() { for (final UpdateSite site : updateSites.values()) if (site.isActive() && site.isUploadable()) return true; return false; } public boolean hasUpdateSitesChanges() { return updateSitesChanged; } public void setUpdateSitesChanged(boolean updateSitesChanged) { this.updateSitesChanged = updateSitesChanged; } /** * Deactivates the given update site. * * @param site the site to deactivate * @return the number of files marked for update/install/uninstall */ public int deactivateUpdateSite(final UpdateSite site) { if (!site.isActive()) return 0; final List<FileObject> list = new ArrayList<FileObject>(); final String updateSite = site.getName(); for (final FileObject file : forUpdateSite(updateSite)) { list.add(file); } for (final FileObject file : list) { file.removeFromUpdateSite(updateSite, this); } site.setActive(false); return list.size(); } /** * Activate the given update site. * * @param updateSite the update site to activate * @param progress the object to display the progress * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public void activateUpdateSite(final UpdateSite updateSite, final Progress progress) throws ParserConfigurationException, IOException, SAXException { if (updateSite.isActive()) return; updateSite.setActive(true); reReadUpdateSite(updateSite.getName(), progress); markForUpdate(updateSite.getName(), false); } private void markForUpdate(final String updateSite, final boolean evenForcedUpdates) { for (final FileObject file : forUpdateSite(updateSite)) { if ((file.isUpdateable(evenForcedUpdates) || file.getStatus() .isValid(Action.INSTALL)) && file.isUpdateablePlatform(this)) { file.setFirstValidAction(this, Action.UPDATE, Action.UNINSTALL, Action.INSTALL); } } } public void reReadUpdateSite(final String name, final Progress progress) throws ParserConfigurationException, IOException, SAXException { new XMLFileReader(this).read(name); final List<String> filesFromSite = new ArrayList<String>(); for (final FileObject file : forUpdateSite(name)) filesFromSite.add(file.localFilename != null ? file.localFilename : file.filename); final Checksummer checksummer = new Checksummer(this, progress); checksummer.updateFromLocal(filesFromSite); } public String protocolsMissingUploaders(final UploaderService uploaderService, final Progress progress) { final Map<String, Set<String>> map = new LinkedHashMap<String, Set<String>>(); for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) { final UpdateSite site = entry.getValue(); if (!site.isUploadable()) continue; final String protocol = site.getUploadProtocol(); try { uploaderService.installUploader(protocol, this, progress); } catch (IllegalArgumentException e) { Set<String> set = map.get(protocol); if (set == null) { set = new LinkedHashSet<String>(); map.put(protocol, set); } set.add(entry.getKey()); } } if (map.size() == 0) return null; final StringBuilder builder = new StringBuilder(); builder.append(prefixUpdate("").isDirectory() ? "Uploads via these protocols require a restart:\n" : "Missing uploaders:\n"); for (final Map.Entry<String, Set<String>> entry : map.entrySet()) { final String list = Arrays.toString(entry.getValue().toArray()); builder.append("'").append(entry.getKey()).append("': ").append(list).append("\n"); } return builder.toString(); } public Set<GroupAction> getValidActions() { final Set<GroupAction> actions = new LinkedHashSet<GroupAction>(); actions.add(new KeepAsIs()); boolean hasChanges = hasChanges(), hasUploadOrRemove = hasUploadOrRemove(); if (!hasUploadOrRemove) { actions.add(new InstallOrUpdate()); } if (hasUploadOrRemove || !hasChanges) { final Collection<String> siteNames = getSiteNamesToUpload(); final Map<String, UpdateSite> updateSites; if (siteNames.size() == 0) updateSites = this.updateSites; else { updateSites = new LinkedHashMap<String, UpdateSite>(); for (final String name : siteNames) { updateSites.put(name, getUpdateSite(name, true)); } } for (final UpdateSite updateSite : getUpdateSites(false)) { if (updateSite.isUploadable()) { final String name = updateSite.getName(); actions.add(new Upload(name)); actions.add(new Remove(name)); } } } if (!hasUploadOrRemove) { actions.add(new Uninstall()); } return actions; } public Set<GroupAction> getValidActions(final Iterable<FileObject> selected) { final Set<GroupAction> actions = getValidActions(); for (final Iterator<GroupAction> iter = actions.iterator(); iter.hasNext(); ) { final GroupAction action = iter.next(); for (final FileObject file : selected) { if (!action.isValid(this, file)) { iter.remove(); break; } } } return actions; } @Deprecated public Action[] getActions(final FileObject file) { return file.isUploadable(this, false) ? file.getStatus().getDeveloperActions() : file.getStatus().getActions(); } @Deprecated public Action[] getActions(final Iterable<FileObject> files) { List<Action> result = null; for (final FileObject file : files) { final Action[] actions = getActions(file); if (result == null) { result = new ArrayList<Action>(); for (final Action action : actions) result.add(action); } else { final Set<Action> set = new TreeSet<Action>(); for (final Action action : actions) set.add(action); final Iterator<Action> iter = result.iterator(); while (iter.hasNext()) if (!set.contains(iter.next())) iter.remove(); } } if (result == null) { return new Action[0]; } return result.toArray(new Action[result.size()]); } public void read() throws IOException, ParserConfigurationException, SAXException { read(prefix(UpdaterUtil.XML_COMPRESSED)); } public void read(final File file) throws IOException, ParserConfigurationException, SAXException { read(new FileInputStream(file)); } public void read(final FileInputStream in) throws IOException, ParserConfigurationException, SAXException { new XMLFileReader(this).read(in); in.close(); } public void write() throws IOException, SAXException, TransformerConfigurationException { final File out = prefix(UpdaterUtil.XML_COMPRESSED); final File tmp = prefix(UpdaterUtil.XML_COMPRESSED + ".tmp"); new XMLFileWriter(this).write(new GZIPOutputStream( new FileOutputStream(tmp)), true); if (out.exists() && !out.delete()) out.renameTo(prefix(UpdaterUtil.XML_COMPRESSED + ".backup")); tmp.renameTo(out); setUpdateSitesChanged(false); } public interface Filter { boolean matches(FileObject file); } public FilesCollection clone(final Iterable<FileObject> iterable) { final FilesCollection result = new FilesCollection(imagejRoot); for (final FileObject file : iterable) result.add(file); for (final String name : updateSites.keySet()) result.updateSites.put(name, (UpdateSite) updateSites.get(name).clone()); return result; } public Iterable<FileObject> toUploadOrRemove() { return filter(or(is(Action.UPLOAD), is(Action.REMOVE))); } public Iterable<FileObject> toUpload() { return toUpload(false); } public Iterable<FileObject> toUpload(final boolean includeMetadataChanges) { if (!includeMetadataChanges) return filter(is(Action.UPLOAD)); return filter(or(is(Action.UPLOAD), new Filter() { @Override public boolean matches(final FileObject file) { return file.metadataChanged && file.isUploadable(FilesCollection.this, false); } })); } public Iterable<FileObject> toUpload(final String updateSite) { return filter(and(is(Action.UPLOAD), isUpdateSite(updateSite))); } public Iterable<FileObject> toUninstall() { return filter(is(Action.UNINSTALL)); } public Iterable<FileObject> toRemove() { return filter(is(Action.REMOVE)); } public Iterable<FileObject> toUpdate() { return filter(is(Action.UPDATE)); } public Iterable<FileObject> upToDate() { return filter(is(Action.INSTALLED)); } public Iterable<FileObject> toInstall() { return filter(is(Action.INSTALL)); } public Iterable<FileObject> toInstallOrUpdate() { return filter(oneOf(Action.INSTALL, Action.UPDATE)); } public Iterable<FileObject> notHidden() { return filter(and(not(is(Status.OBSOLETE_UNINSTALLED)), doesPlatformMatch())); } public Iterable<FileObject> uninstalled() { return filter(is(Status.NOT_INSTALLED)); } public Iterable<FileObject> installed() { return filter(not(oneOf(Status.LOCAL_ONLY, Status.NOT_INSTALLED))); } public Iterable<FileObject> locallyModified() { return filter(oneOf(Status.MODIFIED, Status.OBSOLETE_MODIFIED)); } public Iterable<FileObject> forUpdateSite(final String name) { return forUpdateSite(name, false); } public Iterable<FileObject> forUpdateSite(final String name, boolean includeObsoletes) { Filter filter = and(doesPlatformMatch(), isUpdateSite(name)); if (!includeObsoletes) { filter = and(not(is(Status.OBSOLETE_UNINSTALLED)), filter); return filter(filter); } // make sure that overridden records are kept List<FileObject> result = new ArrayList<FileObject>(); for (FileObject file : this) { if (filter.matches(file)) result.add(file); else { FileObject overridden = file.overriddenUpdateSites.get(name); if (overridden != null) result.add(overridden); } } return result; } public Iterable<FileObject> managedFiles() { return filter(not(is(Status.LOCAL_ONLY))); } public Iterable<FileObject> localOnly() { return filter(is(Status.LOCAL_ONLY)); } public Iterable<FileObject> shownByDefault() { /* * Let's not show the NOT_INSTALLED ones, as the user chose not * to have them. */ final Status[] oneOf = { Status.UPDATEABLE, Status.NEW, Status.OBSOLETE, Status.OBSOLETE_MODIFIED }; return filter(or(oneOf(oneOf), oneOf(Action.INSTALL, Action.UPDATE, Action.UNINSTALL))); } public Iterable<FileObject> uploadable() { return uploadable(false); } /** * Gets the list of uploadable files. * * @param assumeModified true if we want the potentially uploadable files if * they (or their metadata) were to be changed. * @return the list of uploadable files */ public Iterable<FileObject> uploadable(final boolean assumeModified) { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUploadable(FilesCollection.this, assumeModified); } }); } public Iterable<FileObject> changes() { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() != file.getStatus().getNoAction(); } }); } public static class FilteredIterator implements Iterator<FileObject> { Filter filter; boolean opposite; Iterator<FileObject> iterator; FileObject next; FilteredIterator(final Filter filter, final Iterable<FileObject> files) { this.filter = filter; iterator = files.iterator(); findNext(); } @Override public boolean hasNext() { return next != null; } @Override public FileObject next() { final FileObject file = next; findNext(); return file; } @Override public void remove() { throw new UnsupportedOperationException(); } protected void findNext() { while (iterator.hasNext()) { next = iterator.next(); if (filter.matches(next)) return; } next = null; } } public static Iterable<FileObject> filter(final Filter filter, final Iterable<FileObject> files) { return new Iterable<FileObject>() { @Override public Iterator<FileObject> iterator() { return new FilteredIterator(filter, files); } }; } public static Iterable<FileObject> filter(final String search, final Iterable<FileObject> files) { final String keyword = search.trim().toLowerCase(); return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getFilename().trim().toLowerCase().indexOf(keyword) >= 0; } }, files); } public Filter yes() { return new Filter() { @Override public boolean matches(final FileObject file) { return true; } }; } public Filter doesPlatformMatch() { // If we're a developer or no platform was specified, return yes if (hasUploadableSites()) return yes(); return new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateablePlatform(FilesCollection.this); } }; } public Filter is(final Action action) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == action; } }; } public Filter isNoAction() { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == file.getStatus().getNoAction(); } }; } public Filter oneOf(final Action... actions) { final Set<Action> oneOf = new HashSet<Action>(); for (final Action action : actions) oneOf.add(action); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getAction()); } }; } public Filter is(final Status status) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getStatus() == status; } }; } public Filter hasMetadataChanges() { return new Filter() { @Override public boolean matches(final FileObject file) { return file.metadataChanged; } }; } public Filter isUpdateSite(final String updateSite) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.updateSite != null && // is null for local-only files file.updateSite.equals(updateSite); } }; } public Filter oneOf(final Status... states) { final Set<Status> oneOf = new HashSet<Status>(); for (final Status status : states) oneOf.add(status); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getStatus()); } }; } public Filter startsWith(final String prefix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.startsWith(prefix); } }; } public Filter startsWith(final String... prefixes) { return new Filter() { @Override public boolean matches(final FileObject file) { for (final String prefix : prefixes) if (file.filename.startsWith(prefix)) return true; return false; } }; } public Filter endsWith(final String suffix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.endsWith(suffix); } }; } public Filter not(final Filter filter) { return new Filter() { @Override public boolean matches(final FileObject file) { return !filter.matches(file); } }; } public Filter or(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) || b.matches(file); } }; } public Filter and(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) && b.matches(file); } }; } public Iterable<FileObject> filter(final Filter filter) { return filter(filter, this); } public FileObject getFileFromDigest(final String filename, final String digest) { for (final FileObject file : this) if (file.getFilename().equals(filename) && file.getChecksum().equals(digest)) return file; return null; } public Iterable<String> analyzeDependencies(final FileObject file) { try { if (dependencyAnalyzer == null) dependencyAnalyzer = new DependencyAnalyzer(imagejRoot); return dependencyAnalyzer.getDependencies(imagejRoot, file); } catch (final IOException e) { log.error(e); return null; } } public void updateDependencies(final FileObject file) { final Iterable<String> dependencies = analyzeDependencies(file); if (dependencies == null) return; for (final String dependency : dependencies) file.addDependency(dependency, prefix(dependency)); } public boolean has(final Filter filter) { for (final FileObject file : this) if (filter.matches(file)) return true; return false; } public boolean hasChanges() { return changes().iterator().hasNext(); } public boolean hasUploadOrRemove() { return has(oneOf(Action.UPLOAD, Action.REMOVE)); } public boolean hasForcableUpdates() { for (final FileObject file : updateable(true)) if (!file.isUpdateable(false)) return true; return false; } public Iterable<FileObject> updateable(final boolean evenForcedOnes) { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateable(evenForcedOnes) && file.isUpdateablePlatform(FilesCollection.this); } }); } public void markForUpdate(final boolean evenForcedUpdates) { for (final FileObject file : updateable(evenForcedUpdates)) { file.setFirstValidAction(this, Action.UPDATE, Action.UNINSTALL, Action.INSTALL); } } public String getURL(final FileObject file) { final String siteName = file.updateSite; assert (siteName != null && !siteName.equals("")); final UpdateSite site = getUpdateSite(siteName, false); if (site == null) return null; return site.getURL() + file.filename.replace(" ", "%20") + "-" + file.getTimestamp(); } public static class DependencyMap extends HashMap<FileObject, FilesCollection> { // returns true when the map did not have the dependency before public boolean add(final FileObject dependency, final FileObject dependencee) { if (containsKey(dependency)) { get(dependency).add(dependencee); return false; } final FilesCollection list = new FilesCollection(null); list.add(dependencee); put(dependency, list); return true; } } void addDependencies(final FileObject file, final DependencyMap map, final boolean overriding) { for (final Dependency dependency : file.getDependencies()) { final FileObject other = get(dependency.filename); if (other == null || overriding != dependency.overrides || !other.isUpdateablePlatform(this)) continue; if (other.isObsolete() && other.willNotBeInstalled()) { log.warn("Ignoring obsolete dependency " + dependency.filename + " of " + file.filename); continue; } if (dependency.overrides) { if (other.willNotBeInstalled()) continue; } else if (other.willBeUpToDate()) continue; if (!map.add(other, file)) continue; // overriding dependencies are not recursive if (!overriding) addDependencies(other, map, overriding); } } /** * Gets a map listing all the dependencees of files to be installed or * updated. * * @param overridingOnes * whether to include files that override a particular dependency * @return the map */ public DependencyMap getDependencies(final boolean overridingOnes) { return getDependencies(toInstallOrUpdate(), overridingOnes); } /** * Gets a map listing all the dependencees of the specified files. * * @param files * the dependencies * @param overridingOnes * whether to include files that override a particular dependency * @return the map */ public DependencyMap getDependencies(final Iterable<FileObject> files, final boolean overridingOnes) { final DependencyMap result = new DependencyMap(); for (final FileObject file : files) addDependencies(file, result, overridingOnes); return result; } public void sort() { // first letters in this order: 'C', 'I', 'f', 'p', 'j', 's', 'i', 'm', 'l, final ArrayList<FileObject> files = new ArrayList<FileObject>(); for (final FileObject file : this) { files.add(file); } Collections.sort(files, new Comparator<FileObject>() { @Override public int compare(final FileObject a, final FileObject b) { final int result = firstChar(a) - firstChar(b); return result != 0 ? result : a.filename.compareTo(b.filename); } int firstChar(final FileObject file) { final char c = file.filename.charAt(0); final int index = "CIfpjsim".indexOf(c); return index < 0 ? 0x200 + c : index; } }); this.clear(); for (final FileObject file : files) { super.put(file.filename, file); } } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen, final String updateSite) { if (seen.contains(file)) return ""; final String result = checkForCircularDependency(file, seen, new HashSet<FileObject>(), updateSite); if (result == null) return ""; // Display only the circular dependency final int last = result.lastIndexOf(' '); final int off = result.lastIndexOf(result.substring(last), last - 1); return "Circular dependency detected: " + result.substring(off + 1) + "\n"; } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen, final Set<FileObject> chain, final String updateSite) { if (seen.contains(file)) return null; for (final String dependency : file.dependencies.keySet()) { final FileObject dep = get(dependency); if (dep == null) continue; if (updateSite != null && !updateSite.equals(dep.updateSite)) continue; if (chain.contains(dep)) return " " + dependency; chain.add(dep); final String result = checkForCircularDependency(dep, seen, chain, updateSite); seen.add(dep); if (result != null) return " " + dependency + " ->" + result; chain.remove(dep); } return null; } /* returns null if consistent, error string when not */ public String checkConsistency() { final Collection<String> uploadSiteNames = getSiteNamesToUpload(); final String uploadSiteName = uploadSiteNames.isEmpty() ? null : uploadSiteNames.iterator().next(); final StringBuilder result = new StringBuilder(); final Set<FileObject> circularChecked = new HashSet<FileObject>(); for (final FileObject file : this) { if (uploadSiteName != null && !uploadSiteName.equals(file.updateSite)) { continue; } result.append(checkForCircularDependency(file, circularChecked, uploadSiteName)); // only non-obsolete components can have dependencies final Set<String> deps = file.dependencies.keySet(); if (deps.size() > 0 && file.isObsolete() && file.getAction() != Action.UPLOAD) { result.append("Obsolete file " + file + " has dependencies: " + UpdaterUtil.join(", ", deps) + "!\n"); } for (final String dependency : deps) { final FileObject dep = get(dependency); if (dep == null || dep.current == null) result.append("The file " + file + " has the obsolete/local-only " + "dependency " + dependency + "!\n"); } } return result.length() > 0 ? result.toString() : null; } public File prefix(final FileObject file) { return prefix(file.getFilename()); } public File prefix(final String path) { final File file = new File(path); if (file.isAbsolute()) return file; assert (imagejRoot != null); return new File(imagejRoot, path); } public File prefixUpdate(final String path) { return prefix("update/" + path); } public boolean fileExists(final String filename) { return prefix(filename).exists(); } @Override public String toString() { return UpdaterUtil.join(", ", this); } @Deprecated public FileObject get(final int index) { throw new UnsupportedOperationException(); } public void add(final FileObject file) { super.put(file.getFilename(true), file); } @Override public FileObject get(final Object filename) { return super.get(FileObject.getFilename((String)filename, true)); } @Override public FileObject put(final String key, final FileObject file) { throw new UnsupportedOperationException(); } @Override public FileObject remove(final Object file) { if (file instanceof FileObject) super.remove(((FileObject) file).getFilename(true)); if (file instanceof String) return super.remove(FileObject.getFilename((String)file, true)); return null; } @Override public Iterator<FileObject> iterator() { final Iterator<Map.Entry<String, FileObject>> iterator = entrySet().iterator(); return new Iterator<FileObject>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public FileObject next() { return iterator.next().getValue(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public String downloadIndexAndChecksum(final Progress progress) throws ParserConfigurationException, SAXException { try { read(); } catch (final FileNotFoundException e) { if (prefix("plugins/Fiji_Updater.jar").exists()) { // make sure that the Fiji update site is enabled UpdateSite fiji = getUpdateSite("Fiji", true); if (fiji == null) { addUpdateSite("Fiji", "http://fiji.sc/update/", null, null, 0); } } } catch (final IOException e) { /* ignore */ } // clear the files clear(); final XMLFileDownloader downloader = new XMLFileDownloader(this); downloader.addProgress(progress); try { downloader.start(false); } catch (final UpdateCanceledException e) { downloader.done(); throw e; } new Checksummer(this, progress).updateFromLocal(); // When upstream fixed dependencies, heed them for (final FileObject file : upToDate()) { for (final FileObject dependency : file.getFileDependencies(this, false)) { if (dependency.getAction() == Action.NOT_INSTALLED && dependency.isUpdateablePlatform(this)) { dependency.setAction(this, Action.INSTALL); } } } return downloader.getWarnings(); } public List<Conflict> getConflicts() { return conflicts; } /** * Utility method for Fiji's Bug Submitter * * @return the list of files known to the Updater, with versions, as a String */ public static String getInstalledVersions(final File ijDirectory, final Progress progress) { final StringBuilder sb = new StringBuilder(); final FilesCollection files = new FilesCollection(ijDirectory); try { files.read(); } catch (Exception e) { sb.append("Error while reading db.xml.gz: ").append(e.getMessage()).append("\n\n"); } final Checksummer checksummer = new Checksummer(files, progress); try { checksummer.updateFromLocal(); } catch (UpdateCanceledException t) { return null; } final Map<String, FileObject.Version> checksums = checksummer.getCachedChecksums(); sb.append("Activated update sites:\n"); for (final UpdateSite site : files.getUpdateSites(false)) { sb.append(site.getName()).append(": ").append(site.getURL()) .append(" (last check:").append(site.getTimestamp()) .append(")\n"); } boolean notUpToDateShown = false; for (final Map.Entry<String, FileObject.Version> entry : checksums.entrySet()) { String file = entry.getKey(); if (file.startsWith(":") && file.length() == 41) continue; final FileObject fileObject = files.get(file); if (fileObject != null && fileObject.getStatus() == Status.INSTALLED) continue; if (!notUpToDateShown) { sb.append("\nFiles not up-to-date:\n"); notUpToDateShown = true; } final FileObject.Version version = entry.getValue(); String checksum = version.checksum; if (version.checksum != null && version.checksum.length() > 8) { final StringBuilder rebuild = new StringBuilder(); for (final String element : checksum.split(":")) { if (rebuild.length() > 0) rebuild.append(":"); if (element == null || element.length() <= 8) rebuild.append(element); else rebuild.append(element.substring(0, 8)); } checksum = rebuild.toString(); } sb.append(" ").append(checksum).append(" "); if (fileObject != null) sb.append("(").append(fileObject.getStatus()).append(") "); sb.append(version.timestamp).append(" "); sb.append(file).append("\n"); } return sb.toString(); } public Collection<String> getProtocols(Iterable<FileObject> selected) { final Set<String> protocols = new LinkedHashSet<String>(); for (final FileObject file : selected) { final UpdateSite site = getUpdateSite(file.updateSite, false); if (site != null) { if (site.getHost() == null) protocols.add("unknown(" + file.filename + ")"); else protocols.add(site.getUploadProtocol()); } } return protocols; } }
package net.md_5.bungee.command; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.ChatColor; public class CommandEnd extends Command { @Override public void execute(CommandSender sender, String[] args) { if (!(sender instanceof ConsoleCommandSender)) { sender.sendMessage(ChatColor.RED + "Only the console can use this command"); } BungeeCord.instance.stop(); } }
package net.reini.rabbitmq.cdi; import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.annotation.PostConstruct; import javax.enterprise.event.Event; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Address; import com.rabbitmq.client.MessageProperties; /** * <p> * Binds incoming CDI events to queues and outgoing CDI events to exchanges of a broker. * </p> * * <p> * Inherit from this class and override its {@link #bindEvents()} method to create bindings. * </p> * * <p> * <b>Queue example:</b> * </p> * * <pre> * protected void bindEvents() { * bind(MyEventOne.class).toQueue(&quot;myQueueOne&quot;); * bind(MyEventTwo.class).toQueue(&quot;myQueueTwo&quot;).autoAck(); * } * </pre> * * <p> * <b>Exchange example:</b> * </p> * * <pre> * protected void bindEvents() { * bind(MyEvent.class).toExchange(&quot;myExchange&quot;).withRoutingKey(&quot;myRoutingKey&quot;) * .withPublisherTransactions(); * bind(MyEvent.class).toExchange(&quot;myExchange&quot;).withRoutingKey(&quot;myRoutingKey&quot;) * .withEncoder(new MyCustomEncoder()).withPublisherTransactions(); * } * </pre> * * <p> * To initialize the event bindings, inject the instance of this class and call {@link #initialize}. * In a web application, you would normally do this in a context listener on application startup * <b>after</b> your CDI framework was initialized. * </p> * * @author Patrick Reinhart */ @Singleton public abstract class EventBinder { private static final Logger LOGGER = LoggerFactory.getLogger(EventBinder.class); private final Set<QueueBinding<?>> queueBindings; private final Set<ExchangeBinding<?>> exchangeBindings; @Inject private Event<Object> remoteEventControl; @Inject private Instance<Object> remoteEventPool; @Inject private EventPublisher eventPublisher; @Inject private ConnectionProducer connectionProducer; private ConsumerContainer consumerContainer; private BinderConfiguration configuration; public EventBinder() { exchangeBindings = new HashSet<>(); queueBindings = new HashSet<>(); } /** * Extend {@link EventBinder} and implement this method to create the event bindings for your * application. * <p> * * <b>Binder example:</b> * * <pre> * public class MyEventBinder extends EventBinder { * &#064;Override * protected void bindEvents() { * bind(MyEvent.class).toExchange(&quot;my.exchange&quot;).withRoutingKey(&quot;my.routing.Key&quot;) * .withDecoder(new MyDecoder()); * } * } * </pre> */ protected abstract void bindEvents(); /** * Returns the configuration object for the event binder, in order to configure the connection * specific part. * <p> * * <b>Configuration example:</b> * * <pre> * binder.configuration().setHost("somehost.somedomain").setUsername("user") * .setPassword("password"); * </pre> * * @return the configuration object */ public BinderConfiguration configuration() { return configuration; } /** * Initializes the event binder and effectively enables all bindings created in * {@link #bindEvents()}. * <p> * * Inject your event binder implementation at the beginning of your application's life cycle and * call this method. In web applications, a good place for this is a ServletContextListener. * * <p> * After this method was successfully called, consumers are registered at the target broker for * every queue binding. Also, for every exchange binding messages are going to be published to the * target broker. * * @throws IOException if the initialization failed due to a broker related issue */ public void initialize() throws IOException { bindEvents(); processQueueBindings(); consumerContainer.startAllConsumers(); processExchangeBindings(); } @PostConstruct void initializeConsumerContainer() { consumerContainer = new ConsumerContainer(connectionProducer); configuration = new BinderConfiguration(); } void processExchangeBindings() { for (ExchangeBinding<?> exchangeBinding : exchangeBindings) { bindExchange(exchangeBinding); } exchangeBindings.clear(); } void processQueueBindings() { for (QueueBinding<?> queueBinding : queueBindings) { bindQueue(queueBinding); } queueBindings.clear(); } void bindQueue(QueueBinding<?> queueBinding) { @SuppressWarnings("unchecked") Event<Object> eventControl = (Event<Object>) remoteEventControl.select(queueBinding.eventType); @SuppressWarnings("unchecked") Instance<Object> eventPool = (Instance<Object>) remoteEventPool.select(queueBinding.eventType); EventConsumer consumer = new EventConsumer(queueBinding.decoder, queueBinding.autoAck, eventControl, eventPool); consumerContainer.addConsumer(consumer, queueBinding.queue, queueBinding.autoAck); LOGGER.info("Binding between queue {} and event type {} activated", queueBinding.queue, queueBinding.eventType.getSimpleName()); } void bindExchange(ExchangeBinding<?> exchangeBinding) { PublisherConfiguration cfg = new PublisherConfiguration(exchangeBinding.exchange, exchangeBinding.routingKey, exchangeBinding.persistent, exchangeBinding.basicProperties, exchangeBinding.encoder); eventPublisher.addEvent(exchangeBinding.eventType, cfg); LOGGER.info("Binding between exchange {} and event type {} activated", exchangeBinding.exchange, exchangeBinding.eventType.getSimpleName()); } /** * Starting point for binding an event. * * <p> * <b>Binding fired events to be published to an exchange:</b> * <p> * bind(MyEvent.class).toExchange("my.exchange"); * <p> * <b>Binding consuming from a queue to fire an event:</b> * <p> * bind(MyEvent.class).toQueue("my.queue"); * * @param event The event * @return The binding builder */ public <M> EventBindingBuilder<M> bind(Class<M> event) { return new EventBindingBuilder<>(event); } public final class EventBindingBuilder<T> { private final Class<T> eventType; EventBindingBuilder(Class<T> eventType) { this.eventType = eventType; } /** * Binds an event to the given queue. On initialization, a consumer is going to be registered at * the broker that is going to fire an event of the bound event type for every consumed message. * * @param queue The queue * @return the queue binding */ public QueueBinding<T> toQueue(String queue) { return new QueueBinding<>(eventType, queue); } /** * Binds an event to the given exchange. After initialization, all fired events of the bound * event type are going to be published to the exchange. * * @param exchange The exchange * @return the exchange binding */ public ExchangeBinding<T> toExchange(String exchange) { return new ExchangeBinding<>(eventType, exchange); } } /** * Configures and stores the binding between and event class and a queue. */ public final class QueueBinding<T> { private final Class<T> eventType; private final String queue; private boolean autoAck; private Decoder<T> decoder; QueueBinding(Class<T> eventType, String queue) { this.eventType = eventType; this.queue = queue; this.decoder = new JsonDecoder<>(eventType); queueBindings.add(this); LOGGER.info("Binding created between queue {} and event type {}", queue, eventType.getSimpleName()); } /** * <p> * Sets the acknowledgement mode to be used for consuming message to automatic acknowledges * (auto acks). * </p> * * <p> * If auto acks is enabled, messages are delivered by the broker to its consumers in a * fire-and-forget manner. The broker removes a message from the queue as soon as its is * delivered to the consumer and does not care about whether the consumer successfully processes * this message or not. * </p> * * @return the queue binding */ public QueueBinding<T> autoAck() { this.autoAck = true; LOGGER.info("Auto acknowledges enabled for event type {}", eventType.getSimpleName()); return this; } /** * Sets the message decoder to be used for message decoding. * * @param messageDecoder The message decoder instance * @return the queue binding */ public QueueBinding<T> withDecoder(Decoder<T> messageDecoder) { this.decoder = messageDecoder; LOGGER.info("Decoder set to {} for event type {}", messageDecoder, eventType.getSimpleName()); return this; } } /** * Configures and stores the binding between an event class and an exchange. */ public final class ExchangeBinding<T> { private final Class<T> eventType; private final String exchange; private boolean persistent; private String routingKey; private Encoder<T> encoder; private AMQP.BasicProperties basicProperties; ExchangeBinding(Class<T> eventType, String exchange) { basicProperties = MessageProperties.BASIC; this.eventType = eventType; this.exchange = exchange; exchangeBindings.add(this); LOGGER.info("Binding created between exchange {} and event type {}", exchange, eventType.getSimpleName()); } /** * Sets the routing key to be used for message publishing. * * @param key The routing key * @return the exchange binding */ public ExchangeBinding<T> withRoutingKey(String key) { this.routingKey = key; LOGGER.info("Routing key for event type {} set to {}", eventType.getSimpleName(), key); return this; } /** * Sets the message encoder to be used for message encoding. * * @param messageEncoder The message encoder instance * @return the exchange binding */ public ExchangeBinding<T> withEncoder(Encoder<T> messageEncoder) { this.encoder = messageEncoder; LOGGER.info("Encoder for event type {} set to {}", eventType.getSimpleName(), encoder.getClass().getName()); return this; } /** * Sets the given basic properties to be used for message publishing. * * @param properties The basic properties * @return the exchange binding */ public ExchangeBinding<T> withProperties(AMQP.BasicProperties properties) { this.basicProperties = properties; LOGGER.info("Publisher properties for event type {} set to {}", eventType.getSimpleName(), properties.toString()); return this; } } public final class BinderConfiguration { /** * Adds a broker host name used when establishing a connection. * * @param hostName a broker host name without a port * @return the binder configuration object */ public BinderConfiguration setHost(String hostName) { connectionProducer.getConnectionFactory().setHost(hostName); return this; } /** * Set the user name. * * @param username the AMQP user name to use when connecting to the broker * @return the binder configuration object */ public BinderConfiguration setUsername(String username) { connectionProducer.getConnectionFactory().setUsername(username); return this; } /** * Set the password. * * @param password the password to use when connecting to the broker * @return the binder configuration object */ public BinderConfiguration setPassword(String password) { connectionProducer.getConnectionFactory().setPassword(password); return this; } /** * Set the virtual host. * * @param virtualHost the virtual host to use when connecting to the broker * @return the binder configuration object */ public BinderConfiguration setVirtualHost(String virtualHost) { connectionProducer.getConnectionFactory().setVirtualHost(virtualHost); return this; } /** * Adds a broker host address used when establishing a connection. * * @param hostAddress the broker host address * @return the binder configuration object */ public BinderConfiguration addHost(Address hostAddress) { connectionProducer.getBrokerHosts().add(hostAddress); return this; } } }
package net.sf.kerner.utils.math; import java.util.Arrays; import java.util.List; import net.sf.kerner.utils.counter.Counter; public class MathUtils { private MathUtils() { } /** * Round a floating point number ({@code double}) with an accuracy up to * given decimal place. * * @param number * {@code double} that is rounded to given decimal place * @param decimalPlace * decimal place to which given {@code double} is rounded * @return rounded {@code double} */ public static double round(double number, int decimalPlace) { int n = decimalPlace; Counter c = new Counter(); while (n > 10) { n = n / 10; c.count(); } decimalPlace = decimalPlace + c.getCount(); // System.out.println("number: " + number + ", digits: " + // decimalPlace); final double factor = Math.pow(10, decimalPlace); final double result = Math.round(number * factor) / factor; // System.out.println("result: " + result); return result; } public static int max(Integer... values) { int result = Integer.MIN_VALUE; for (int i : values) { if (i > result) result = i; } return result; } public static int min(Integer... values) { int result = Integer.MAX_VALUE; for (int i : values) { if (i < result) result = i; } return result; } public static double average(Double... values) { return average(Arrays.asList(values)); } public static double average(List<Double> values) { return sum(values) / values.size(); } public static double sum(List<Double> values) { double result = 0; for (Double d : values) { // Ignore null values if(d != null) result += d; } return result; } public static double sum(Double... values) { return sum(Arrays.asList(values)); } }
package net.sf.kerner.utils.math; import net.sf.kerner.utils.counter.Counter; public class MathUtils { private MathUtils() { } /** * Round a floating point number ({@code double}) with an accuracy up to * given decimal place. * * @param number * {@code double} that is rounded to given decimal place * @param decimalPlace * decimal place to which given {@code double} is rounded * @return rounded {@code double} */ public static double round(double number, int decimalPlace) { int n = decimalPlace; Counter c = new Counter(); while (n > 10) { n = n / 10; c.count(); } decimalPlace = decimalPlace + c.getCount(); // System.out.println("number: " + number + ", digits: " + // decimalPlace); final double factor = Math.pow(10, decimalPlace); final double result = Math.round(number * factor) / factor; // System.out.println("result: " + result); return result; } public static int max(Integer... values) { int result = Integer.MIN_VALUE; for (int i : values) { if (i > result) result = i; } return result; } public static int min(Integer... values) { int result = Integer.MAX_VALUE; for (int i : values) { if (i < result) result = i; } return result; } public static double average(Double... values) { return sum(values) / values.length; } public static double sum(Double... values) { double result = 0; for (double d : values) { result += d; } return result; } }
package no.sonat.battleships; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import no.sonat.battleships.models.Coordinate; import no.sonat.battleships.models.Ship; import no.sonat.battleships.models.ShootMessage; import no.sonat.battleships.models.SetShipMessage; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_10; import org.java_websocket.drafts.Draft_76; import org.java_websocket.handshake.ServerHandshake; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; public class VeryDumbRobot { final ObjectMapper json = new ObjectMapper(); final String token; WebSocketClient wsClient; public VeryDumbRobot(String token) throws Exception { this.token = token; } public void initiate() throws URISyntaxException { System.out.println("befor connect"); Map<String, String> headers = new HashMap<String, String>(){{ put("Authorization", "Bearer " + token); }}; this.wsClient = new WebSocketClient(new URI("ws://localhost:9000/connect"), new Draft_10(), headers, 500) { @Override public void onOpen(ServerHandshake serverHandshake) { System.out.println("Connected!"); } @Override public void onMessage(String s) { System.out.println(String.format("message received: %1$s", s)); final JsonNode msg; try { msg = json.readTree(s); } catch (IOException e) { throw new RuntimeException("error reading json", e); } final String type = msg.get("class").asText(); switch (type) { case "game.broadcast.GameIsInPlanningMode": placeShips(); break; case "game.broadcast.GameIsStarted": onGameStart(msg); break; case "game.messages.ItsYourTurnMessage": shoot(); break; case "game.broadcast.GameOver": // allright!! be ready for next game break; default: break; } } @Override public void onClose(int i, String s, boolean b) { System.out.println("Disconnected!"); } @Override public void onError(Exception e) { System.out.println("onError"); System.out.println(e.getMessage()); } }; wsClient.connect(); } public void placeShips() { SetShipMessage ship1 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(2,2), new Coordinate(2,3)})); SetShipMessage ship2 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(4,4), new Coordinate(4,5), new Coordinate(4,6)})); SetShipMessage ship3 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,1), new Coordinate(9,1), new Coordinate(10, 1)})); SetShipMessage ship4 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(1,1), new Coordinate(2,1), new Coordinate(3,1), new Coordinate(4,1)})); SetShipMessage ship5 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,5), new Coordinate(9,5), new Coordinate(10,5), new Coordinate(11,5)})); SetShipMessage ship6 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(11,7), new Coordinate(11,8),new Coordinate(11,9), new Coordinate(11,10), new Coordinate(11, 11)})); try { wsClient.send(json.writeValueAsString(ship1)); wsClient.send(json.writeValueAsString(ship2)); wsClient.send(json.writeValueAsString(ship3)); wsClient.send(json.writeValueAsString(ship4)); wsClient.send(json.writeValueAsString(ship5)); wsClient.send(json.writeValueAsString(ship6)); } catch (Exception e) { throw new RuntimeException("marshalling failure", e); } } final List<Coordinate> availableCoordinates = new ArrayList<>(); final Random rand = new Random(); public void onGameStart(JsonNode msg) { // if another game is finished, available coordinates might still contain old data. Clear it and refill it. availableCoordinates.clear(); for (int x = 0; x < 12; x++) { for (int y = 0; y < 12; y++) { availableCoordinates.add(new Coordinate(x, y)); } } } public void shoot() { int idx = rand.nextInt(availableCoordinates.size()); Coordinate coord = availableCoordinates.get(idx); availableCoordinates.remove(idx); ShootMessage shootMessage = new ShootMessage(coord); try { wsClient.send(json.writeValueAsString(shootMessage)); } catch (JsonProcessingException e) { throw new RuntimeException("Error marshalling object", e); } } }
package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.type.algebra.AbsoluteValue; import nom.bdezonia.zorbage.type.algebra.Group; import nom.bdezonia.zorbage.type.algebra.ModularDivision; import nom.bdezonia.zorbage.type.algebra.Multiplication; import nom.bdezonia.zorbage.type.algebra.Ordered; /** * Least Common Multiple algorithm * * @author Barry DeZonia * */ public class Lcm { /** * Do not instantiate. Private constructor for utility class. */ private Lcm() {} /** * Sets the result to the least common multiple of a and b. Result is always nonnegative. * * @param group * @param a * @param b * @param result */ public static <T extends Group<T,U> & AbsoluteValue<U> & ModularDivision<U> & Multiplication<U> & Ordered<U>, U> void compute(T group, U a, U b, U result) { U gcd = group.construct(); U a1 = group.construct(); U b1 = group.construct(); Gcd.compute(group, a, b, gcd); group.div(a, gcd, a1); group.div(b, gcd, b1); group.abs(a1, a1); group.abs(b1, b1); group.multiply(a1, b1, result); group.multiply(result, gcd, result); } }
package org.basex.examples.api; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class BaseXClient { /** UTF-8 charset. */ static final Charset UTF8 = Charset.forName("UTF-8"); /** Event notifications. */ final Map<String, EventNotifier> notifiers = new HashMap<String, EventNotifier>(); /** Output stream. */ final OutputStream out; /** Socket. */ final Socket socket; /** Cache. */ final BufferedInputStream in; /** Command info. */ String info; /** Socket event reference. */ Socket esocket; /** Socket host name. */ String ehost; /** * Constructor. * @param host server name * @param port server port * @param usern user name * @param pw password * @throws IOException Exception */ public BaseXClient(final String host, final int port, final String usern, final String pw) throws IOException { socket = new Socket(); socket.connect(new InetSocketAddress(host, port), 5000); in = new BufferedInputStream(socket.getInputStream()); out = socket.getOutputStream(); ehost = host; // receive timestamp final String ts = receive(); // send {Username}0 and hashed {Password/Timestamp}0 send(usern); send(md5(md5(pw) + ts)); // receive success flag if(!ok()) throw new IOException("Access denied."); } /** * Executes a command and serializes the result to an output stream. * @param cmd command * @param o output stream * @throws IOException Exception */ public void execute(final String cmd, final OutputStream o) throws IOException { // send {Command}0 send(cmd); receive(in, o); info = receive(); if(!ok()) throw new IOException(info); } /** * Executes a command and returns the result. * @param cmd command * @return result * @throws IOException Exception */ public String execute(final String cmd) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); execute(cmd, os); return new String(os.toByteArray(), UTF8); } /** * Creates a query object. * @param query query string * @return query * @throws IOException Exception */ public Query query(final String query) throws IOException { return new Query(query); } /** * Creates a database. * @param name name of database * @param input xml input * @throws IOException I/O exception */ public void create(final String name, final InputStream input) throws IOException { send(8, name, input); } /** * Adds a document to a database. * @param path path to document * @param input xml input * @throws IOException I/O exception */ public void add(final String path, final InputStream input) throws IOException { send(9, path, input); } /** * Replaces a document in a database. * @param path path to document * @param input xml input * @throws IOException I/O exception */ public void replace(final String path, final InputStream input) throws IOException { send(12, path, input); } /** * Stores a binary resource in a database. * @param path path to document * @param input xml input * @throws IOException I/O exception */ public void store(final String path, final InputStream input) throws IOException { send(13, path, input); } /** * Watches an event. * @param name event name * @param notifier event notification * @throws IOException I/O exception */ public void watch(final String name, final EventNotifier notifier) throws IOException { out.write(10); if(esocket == null) { final int eport = Integer.parseInt(receive()); // initialize event socket esocket = new Socket(); esocket.connect(new InetSocketAddress(ehost, eport), 5000); final OutputStream os = esocket.getOutputStream(); receive(in, os); os.write(0); os.flush(); final InputStream is = esocket.getInputStream(); is.read(); listen(is); } send(name); info = receive(); if(!ok()) throw new IOException(info); notifiers.put(name, notifier); } /** * Unwatches an event. * @param name event name * @throws IOException I/O exception */ public void unwatch(final String name) throws IOException { out.write(11); send(name); info = receive(); if(!ok()) throw new IOException(info); notifiers.remove(name); } /** * Returns command information. * @return string info */ public String info() { return info; } /** * Closes the session. * @throws IOException Exception */ public void close() throws IOException { send("exit"); out.flush(); if(esocket != null) esocket.close(); socket.close(); } /** * Checks the next success flag. * @return value of check * @throws IOException Exception */ boolean ok() throws IOException { out.flush(); return in.read() == 0; } /** * Returns the next received string. * @return String result or info * @throws IOException I/O exception */ String receive() throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); receive(in, os); return new String(os.toByteArray(), UTF8); } /** * Sends a string to the server. * @param s string to be sent * @throws IOException I/O exception */ void send(final String s) throws IOException { out.write((s + '\0').getBytes(UTF8)); } /** * Receives a string and writes it to the specified output stream. * @param is input stream * @param os output stream * @throws IOException I/O exception */ static void receive(final InputStream is, final OutputStream os) throws IOException { for(int b; (b = is.read()) > 0;) { // read next byte if 0xFF is received os.write(b == 0xFF ? is.read() : b); } } /** * Sends a command, argument, and input. * @param cmd command * @param path path to document * @param input xml input * @throws IOException I/O exception */ private void send(final int cmd, final String path, final InputStream input) throws IOException { out.write(cmd); send(path); send(input); } /** * Starts the listener thread. * @param is input stream */ private void listen(final InputStream is) { final BufferedInputStream bi = new BufferedInputStream(is); new Thread() { @Override public void run() { try { while(true) { ByteArrayOutputStream os = new ByteArrayOutputStream(); receive(bi, os); final String name = new String(os.toByteArray(), UTF8); os = new ByteArrayOutputStream(); receive(bi, os); final String data = new String(os.toByteArray(), UTF8); notifiers.get(name).notify(data); } } catch(final IOException ex) { /* ignored */ } } }.start(); } /** * Sends an input stream to the server. * @param input xml input * @throws IOException I/O exception */ private void send(final InputStream input) throws IOException { final BufferedInputStream bis = new BufferedInputStream(input); final BufferedOutputStream bos = new BufferedOutputStream(out); for(int b; (b = bis.read()) != -1;) { // 0x00 and 0xFF will be prefixed by 0xFF if(b == 0x00 || b == 0xFF) bos.write(0xFF); bos.write(b); } bos.write(0); bos.flush(); info = receive(); if(!ok()) throw new IOException(info); } /** * Returns an MD5 hash. * @param pw String * @return String */ private static String md5(final String pw) { final StringBuilder sb = new StringBuilder(); try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pw.getBytes()); for(final byte b : md.digest()) { final String s = Integer.toHexString(b & 0xFF); if(s.length() == 1) sb.append('0'); sb.append(s); } } catch(final NoSuchAlgorithmException ex) { // should not occur ex.printStackTrace(); } return sb.toString(); } /** * Inner class for iterative query execution. */ public class Query { /** Query id. */ private final String id; /** Cached results. */ private ArrayList<byte[]> cache; /** Cache pointer. */ private int pos; /** * Standard constructor. * @param query query string * @throws IOException I/O exception */ public Query(final String query) throws IOException { id = exec(0, query); } /** * Binds a variable. * @param name name of variable * @param value value * @throws IOException I/O exception */ public void bind(final String name, final String value) throws IOException { exec(3, id + '\0' + name + '\0' + value + '\0'); } /** * Checks for the next item. * @return result of check * @throws IOException I/O exception */ public boolean more() throws IOException { if(cache == null) { out.write(4); send(id); cache = new ArrayList<byte[]>(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); while(in.read() > 0) { receive(in, os); cache.add(os.toByteArray()); os.reset(); } if(!ok()) throw new IOException(receive()); } return pos < cache.size(); } /** * Returns the next item. * @return item string * @throws IOException I/O Exception */ public String next() throws IOException { return more() ? new String(cache.set(pos++, null), UTF8) : null; } /** * Returns the whole result of the query. * @return query result * @throws IOException I/O Exception */ public String execute() throws IOException { return exec(5, id); } /** * Returns query info in a string. * @return query info * @throws IOException I/O exception */ public String info() throws IOException { return exec(6, id); } /** * Returns serialization parameters in a string. * @return query info * @throws IOException I/O exception */ public String options() throws IOException { return exec(7, id); } /** * Closes the query. * @throws IOException I/O exception */ public void close() throws IOException { exec(2, id); } /** * Executes the specified command. * @param cmd command * @param arg argument * @return resulting string * @throws IOException I/O exception */ private String exec(final int cmd, final String arg) throws IOException { out.write(cmd); send(arg); final String s = receive(); if(!ok()) throw new IOException(receive()); return s; } } /** * Interface for event notifications. */ public interface EventNotifier { /** * Invoked when a database event was fired. * @param value event string */ void notify(final String value); } }
package org.dlw.ai.blackboard.rule; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.OneToMany; /** * This interface defines the signature knowledge source object. Any default * implementation e.g. * {@link org.dlw.ai.blackboard.knowledge.primitive.CommonPrefixKnowledgeSource} * extends {@link InferenceEngine} ultimately through the implementation of this * interface and the extension {@link org.dlw.ai.blackboard.BlackboardContext} * directly within the implementation. * * @author <a href="mailto:dlwhitehurst@gmail.com">David L. Whitehurst</a> * @version 1.0.0-RC (hibernate-mysql branch) * */ @Entity @Table(name="ruleset") public class RuleSet { /** * unique serial identifier */ private static final long serialVersionUID = 3094361637466019949L; /** * Attribute id or primary key */ private Long id; /** * Attribute name of KnowledgeSource (type extension) */ private String name; /** * Attribute to hold rules for KnowledgeSource */ private List<Rule> rules = new ArrayList<Rule>(); /** * @param rules * the rules to set */ public void setRules(List<Rule> rules) { this.rules = rules; } /** * @return the rules */ @OneToMany(mappedBy="rset") public List<Rule> getRules() { return rules; } /** * @return the id */ @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the name */ @Column(name="name",nullable=false,length=50) public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } }
package org.jfrog.hudson; import hudson.model.Item; import org.apache.commons.lang.StringUtils; import org.jfrog.hudson.util.Credentials; import org.jfrog.hudson.util.plugins.PluginsUtils; import org.kohsuke.stapler.DataBoundConstructor; import java.io.Serializable; /** * Configuration for all available credentials providers - Legacy credentials method or credentials plugin * Each call for username/password should go through here and this object will provide the username/password * according to the global configuration objects which will configured with the "useCredentialsPlugin" property * * @author Aviad Shikloshi */ public class CredentialsConfig implements Serializable { public static final CredentialsConfig EMPTY_CREDENTIALS_CONFIG = new CredentialsConfig(new Credentials(StringUtils.EMPTY, StringUtils.EMPTY), StringUtils.EMPTY, false); private Credentials credentials; private String credentialsId; private Boolean overridingCredentials; private boolean ignoreCredentialPluginDisabled; //We need this for the pipeline flow we can set credentials although the credentials plugin is disabled /** * Constructed from the build configuration (Maven, Gradle, Ivy, Freestyle, etc) * This object obtains the username, password and credentials id (used with the Credentials plugin) * Each of these properties could be empty string if not specified but not null * * @param username legacy username from textbox * @param password legacy password from textbox * @param credentialsId credentialsId chosen from the select box */ @DataBoundConstructor public CredentialsConfig(String username, String password, String credentialsId, Boolean overridingCredentials) { this.overridingCredentials = overridingCredentials == null ? false : overridingCredentials; if (overridingCredentials == null || overridingCredentials.equals(Boolean.TRUE)) { this.credentials = new Credentials(username, password); this.credentialsId = credentialsId; } } public CredentialsConfig(String username, String password, String credentialsId) { this.overridingCredentials = false; this.ignoreCredentialPluginDisabled = StringUtils.isNotEmpty(credentialsId); this.credentials = new Credentials(username, password); this.credentialsId = credentialsId; } public CredentialsConfig(Credentials credentials, String credentialsId, boolean overridingCredentials) { this.credentials = credentials; this.credentialsId = credentialsId; this.overridingCredentials = overridingCredentials; } public void deleteCredentials() { this.credentials = new Credentials(StringUtils.EMPTY, StringUtils.EMPTY); } /** * In case of overriding the global configuration this method should be called to check if override credentials were supplied * from configuration - this will take under consideration the state of the "useCredentialsPlugin" option in global config object * * s@return in legacy mode this will return true if username and password both supplied * In Credentials plugin mode this will return true if a credentials id was selected in the job configuration */ public boolean isCredentialsProvided() { if (PluginsUtils.isCredentialsPluginEnabled() || ignoreCredentialPluginDisabled) { return StringUtils.isNotBlank(credentialsId); } return overridingCredentials; } /** * Not like getUsername this will return the username of the current Credentials mode of the system (legacy/credentials plugin) * * @return the username that should be apply in this configuration */ public String provideUsername(Item item) { return isUsingCredentialsPlugin() ? PluginsUtils.credentialsLookup(credentialsId, item).getUsername() : credentials.getUsername(); } /** * Not like getPassword this will return the username of the current Credentials mode of the system (legacy/credentials plugin) * * @return the password that should be apply in this configuration */ public String providePassword(Item item) { return isUsingCredentialsPlugin() ? PluginsUtils.credentialsLookup(credentialsId, item).getPassword() : credentials.getPassword(); } public Credentials getCredentials(Item item) { return isUsingCredentialsPlugin() ? PluginsUtils.credentialsLookup(credentialsId, item) : credentials; } // NOTE: These getters are not part of the API, but used by Jenkins Jelly for displaying values on user interface // This should not be used in order to retrieve credentials in the configuration - Use provideUsername, providePassword instead public String getUsername() { if (credentials == null) { return StringUtils.EMPTY; } return credentials.getUsername(); } public String getPassword() { if (credentials == null) { return StringUtils.EMPTY; } return credentials.getPassword(); } public String getCredentialsId() { return credentialsId; } public boolean isOverridingCredentials() { return overridingCredentials; } public boolean isIgnoreCredentialPluginDisabled() { return ignoreCredentialPluginDisabled; } public void setIgnoreCredentialPluginDisabled(boolean ignoreCredentialPluginDisabled) { this.ignoreCredentialPluginDisabled = ignoreCredentialPluginDisabled; } public boolean isUsingCredentialsPlugin() { return (PluginsUtils.isCredentialsPluginEnabled() && StringUtils.isNotEmpty(credentialsId)) || ignoreCredentialPluginDisabled; } }
package org.jshint.data; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class ES5IdentifierNames { private ES5IdentifierNames() {}; private static final Pattern pattern; static { try ( InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("es5-identifier-names.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ) { String str = reader.readLine(); pattern = Pattern.compile(str); } catch (IOException e) { throw new RuntimeException("Cannot load resource file!"); } } public static boolean test(String value) { return pattern.matcher(StringUtils.defaultString(value)).find(); } }
package org.lantern.network; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.netty.util.internal.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Singleton; /** * <p> * This singleton is responsible for tracking information about the physical * Lantern network as well as the trust network that's used to build it. * </p> * * <p> * Core Concepts: * </p> * * <ul> * <li>instanceId: Identifies a Lantern instance in some consistent and unique * way. In practice, this is currently the Jabber ID.</li> * <li>Instance online/offline: we're told of this as we learn about instances * being online or offline (e.g. via KScope ad)</li> * <li>User trusted/untrusted: we're told of this as the friends list changes</li> * <li>Certificate received: we're told of this as certificates are received</li> * </ul> * * @param <U> * Type of object identifying users * @param <I> * Type of object identifying instances * @param <D> * Type of object representing additional data stored in * {@link InstanceInfo}s */ @Singleton public class NetworkTracker<U, I, D> { private static final Logger LOG = LoggerFactory .getLogger(NetworkTracker.class); private final Map<I, Certificate> trustedCertificatesByInstance = new ConcurrentHashMap<I, Certificate>(); private final Map<U, Map<I, InstanceInfo<I, D>>> onlineInstancesByAdvertisingUser = new ConcurrentHashMap<U, Map<I, InstanceInfo<I, D>>>(); private final Set<U> trustedUsers = Collections .synchronizedSet(new HashSet<U>()); private final List<NetworkTrackerListener<I, D>> listeners = new ArrayList<NetworkTrackerListener<I, D>>(); private volatile Set<InstanceInfo<I, D>> trustedOnlineInstances; public NetworkTracker() { identifyTrustedOnlineInstances(); } /** * Add a {@link NetworkTrackerListener} to listen for events from this * tracker. * * @param listener */ public void addListener( NetworkTrackerListener<I, D> listener) { this.listeners.add(listener); } /** * Tell the {@link NetworkTracker} that an instance went online. * * @param advertisingUser * the user who told us this instance is online * @param instanceId * @param instanceInfo * @return true if NetworkTracker didn't already know that this instance is * online. */ public boolean instanceOnline(U advertisingUser, I instanceId, InstanceInfo<I, D> instanceInfo) { LOG.debug("instanceOnline: {}", instanceInfo); boolean instanceIsNew = false; synchronized (onlineInstancesByAdvertisingUser) { Map<I, InstanceInfo<I, D>> userInstances = onlineInstancesByAdvertisingUser .get(advertisingUser); if (userInstances == null) { userInstances = new ConcurrentHashMap<I, InstanceInfo<I, D>>(); instanceIsNew = onlineInstancesByAdvertisingUser.put( advertisingUser, userInstances) == null; } userInstances.put(instanceId, instanceInfo); } reevaluateTrustedOnlineInstances(); LOG.debug("New instance? {}", instanceIsNew); return instanceIsNew; } public void instanceOffline(U advertisingUser, I instanceId) { LOG.debug("instanceOffline: {}", instanceId); synchronized (onlineInstancesByAdvertisingUser) { Map<I, InstanceInfo<I, D>> userInstances = onlineInstancesByAdvertisingUser .get(advertisingUser); if (userInstances != null) { userInstances.remove(instanceId); } } reevaluateTrustedOnlineInstances(); } public void userTrusted(U userId) { LOG.debug("userTrusted: {}", userId); trustedUsers.add(userId); reevaluateTrustedOnlineInstances(); } public void userUntrusted(U userId) { LOG.debug("userUntrusted: {}", userId); trustedUsers.remove(userId); reevaluateTrustedOnlineInstances(); } public void certificateTrusted(I instanceId, Certificate certificate) { LOG.debug("certificateReceived: {} {}", instanceId, certificate); trustedCertificatesByInstance.put(instanceId, certificate); reevaluateTrustedOnlineInstances(); } /** * Returns a list of all instances that are currently trusted, including * their certificates. * * @return */ public Set<InstanceInfo<I, D>> getTrustedOnlineInstances() { return trustedOnlineInstances; } /** * Re-evalute which certificates and instances are trusted and notify * listeners. */ private void reevaluateTrustedOnlineInstances() { Set<InstanceInfo<I, D>> originalTrustedOnlineInstances = trustedOnlineInstances; identifyTrustedOnlineInstances(); notifyListenersAboutInstances(originalTrustedOnlineInstances); } private void notifyListenersAboutInstances( Set<InstanceInfo<I, D>> originalTrustedOnlineInstances) { Set<InstanceInfo<I, D>> addedOnlineInstances = new HashSet<InstanceInfo<I, D>>( trustedOnlineInstances); Set<InstanceInfo<I, D>> removedOnlineInstances = new HashSet<InstanceInfo<I, D>>( originalTrustedOnlineInstances); addedOnlineInstances.removeAll(originalTrustedOnlineInstances); removedOnlineInstances.removeAll(trustedOnlineInstances); for (InstanceInfo<I, D> instance : addedOnlineInstances) { LOG.debug("Online trusted instance added: {}", instance); for (NetworkTrackerListener<I, D> listener : listeners) { listener.instanceOnlineAndTrusted(instance); } } for (InstanceInfo<I, D> instance : removedOnlineInstances) { LOG.debug("Online trusted instance removed: {}", instance); for (NetworkTrackerListener<I, D> listener : listeners) { listener.instanceOfflineOrUntrusted(instance); } } } /** * <p> * Determines all trusted online instances. * </p> * * <p> * Note - yes this is expensive, but we don't expect it to be on any * performance critical paths so it's not worth worrying about right now. * </p> * * @return */ private void identifyTrustedOnlineInstances() { Set<InstanceInfo<I, D>> currentTrustedOnlineInstances = Collections .synchronizedSet(new HashSet<InstanceInfo<I, D>>()); for (Map.Entry<U, Map<I, InstanceInfo<I, D>>> userInstancesEntry : onlineInstancesByAdvertisingUser .entrySet()) { U userId = userInstancesEntry.getKey(); if (trustedUsers.contains(userId)) { Map<I, InstanceInfo<I, D>> instances = userInstancesEntry .getValue(); for (InstanceInfo<I, D> instance : instances.values()) { I instanceId = instance.getId(); if (trustedCertificatesByInstance.containsKey(instanceId)) { currentTrustedOnlineInstances.add(instance); } } } } this.trustedOnlineInstances = currentTrustedOnlineInstances; LOG.debug("Number of trusted online instances: {}", trustedOnlineInstances.size()); } }
package org.lightmare.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.lightmare.utils.StringUtils; /** * Defines unit name of {@link javax.persistence.Entity} class for scanning on * start time * * @author Levan * @since 0.0.16-SNAPSHOT */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface UnitName { String value() default StringUtils.EMPTY_STRING; }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Default location for configuration YAML file private static final String CONFIG_FILE = "./config/configuration.yaml"; // Is configuration server or client (default is server) // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Resource path private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(Config.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(Config.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value); } contains = containsConfigKey(Config.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.PORT.key, Config.PORT.value); } contains = containsConfigKey(Config.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value); } contains = containsConfigKey(Config.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * (Integer) Config.WORKER_POOL.value; String workerProperty = String.valueOf(workers); setConfigValue(Config.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.CONNECTION_TIMEOUT.key, Config.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ @SuppressWarnings("unchecked") public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(Config.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value; setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return (String) Config.ADMIN_USER_PATH.value; } public static void setAdminUsersPath(String adminUserPath) { Config.ADMIN_USERS_PATH.value = adminUserPath; } public boolean isRemote() { return (Boolean) Config.REMOTE.value; } public void setRemote(boolean remote) { Config.REMOTE.value = remote; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(Config.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(Config.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(Config.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(Config.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(Config.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(Config.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(Config.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(Config.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(Config.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(Config.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(Config.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.nanopub; import static org.nanopub.Nanopub.NANOPUB_TYPE_URI; import static org.nanopub.Nanopub.HAS_ASSERTION_URI; import static org.nanopub.Nanopub.HAS_PROVENANCE_URI; import static org.nanopub.Nanopub.HAS_PUBINFO_URI; import static org.nanopub.Nanopub.NANOPUBCOLL_TYPE_URI; import static org.nanopub.Nanopub.HAS_ASSERTIONSET_URI; import static org.nanopub.Nanopub.HAS_COLLPROVENANCE_URI; import static org.nanopub.Nanopub.HAS_COLLPUBINFO_URI; import static org.nanopub.Nanopub.HAS_MEMBER; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.RDFHandlerBase; /** * Handles files or streams with a sequence of nanopubs. This class also handles nanopublication * collections (they are on the fly transformed to proper nanopubs). * * @author Tobias Kuhn */ public class MultiNanopubRdfHandler extends RDFHandlerBase { public static void process(RDFFormat format, InputStream in, NanopubHandler npHandler) throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException { process(format, in, null, npHandler); } public static void process(RDFFormat format, File file, NanopubHandler npHandler) throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException { InputStream in; if (file.getName().matches(".*\\.(gz|gzip)")) { in = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); } else { in = new BufferedInputStream(new FileInputStream(file)); } process(format, in, file, npHandler); } public static void process(File file, NanopubHandler npHandler) throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException { RDFFormat format = Rio.getParserFormatForFileName(file.getName(), RDFFormat.TRIG); process(format, file, npHandler); } private static void process(RDFFormat format, InputStream in, File file, NanopubHandler npHandler) throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException { RDFParser p = NanopubUtils.getParser(format); p.setRDFHandler(new MultiNanopubRdfHandler(npHandler)); try { p.parse(in, ""); } catch (RuntimeException ex) { if ("wrapped MalformedNanopubException".equals(ex.getMessage()) && ex.getCause() instanceof MalformedNanopubException) { throw (MalformedNanopubException) ex.getCause(); } else { throw ex; } } finally { in.close(); } } private NanopubHandler npHandler; private URI headUri = null; private URI nanopubUri = null; private URI nanopubCollUri = null; private URI nanopubCollAssertionUri = null; private URI nanopubAssertionSetUri = null; private URI nanopubCollProvenanceUri = null; private URI nanopubCollPubInfoUri = null; private boolean headComplete = false; private Map<URI,Boolean> graphs = new HashMap<>(); private Map<URI,Map<URI,Boolean>> members = new HashMap<>(); private Set<Statement> statements = new HashSet<>(); private Set<Statement> collAssertionStatements = new HashSet<>(); private List<String> nsPrefixes = new ArrayList<>(); private Map<String,String> ns = new HashMap<>(); private List<String> newNsPrefixes = new ArrayList<>(); private List<String> newNs = new ArrayList<>(); public MultiNanopubRdfHandler(NanopubHandler npHandler) { this.npHandler = npHandler; } @Override public void handleStatement(Statement st) throws RDFHandlerException { if (!headComplete) { if (headUri == null) { headUri = (URI) st.getContext(); graphs.put(headUri, true); } if (headUri.equals(st.getContext())) { URI p = st.getPredicate(); if (p.equals(RDF.TYPE) && st.getObject().equals(NANOPUB_TYPE_URI)) { nanopubUri = (URI) st.getSubject(); } if (p.equals(RDF.TYPE) && st.getObject().equals(NANOPUBCOLL_TYPE_URI)) { nanopubCollUri = (URI) st.getSubject(); } if (p.equals(HAS_ASSERTION_URI) || p.equals(HAS_PROVENANCE_URI) || p.equals(HAS_PUBINFO_URI)) { graphs.put((URI) st.getObject(), true); } if (p.equals(HAS_ASSERTIONSET_URI)) { nanopubAssertionSetUri = (URI) st.getObject(); } if (p.equals(HAS_COLLPROVENANCE_URI)) { nanopubCollProvenanceUri = (URI) st.getObject(); } if (p.equals(HAS_COLLPUBINFO_URI)) { nanopubCollPubInfoUri = (URI) st.getObject(); } if (p.equals(HAS_MEMBER)) { addMember((URI) st.getSubject(), (URI) st.getObject()); } } else { if (nanopubUri == null && nanopubCollUri == null) { throwMalformed("No nanopub (collection) URI found"); } else if (nanopubUri != null && nanopubCollUri != null) { throwMalformed("Nanopub URI and nanopub collection URI found"); } if (nanopubCollUri != null && nanopubAssertionSetUri == null) { throwMalformed("No assertion set found for nanopub collection"); } headComplete = true; } } if (headComplete) { if (nanopubUri != null) { if (!graphs.containsKey(st.getContext())) { finishAndReset(); handleStatement(st); } else { addNamespaces(); statements.add(st); } } else if (nanopubCollUri != null) { URI c = (URI) st.getContext(); if (members.get(nanopubAssertionSetUri).containsKey(c)) { if (nanopubCollAssertionUri != null && !c.equals(nanopubCollAssertionUri)) { finishNanopubFromCollection(); } nanopubCollAssertionUri = c; addNamespaces(); collAssertionStatements.add(st); } else if (nanopubCollAssertionUri == null) { if (!c.equals(nanopubCollProvenanceUri) && !c.equals(nanopubCollPubInfoUri)) { throwMalformed("Nanopub URI and nanopub collection URI found"); } addNamespaces(); statements.add(st); } else { finishAndReset(); handleStatement(st); } } } else { addNamespaces(); statements.add(st); } } @Override public void handleNamespace(String prefix, String uri) throws RDFHandlerException { newNs.add(uri); newNsPrefixes.add(prefix); } public void addNamespaces() throws RDFHandlerException { for (int i = 0 ; i < newNs.size() ; i++) { String prefix = newNsPrefixes.get(i); String nsUri = newNs.get(i); nsPrefixes.remove(prefix); nsPrefixes.add(prefix); ns.put(prefix, nsUri); } newNs.clear(); newNsPrefixes.clear(); } @Override public void endRDF() throws RDFHandlerException { finishAndReset(); } private void finishAndReset() { try { if (nanopubCollUri != null) { finishNanopubFromCollection(); } else { npHandler.handleNanopub(new NanopubImpl(statements, nsPrefixes, ns)); } } catch (MalformedNanopubException ex) { throwMalformed(ex); } clearAll(); } private void finishNanopubFromCollection() { List<Statement> l = new ArrayList<>(); String s = nanopubCollAssertionUri.toString(); if (!s.matches(".*[^a-zA-Z]a") && !s.matches(".*[^a-zA-Z]assertion")) { throwMalformed("Invalid assertion set member URI: " + s); } s = s.replaceFirst("assertion$", "").replaceFirst("a$", ""); URI npUri = new URIImpl(s.replaceFirst("( URI head = new URIImpl(s + "head"); URI prov = new URIImpl(s + "prov"); URI info = new URIImpl(s + "info"); l.add(new ContextStatementImpl(npUri, RDF.TYPE, NANOPUB_TYPE_URI, head)); l.add(new ContextStatementImpl(npUri, HAS_ASSERTION_URI, nanopubCollAssertionUri, head)); l.add(new ContextStatementImpl(npUri, HAS_PROVENANCE_URI, prov, head)); l.add(new ContextStatementImpl(npUri, HAS_PUBINFO_URI, info, head)); l.addAll(collAssertionStatements); for (Statement st : statements) { Resource context = null; if (st.getContext().equals(nanopubCollProvenanceUri)) { context = prov; } else if (st.getContext().equals(nanopubCollPubInfoUri)) { context = info; } else if (st.getContext().equals(headUri)) { // ignore } else { throwMalformed("Unrecognized graph for statement: " + st); } if (context != null) { l.add(new ContextStatementImpl(st.getSubject(), st.getPredicate(), st.getObject(), context)); } } l.add(new ContextStatementImpl(nanopubAssertionSetUri, HAS_MEMBER, nanopubCollAssertionUri, prov)); l.add(new ContextStatementImpl(nanopubCollUri, HAS_MEMBER, npUri, info)); try { npHandler.handleNanopub(new NanopubImpl(l, nsPrefixes, ns)); } catch (MalformedNanopubException ex) { throwMalformed(ex); } // clear assertion graph: collAssertionStatements.clear(); members.get(nanopubAssertionSetUri).remove(nanopubCollAssertionUri); } private void clearAll() { headUri = null; nanopubUri = null; nanopubCollUri = null; nanopubCollAssertionUri = null; headComplete = false; graphs.clear(); members.clear(); statements.clear(); collAssertionStatements.clear(); } private void addMember(URI container, URI memberUri) { Map<URI,Boolean> m = members.get(container); if (m == null) { m = new HashMap<URI,Boolean>(); members.put(container, m); } m.put(memberUri, true); } private void throwMalformed(MalformedNanopubException ex) { throw new RuntimeException("wrapped MalformedNanopubException", ex); } private void throwMalformed(String message) { throw new RuntimeException("wrapped MalformedNanopubException", new MalformedNanopubException(message)); } public interface NanopubHandler { public void handleNanopub(Nanopub np); } }
package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.ThermometerPlot; import org.jfree.ui.RectangleInsets; /** * Tests for the {@link ThermometerPlot} class. */ public class ThermometerPlotTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ThermometerPlotTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ThermometerPlotTests(String name) { super(name); } /** * Some checks for the equals() method. */ public void testEquals() { ThermometerPlot p1 = new ThermometerPlot(); ThermometerPlot p2 = new ThermometerPlot(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); // padding p1.setPadding(new RectangleInsets(1.0, 2.0, 3.0, 4.0)); assertFalse(p1.equals(p2)); p2.setPadding(new RectangleInsets(1.0, 2.0, 3.0, 4.0)); assertTrue(p2.equals(p1)); // thermometerStroke BasicStroke s = new BasicStroke(1.23f); p1.setThermometerStroke(s); assertFalse(p1.equals(p2)); p2.setThermometerStroke(s); assertTrue(p2.equals(p1)); // thermometerPaint p1.setThermometerPaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.red)); assertFalse(p1.equals(p2)); p2.setThermometerPaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.red)); assertTrue(p2.equals(p1)); // units p1.setUnits(ThermometerPlot.UNITS_KELVIN); assertFalse(p1.equals(p2)); p2.setUnits(ThermometerPlot.UNITS_KELVIN); assertTrue(p2.equals(p1)); // valueLocation p1.setValueLocation(ThermometerPlot.LEFT); assertFalse(p1.equals(p2)); p2.setValueLocation(ThermometerPlot.LEFT); assertTrue(p2.equals(p1)); // axisLocation p1.setAxisLocation(ThermometerPlot.RIGHT); assertFalse(p1.equals(p2)); p2.setAxisLocation(ThermometerPlot.RIGHT); assertTrue(p2.equals(p1)); // valueFont p1.setValueFont(new Font("Serif", Font.PLAIN, 9)); assertFalse(p1.equals(p2)); p2.setValueFont(new Font("Serif", Font.PLAIN, 9)); assertTrue(p2.equals(p1)); // valuePaint p1.setValuePaint(new GradientPaint(4.0f, 5.0f, Color.red, 6.0f, 7.0f, Color.white)); assertFalse(p1.equals(p2)); p2.setValuePaint(new GradientPaint(4.0f, 5.0f, Color.red, 6.0f, 7.0f, Color.white)); assertTrue(p2.equals(p1)); // valueFormat p1.setValueFormat(new DecimalFormat("0.0000")); assertFalse(p1.equals(p2)); p2.setValueFormat(new DecimalFormat("0.0000")); assertTrue(p2.equals(p1)); // mercuryPaint p1.setMercuryPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertFalse(p1.equals(p2)); p2.setMercuryPaint(new GradientPaint(9.0f, 8.0f, Color.red, 7.0f, 6.0f, Color.blue)); assertTrue(p2.equals(p1)); // showValueLines p1.setShowValueLines(true); assertFalse(p1.equals(p2)); p2.setShowValueLines(true); assertTrue(p2.equals(p1)); p1.setSubrange(1, 1.0, 2.0); assertFalse(p1.equals(p2)); p2.setSubrange(1, 1.0, 2.0); assertTrue(p2.equals(p1)); p1.setSubrangePaint(1, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertFalse(p1.equals(p2)); p2.setSubrangePaint(1, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertTrue(p2.equals(p1)); p1.setBulbRadius(9); assertFalse(p1.equals(p2)); p2.setBulbRadius(9); assertTrue(p2.equals(p1)); p1.setColumnRadius(8); assertFalse(p1.equals(p2)); p2.setColumnRadius(8); assertTrue(p2.equals(p1)); p1.setGap(7); assertFalse(p1.equals(p2)); p2.setGap(7); assertTrue(p2.equals(p1)); } /** * Confirm that cloning works. */ public void testCloning() { ThermometerPlot p1 = new ThermometerPlot(); ThermometerPlot p2 = null; try { p2 = (ThermometerPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { ThermometerPlot p1 = new ThermometerPlot(); ThermometerPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (ThermometerPlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization2() { ThermometerPlot p1 = new ThermometerPlot(); p1.setSubrangePaint(1, new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); ThermometerPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (ThermometerPlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(p1.equals(p2)); } /** * Some checks for the setUnits() method. */ public void testSetUnits() { ThermometerPlot p1 = new ThermometerPlot(); assertEquals(ThermometerPlot.UNITS_CELCIUS, p1.getUnits()); p1.setUnits("FAHRENHEIT"); // this doesn't work assertEquals(ThermometerPlot.UNITS_CELCIUS, p1.getUnits()); p1.setUnits("\u00B0F"); // ...but this does! assertEquals(ThermometerPlot.UNITS_FAHRENHEIT, p1.getUnits()); } }
package org.osiam.client.oauth; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.util.HashSet; import java.util.Set; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.StatusType; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpResponse; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.RequestEntityProcessing; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.exception.AccessTokenValidationException; import org.osiam.client.exception.ConflictException; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.ForbiddenException; import org.osiam.client.exception.InvalidAttributeException; import org.osiam.client.exception.OAuthErrorMessage; import org.osiam.client.exception.UnauthorizedException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; /** * The AuthService provides access to the OAuth2 service used to authorize * requests. Please use the {@link AuthService.Builder} to construct one. */ public final class AuthService { // NOSONAR - Builder constructs instances of // this class private static final String BEARER = "Bearer "; private static final Charset CHARSET = Charset.forName("UTF-8"); private static final Client client = ClientBuilder.newClient(new ClientConfig() .connectorProvider(new ApacheConnectorProvider()) .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED)); private final String endpoint; private final String clientId; private final String clientSecret; private final String clientRedirectUri; private String scopes; private final String password; private final String userName; private GrantType grantType; private final WebTarget targetEndpoint; /** * The private constructor for the AuthService. Please use the * {@link AuthService.Builder} to construct one. * * @param builder * a valid Builder that holds all needed variables */ private AuthService(Builder builder) { endpoint = builder.endpoint; scopes = builder.scopes; grantType = builder.grantType; userName = builder.userName; password = builder.password; clientId = builder.clientId; clientSecret = builder.clientSecret; clientRedirectUri = builder.clientRedirectUri; targetEndpoint = client.target(endpoint); } /** * @see OsiamConnector#retrieveAccessToken() */ public AccessToken retrieveAccessToken() { if (grantType == GrantType.AUTHORIZATION_CODE) { throw new IllegalAccessError("For the grant type " + GrantType.AUTHORIZATION_CODE + " you need to retrieve a authentication code first."); } String authHeaderValue = "Basic " + encodeClientCredentials(); Form form = new Form(); form.param("scope", scopes); form.param("grant_type", grantType.getUrlParam()); // FIXME: grantType == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS if (grantType != GrantType.REFRESH_TOKEN) { if (userName != null) { form.param("username", userName); } if (password != null) { form.param("password", password); } } StatusType status; String content; try { Response response = targetEndpoint.path("/oauth/token").request(MediaType.APPLICATION_JSON) .header("Authorization", authHeaderValue) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException("Unable to retrieve access token.", e); } checkAndHandleResponse(content, status); return getAccessToken(content); } @Deprecated public AccessToken retrieveAccessToken(HttpResponse authCodeResponse) { String authCode = null; Header header = authCodeResponse.getLastHeader("Location"); HeaderElement[] elements = header.getElements(); for (HeaderElement actHeaderElement : elements) { if (actHeaderElement.getName().contains("code")) { authCode = actHeaderElement.getValue(); break; } if (actHeaderElement.getName().contains("error")) { throw new ForbiddenException("The user had denied the acces to his data."); } } if (authCode == null) { throw new InvalidAttributeException("Could not find any auth code or error message in the given Response"); } return retrieveAccessToken(authCode); } public AccessToken retrieveAccessToken(String authCode) { checkArgument(!Strings.isNullOrEmpty(authCode), "The given authentication code can't be null."); String authHeaderValue = "Basic " + encodeClientCredentials(); Form form = new Form(); form.param("code", authCode); form.param("grant_type", "authorization_code"); form.param("redirect_uri", clientRedirectUri); StatusType status; String content; try { Response response = targetEndpoint.path("/oauth/token").request(MediaType.APPLICATION_JSON) .header("Authorization", authHeaderValue) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException("Unable to retrieve access token.", e); } // TODO: consolidate with checkAndHandleResponse() if (status.getStatusCode() != Status.OK.getStatusCode()) { String errorMessage = extractErrorMessage(content, status); if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) { throw new ConflictException(errorMessage); } else { throw new ConnectionInitializationException(errorMessage); } } return getAccessToken(content); } /** * @see OsiamConnector#refreshAccessToken(AccessToken, Scope...) */ public AccessToken refreshAccessToken(AccessToken accessToken, Scope[] newScopes) { if (newScopes.length != 0) { StringBuilder stringBuilder = new StringBuilder(); for (Scope scope : newScopes) { stringBuilder.append(" ").append(scope.toString()); } // FIXME: changing the scope? AuthService should be immutable. scopes = stringBuilder.toString().trim(); } // FIXME: changing the grantType? AuthService should be immutable. grantType = GrantType.REFRESH_TOKEN; Form form = new Form(); form.param("scope", scopes); form.param("grant_type", grantType.getUrlParam()); // FIXME: should be a guard on method entry if (accessToken.getRefreshToken() == null) { throw new ConnectionInitializationException( "Unable to perform a refresh_token_grant request without refresh token."); } form.param("refresh_token", accessToken.getRefreshToken()); String authHeaderValue = "Basic " + encodeClientCredentials(); StatusType status; String content; try { Response response = targetEndpoint.path("/oauth/token").request(MediaType.APPLICATION_JSON) .header("Authorization", authHeaderValue) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException("Unable to retrieve access token.", e); } checkAndHandleResponse(content, status); return getAccessToken(content); } public URI getRedirectLoginUri() { if (grantType != GrantType.AUTHORIZATION_CODE) { throw new IllegalAccessError("You need to use the GrantType " + GrantType.AUTHORIZATION_CODE + " to be able to use this method."); } try { return UriBuilder.fromUri(endpoint).path("/oauth/authorize") .queryParam("client_id", clientId) .queryParam("response_type", "code") .queryParam("redirect_uri", clientRedirectUri) .queryParam("scope", scopes) .build(); } catch (UriBuilderException | IllegalArgumentException e) { // FIXME: must be replaced with a different exception throw new ConnectionInitializationException("Unable to create redirect URI", e); } } /** * @see OsiamConnector#validateAccessToken(AccessToken, AccessToken) */ public AccessToken validateAccessToken(AccessToken tokenToValidate, AccessToken tokenToAuthorize) { checkNotNull(tokenToValidate, "The tokenToValidate must not be null."); checkNotNull(tokenToAuthorize, "The tokenToAuthorize must not be null."); StatusType status; String content; try { Response response = targetEndpoint.path("/token/validation/").path(tokenToValidate.getToken()) .request(MediaType.APPLICATION_JSON) .header("Authorization", BEARER + tokenToAuthorize.getToken()) .post(null); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException("Unable to retrieve access token.", e); } if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) { String errorMessage = extractErrorMessage(content, status); throw new AccessTokenValidationException(errorMessage); } checkAndHandleResponse(content, status); return getAccessToken(content); } private String encodeClientCredentials() { String clientCredentials = clientId + ":" + clientSecret; clientCredentials = new String(Base64.encodeBase64(clientCredentials.getBytes(CHARSET)), CHARSET); return clientCredentials; } private void checkAndHandleResponse(String content, StatusType status) { if (status.getStatusCode() == Status.OK.getStatusCode()) { return; } final String errorMessage = extractErrorMessage(content, status); if (status.getStatusCode() == Status.UNAUTHORIZED.getStatusCode()) { throw new UnauthorizedException(errorMessage); } else { throw new ConnectionInitializationException(errorMessage); } } private String extractErrorMessage(String content, StatusType status) { try { OAuthErrorMessage error = new ObjectMapper().readValue(content, OAuthErrorMessage.class); return error.getDescription(); } catch (Exception e) { // NOSONAR - we catch everything String errorMessage = String.format("Could not deserialize the error response for the HTTP status '%s'.", status.getReasonPhrase()); if (content != null) { errorMessage += String.format(" Original response: %s", content); } return errorMessage; } } private AccessToken getAccessToken(String content) { try { return new ObjectMapper().readValue(content, AccessToken.class); } catch (IOException e) { // FIXME: replace with an other exception. IOExceptions means that // jackson could not map/parse json throw new ConnectionInitializationException("Unable to retrieve access token.", e); } catch (ProcessingException e) { throw new ConnectionInitializationException("Unable to retrieve access token.", e); } } /** <<<<<<< HEAD * @see OsiamConnector#refreshAccessToken(AccessToken, Scope...) */ public AccessToken refreshAccessToken(AccessToken accessToken, Scope[] scopes) { if (scopes.length != 0) { StringBuilder stringBuilder = new StringBuilder(); for (Scope scope : scopes) { stringBuilder.append(" ").append(scope.toString()); } this.scopes = stringBuilder.toString().trim(); } this.grantType = GrantType.REFRESH_TOKEN; HttpResponse response = performRequest(accessToken); int status = response.getStatusLine().getStatusCode(); checkAndHandleHttpStatus(response, status); return getAccessToken(response); } /** * @see OsiamConnector#validateAccessToken(AccessToken) */ public AccessToken validateAccessToken(AccessToken tokenToValidate) { if (tokenToValidate == null) { throw new IllegalArgumentException("The given accessToken can't be null."); } DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response; try { URI uri = new URI(endpoint + "/token/validation"); HttpPost realWebResource = new HttpPost(uri); realWebResource.addHeader(AUTHORIZATION, BEARER + tokenToValidate.getToken()); realWebResource.addHeader(ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); response = httpclient.execute(realWebResource); } catch (IOException | URISyntaxException e) { throw new ConnectionInitializationException("", e); } int httpStatus = response.getStatusLine().getStatusCode(); if (httpStatus == SC_UNAUTHORIZED) { String errorMessage = getErrorMessage(response); throw new AccessTokenValidationException(errorMessage); } checkAndHandleHttpStatus(response, httpStatus); return getAccessToken(response); } public static class Builder { private String clientId; private String clientSecret; private GrantType grantType; private String scopes; private String endpoint; private String password; private String userName; private String clientRedirectUri; /** * Set up the Builder for the construction of an {@link AuthService} * instance for the OAuth2 service at the given endpoint * * @param endpoint * The URL at which the OAuth2 service lives. */ public Builder(String endpoint) { this.endpoint = endpoint; } /** * Use the given {@link Scope} to for the request. * * @param scope * the needed scope * @param scopes * the needed scopes * @return The builder itself */ public Builder setScope(Scope scope, Scope... scopes) { Set<Scope> scopeSet = new HashSet<>(); scopeSet.add(scope); for (Scope actScope : scopes) { scopeSet.add(actScope); } if (scopeSet.contains(Scope.ALL)) { this.scopes = Scope.ALL.toString(); } else { StringBuilder scopeBuilder = new StringBuilder(); for (Scope actScope : scopeSet) { scopeBuilder.append(" ").append(actScope.toString()); } this.scopes = scopeBuilder.toString().trim(); } return this; } /** * The needed access token scopes as String like 'GET PATCH' * * @param scope * the needed scopes * @return The builder itself */ public Builder setScope(String scope) { scopes = scope; return this; } /** * Use the given {@link GrantType} to for the request. * * @param grantType * of the requested AuthCode * @return The builder itself */ public Builder setGrantType(GrantType grantType) { this.grantType = grantType; return this; } /** * Add a ClientId to the OAuth2 request * * @param clientId * The client-Id * @return The builder itself */ public Builder setClientId(String clientId) { this.clientId = clientId; return this; } /** * Add a Client redirect URI to the OAuth2 request * * @param clientRedirectUri * the clientRedirectUri which is known to the OSIAM server * @return The builder itself */ public Builder setClientRedirectUri(String clientRedirectUri) { this.clientRedirectUri = clientRedirectUri; return this; } /** * Add a clientSecret to the OAuth2 request * * @param clientSecret * The client secret * @return The builder itself */ public Builder setClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } /** * Add the given userName to the OAuth2 request * * @param userName * The userName * @return The builder itself */ public Builder setUsername(String userName) { this.userName = userName; return this; } /** * Add the given password to the OAuth2 request * * @param password * The password * @return The builder itself */ public Builder setPassword(String password) { this.password = password; return this; } /** * Construct the {@link AuthService} with the parameters passed to this * builder. * * @return An {@link AuthService} configured accordingly. */ public AuthService build() { ensureAllNeededParameterAreCorrect(); return new AuthService(this); } private void ensureAllNeededParameterAreCorrect() {// NOSONAR - this is // a test method the // Cyclomatic // Complexity // can be over 10. if (clientId == null || clientSecret == null) { throw new IllegalArgumentException("The provided client credentials are incomplete."); } if (scopes == null) { throw new IllegalArgumentException("At least one scope needs to be set."); } if (grantType == null) { throw new IllegalArgumentException("The grant type is not set."); } if (grantType.equals(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) && userName == null && password == null) { throw new IllegalArgumentException("The grant type 'password' requires username and password"); } if ((grantType.equals(GrantType.CLIENT_CREDENTIALS) || grantType.equals(GrantType.AUTHORIZATION_CODE)) && (userName != null || password != null)) { throw new IllegalArgumentException("For the grant type '" + grantType + "' setting of password and username are not allowed."); } if (grantType.equals(GrantType.AUTHORIZATION_CODE) && clientRedirectUri == null) { throw new IllegalArgumentException("For the grant type '" + grantType + "' the redirect Uri is needed."); } } } }
package org.smoothbuild.lang.parse.ast; import static java.lang.String.join; import static java.util.Collections.rotate; import static java.util.stream.Collectors.toSet; import static org.smoothbuild.cli.console.ImmutableLogs.logs; import static org.smoothbuild.cli.console.Log.error; import static org.smoothbuild.cli.console.Maybe.maybeLogs; import static org.smoothbuild.cli.console.Maybe.maybeValue; import static org.smoothbuild.util.collect.Lists.map; import static org.smoothbuild.util.collect.NamedList.namedList; import static org.smoothbuild.util.graph.SortTopologically.sortTopologically; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.smoothbuild.cli.console.Log; import org.smoothbuild.cli.console.Maybe; import org.smoothbuild.lang.base.define.Location; import org.smoothbuild.util.collect.NamedList; import org.smoothbuild.util.graph.GraphEdge; import org.smoothbuild.util.graph.GraphNode; import org.smoothbuild.util.graph.SortTopologically.TopologicalSortingResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; public class Ast { private final ImmutableList<StructNode> structs; private final ImmutableList<ReferencableNode> referencables; private NamedList<ReferencableNode> referencablesMap; private ImmutableMap<String, StructNode> structsMap; public Ast(List<StructNode> structs, List<ReferencableNode> referencables) { this.structs = ImmutableList.copyOf(structs); this.referencables = ImmutableList.copyOf(referencables); } public ImmutableList<ReferencableNode> referencables() { return referencables; } public ImmutableList<StructNode> structs() { return structs; } public NamedList<ReferencableNode> referencablesMap() { if (referencablesMap == null) { referencablesMap = createReferencablesMap(); } return referencablesMap; } private NamedList<ReferencableNode> createReferencablesMap() { var result = new HashMap<String, ReferencableNode>(); new AstVisitor() { @Override public void visitReferencable(ReferencableNode referencable) { super.visitReferencable(referencable); result.put(referencable.name(), referencable); } }.visitAst(this); return namedList(ImmutableMap.copyOf(result)); } public ImmutableMap<String, StructNode> structsMap() { if (structsMap == null) { structsMap = createStructsMap(); } return structsMap; } private ImmutableMap<String, StructNode> createStructsMap() { var builder = ImmutableMap.<String, StructNode>builder(); new AstVisitor() { @Override public void visitStruct(StructNode struct) { builder.put(struct.name(), struct); } }.visitAst(this); return builder.build(); } public Maybe<Ast> sortedByDependencies() { var sortedTypes = sortStructsByDependencies(); if (sortedTypes.sorted() == null) { Log error = createCycleError("Type hierarchy", sortedTypes.cycle()); return maybeLogs(logs(error)); } var sortedReferencables = sortReferencablesByDependencies(); if (sortedReferencables.sorted() == null) { Log error = createCycleError("Dependency graph", sortedReferencables.cycle()); return maybeLogs(logs(error)); } Ast ast = new Ast(sortedTypes.valuesReversed(), sortedReferencables.valuesReversed()); return maybeValue(ast); } private TopologicalSortingResult<String, ReferencableNode, Location> sortReferencablesByDependencies() { HashSet<String> names = new HashSet<>(); referencables.forEach(v -> names.add(v.name())); HashSet<GraphNode<String, ReferencableNode, Location>> nodes = new HashSet<>(); nodes.addAll(map(referencables, value -> referencableNodeToGraphNode(value, names))); return sortTopologically(nodes); } private static GraphNode<String, ReferencableNode, Location> referencableNodeToGraphNode( ReferencableNode referencable, Set<String> names) { Set<GraphEdge<Location, String>> dependencies = new HashSet<>(); new AstVisitor() { @Override public void visitRef(RefNode ref) { super.visitRef(ref); if (names.contains(ref.name())) { dependencies.add(new GraphEdge<>(ref.location(), ref.name())); } } }.visitReferencable(referencable); return new GraphNode<>(referencable.name(), referencable, ImmutableList.copyOf(dependencies)); } private TopologicalSortingResult<String, StructNode, Location> sortStructsByDependencies() { Set<String> structNames = structs.stream() .map(NamedNode::name) .collect(toSet()); var nodes = map(structs, struct -> structNodeToGraphNode(struct, structNames)); return sortTopologically(nodes); } private static GraphNode<String, StructNode, Location> structNodeToGraphNode( StructNode struct, Set<String> funcNames) { Set<GraphEdge<Location, String>> dependencies = new HashSet<>(); new AstVisitor() { @Override public void visitField(ItemNode field) { super.visitField(field); field.typeNode().ifPresent(this::addToDependencies); } private void addToDependencies(TypeNode type) { if (type instanceof ArrayTypeNode arrayType) { addToDependencies(arrayType.elementType()); } else if (type instanceof FunctionTypeNode functionType) { addToDependencies(functionType.resultType()); functionType.parameterTypes().forEach(this::addToDependencies); } else { if (funcNames.contains(type.name())) { dependencies.add(new GraphEdge<>(type.location(), type.name())); } } } }.visitStruct(struct); return new GraphNode<>(struct.name(), struct, ImmutableList.copyOf(dependencies)); } private static Log createCycleError(String name, List<GraphEdge<Location, String>> cycle) { // Choosing edge with lowest line number and printing a cycle starting from that edge // is a way to make report deterministic and (as a result) to make testing those reports simple. int edgeIndex = chooseEdgeWithLowestLineNumber(cycle); rotate(cycle, -edgeIndex); String previous = cycle.get(cycle.size() - 1).targetKey(); var lines = new ArrayList<String>(); for (var current : cycle) { String dependency = current.targetKey(); lines.add(current.value() + ": " + previous + " -> " + dependency); previous = dependency; } return error(name + " contains cycle:\n" + join("\n", lines)); } private static int chooseEdgeWithLowestLineNumber(List<GraphEdge<Location, String>> cycle) { int lowestLineNumber = Integer.MAX_VALUE; int result = 0; for (int i = 0; i < cycle.size(); i++) { int line = cycle.get(i).value().line(); if (line < lowestLineNumber) { lowestLineNumber = line; result = i; } } return result; } }
package org.spiffyui.client.rest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Window; import org.spiffyui.client.JSONUtil; import org.spiffyui.client.JSUtil; import org.spiffyui.client.MessageUtil; import org.spiffyui.client.SpiffyUIStrings; /** * A set of utilities for calling REST from GWT. */ public final class RESTility { private static final SpiffyUIStrings STRINGS = (SpiffyUIStrings) GWT.create(SpiffyUIStrings.class); private static final String SESSION_COOKIE = "Spiffy_Session"; private static final String LOCALE_COOKIE = "Spiffy_Locale"; private static final RESTility RESTILITY = new RESTility(); /** * This method represents an HTTP GET request */ public static final HTTPMethod GET = RESTILITY.new HTTPMethod("GET"); /** * This method represents an HTTP PUT request */ public static final HTTPMethod PUT = RESTILITY.new HTTPMethod("PUT"); /** * This method represents an HTTP POST request */ public static final HTTPMethod POST = RESTILITY.new HTTPMethod("POST"); /** * This method represents an HTTP DELETE request */ public static final HTTPMethod DELETE = RESTILITY.new HTTPMethod("DELETE"); private static boolean g_inLoginProcess = false; private static List<RESTLoginCallBack> g_loginListeners = new ArrayList<RESTLoginCallBack>(); private int m_callCount = 0; private boolean m_hasLoggedIn = false; private boolean m_logInListenerCalled = false; private static RESTAuthProvider g_authProvider; /** * This is a helper type class so we can pass the HTTP method as a type safe * object instead of a string. */ public final class HTTPMethod { private String m_method; /** * Create a new HTTPMethod object * * @param method the method */ private HTTPMethod(String method) { m_method = method; } /** * Get the method string for this object * * @return the method string */ private String getMethod() { return m_method; } } private Map<RESTCallback, RESTCallStruct> m_restCalls = new HashMap<RESTCallback, RESTCallStruct>(); private String m_userToken = null; private String m_tokenType = null; private String m_tokenServerUrl = null; private String m_username = null; private String m_tokenServerLogoutUrl = null; private String m_bestLocale = null; private boolean m_checkedCookie = false; /** * Just to make sure that nobody else can instatiate this object. */ private RESTility() { } private static final String URI_KEY = "uri"; private static final String SIGNOFF_URI_KEY = "signoffuri"; static { RESTAuthProvider authUtil = new AuthUtil(); RESTility.setAuthProvider(authUtil); } /** * <p> * Sets the authentication provider used for future REST requests. * </p> * * <p> * By default authentication is provided by the AuthUtil class, but this * class may be replaced to provide support for custom authentication schemes. * </p> * * @param authProvider * the new authentication provider * * @see AuthUtil */ public static final void setAuthProvider(RESTAuthProvider authProvider) { g_authProvider = authProvider; } /** * Gets the current auth provider which will be used for future REST calls. * * @return The current auth provider */ public static final RESTAuthProvider getAuthProvider() { return g_authProvider; } /** * Make a login request using RESTility authentication framework. * * @param callback the rest callback called when the login is complete * @param response the response from the server requiring the login * @param url the URL of the authentication server * @param errorCode the error code from the server returned with the 401 * * @exception RESTException * if there was an exception when making the login request */ public static void login(RESTCallback callback, Response response, String url, String errorCode) throws RESTException { RESTILITY.doLogin(callback, response, url, errorCode); } private void doLogin(RESTCallback callback, Response response, String url, String errorCode) throws RESTException { g_inLoginProcess = true; /* When the server returns a status code 401 they are required to send back the WWW-Authenticate header to tell us how to authenticate. */ String auth = response.getHeader("WWW-Authenticate"); if (auth == null) { throw new RESTException(RESTException.NO_AUTH_HEADER, "", STRINGS.noAuthHeader(), new HashMap<String, String>(), response.getStatusCode(), url); } /* * Now we have to parse out the token server URL and other information. * * The String should look like this: * * X-OPAUQUE uri=<token server URI>,signoffUri=<token server logout url> * * First we'll remove the token type */ String tokenType = auth.substring(0, auth.indexOf(' ')).trim(); auth = auth.substring(auth.indexOf(' ') + 1); String props[] = auth.split(","); String loginUri = null; String logoutUri = null; for (String prop : props) { if (prop.trim().toLowerCase().startsWith(URI_KEY)) { loginUri = prop.substring(prop.indexOf('=') + 2, prop.length() - 1).trim(); } else if (prop.trim().toLowerCase().startsWith(SIGNOFF_URI_KEY)) { logoutUri = prop.substring(prop.indexOf('=') + 2, prop.length() - 1).trim(); } } if (loginUri == null || logoutUri == null) { throw new RESTException(RESTException.INVALID_AUTH_HEADER, "", STRINGS.invalidAuthHeader(response.getHeader("WWW-Authenticate")), new HashMap<String, String>(), response.getStatusCode(), url); } if (logoutUri.trim().length() == 0) { logoutUri = loginUri; } setTokenType(tokenType); setTokenServerURL(loginUri); setTokenServerLogoutURL(logoutUri); removeCookie(SESSION_COOKIE); removeCookie(LOCALE_COOKIE); g_authProvider.showLogin(callback, loginUri, errorCode); } /** * Returns HTTPMethod corresponding to method name. * If the passed in method does not match any, GET is returned. * * @param method a String representation of a http method * @return the HTTPMethod corresponding to the passed in String method representation. */ public static HTTPMethod parseString(String method) { if (POST.getMethod().equalsIgnoreCase(method)) { return POST; } else if (PUT.getMethod().equalsIgnoreCase(method)) { return PUT; } else if (DELETE.getMethod().equalsIgnoreCase(method)) { return DELETE; } else { //Otherwise return GET return GET; } } /** * Upon logout, delete cookie and clear out all member variables */ public static void doLocalLogout() { RESTILITY.m_hasLoggedIn = false; RESTILITY.m_logInListenerCalled = false; RESTILITY.m_callCount = 0; RESTILITY.m_userToken = null; RESTILITY.m_tokenType = null; RESTILITY.m_tokenServerUrl = null; RESTILITY.m_tokenServerLogoutUrl = null; RESTILITY.m_username = null; removeCookie(SESSION_COOKIE); removeCookie(LOCALE_COOKIE); } /** * The normal GWT mechanism for removing cookies will remove a cookie at the path * the page is on. The is a possibility that the session cookie was set on the * server with a slightly different path. In that case we need to try to delete * the cookie on all the paths of the current URL. This method handles that case. * * @param name the name of the cookie to remove */ private static void removeCookie(String name) { Cookies.removeCookie(name); if (Cookies.getCookie(name) != null) { /* * This could mean that the cookie was there, * but was on a different path than the one that * we get by default. */ removeCookie(name, Window.Location.getPath()); } } private static void removeCookie(String name, String currentPath) { Cookies.removeCookie(name, currentPath); if (Cookies.getCookie(name) != null) { /* * This could mean that the cookie was there, * but was on a different path than the one that * we were passed. In that case we'll bump up * the path and try again. */ String path = currentPath; if (path.charAt(0) != '/') { path = "/" + path; } int slashloc = path.lastIndexOf('/'); if (slashloc > 1) { path = path.substring(0, slashloc); removeCookie(name, path); } } } /** * In some cases, like login, the original REST call returns an error and we * need to run it again. This call gets the same REST request information and * tries the request again. */ protected static void finishRESTCalls() { for (RESTCallback callback : RESTILITY.m_restCalls.keySet()) { RESTCallStruct struct = RESTILITY.m_restCalls.get(callback); if (struct != null && struct.shouldReplay()) { callREST(struct.getUrl(), struct.getData(), struct.getMethod(), callback); } } } /** * Make a rest call using an HTTP GET to the specified URL. * * @param callback the callback to invoke * @param url the REST url to call */ public static void callREST(String url, RESTCallback callback) { callREST(url, "", RESTility.GET, callback); } /** * Make a rest call using an HTTP GET to the specified URL including * the specified data.. * * @param url the REST url to call * @param data the data to pass to the URL * @param callback the callback to invoke */ public static void callREST(String url, String data, RESTCallback callback) { callREST(url, data, RESTility.GET, callback); } /** * Set the user token in JavaScript memory and and saves it in a cookie. * @param token user token */ protected static void setUserToken(String token) { g_inLoginProcess = false; RESTILITY.m_userToken = token; setSessionToken(); } /** * Set the authentication server url in JavaScript memory and and saves it in a cookie. * @param url authentication server url */ protected static void setTokenServerURL(String url) { RESTILITY.m_tokenServerUrl = url; setSessionToken(); } /** * <p> * Set the type of token RESTility will pass. * </p> * * <p> * Most of the time the token type is specified by the REST server and the * client does not have to specify this value. This method is mostly used * for testing. * </p> * * @param type the token type */ public static void setTokenType(String type) { RESTILITY.m_tokenType = type; setSessionToken(); } /** * Set the user name in JavaScript memory and and saves it in a cookie. * @param username user name */ protected static void setUsername(String username) { RESTILITY.m_username = username; setSessionToken(); } /** * Set the authentication server logout url in JavaScript memory and and saves it in a cookie. * @param url authentication server logout url */ protected static void setTokenServerLogoutURL(String url) { RESTILITY.m_tokenServerLogoutUrl = url; setSessionToken(); } /** * We can't know the best locale until after the user logs in because we need to consider * their locale from the identity vault. So we get the locale as part of the identity * information and then store this in a cookie. If the cookie doesn't match the current * locale then we need to refresh the page so we can reload the JavaScript libraries. * * @param locale the locale */ public static void setBestLocale(String locale) { if (getBestLocale() != null) { if (!getBestLocale().equals(locale)) { /* If the best locale from the server doesn't match the cookie. That means we set the cookie with the new locale and refresh the page. */ RESTILITY.m_bestLocale = locale; setSessionToken(); Window.Location.reload(); } else { /* If the best locale from the server matches the best locale from the cookie then we are done. */ return; } } else { /* This means they didn't have a best locale from the server stored as a cookie in the client. So we set the locale from the server into the cookie. */ RESTILITY.m_bestLocale = locale; setSessionToken(); /* * If there are any REST requests in process when we refresh * the page they will cause errors that show up before the * page reloads. Hiding the page makes those errors invisible. */ JSUtil.hide("body", ""); Window.Location.reload(); } } private static void setSessionToken() { Cookies.setCookie(SESSION_COOKIE, RESTILITY.m_tokenType + "," + RESTILITY.m_userToken + "," + RESTILITY.m_tokenServerUrl + "," + RESTILITY.m_tokenServerLogoutUrl + "," + RESTILITY.m_username); if (RESTILITY.m_bestLocale != null) { Cookies.setCookie(LOCALE_COOKIE, RESTILITY.m_bestLocale); } } /** * Returns a boolean flag indicating whether user has logged in or not * * @return boolean indicating whether user has logged in or not */ public static boolean hasUserLoggedIn() { return RESTILITY.m_hasLoggedIn; } /** * Returns user's full authentication token, prefixed with "X-OPAQUE" * * @return user's full authentication token prefixed with "X-OPAQUE" */ public static String getFullAuthToken() { return getTokenType() + " " + getUserToken(); } private static void checkSessionCookie() { String sessionCookie = Cookies.getCookie(SESSION_COOKIE); if (sessionCookie != null && sessionCookie.length() > 0) { // If the cookie value is quoted, strip off the enclosing quotes if (sessionCookie.length() > 2 && sessionCookie.charAt(0) == '"' && sessionCookie.charAt(sessionCookie.length() - 1) == '"') { sessionCookie = sessionCookie.substring(1, sessionCookie.length() - 1); } String sessionCookiePieces [] = sessionCookie.split(","); if (sessionCookiePieces != null) { if (sessionCookiePieces.length >= 1) { RESTILITY.m_tokenType = sessionCookiePieces [0]; } if (sessionCookiePieces.length >= 2) { RESTILITY.m_userToken = sessionCookiePieces [1]; } if (sessionCookiePieces.length >= 3) { RESTILITY.m_tokenServerUrl = sessionCookiePieces [2]; } if (sessionCookiePieces.length >= 4) { RESTILITY.m_tokenServerLogoutUrl = sessionCookiePieces [3]; } if (sessionCookiePieces.length >= 5) { RESTILITY.m_username = sessionCookiePieces [4]; } } } } /** * Returns user's authentication token * * @return user's authentication token */ public static String getUserToken() { if (RESTILITY.m_userToken == null) { checkSessionCookie(); } return RESTILITY.m_userToken; } /** * Returns user's authentication token type * * @return user's authentication token type */ public static String getTokenType() { if (RESTILITY.m_tokenType == null) { checkSessionCookie(); } return RESTILITY.m_tokenType; } /** * Returns the authentication server url * * @return authentication server url */ protected static String getTokenServerUrl() { if (RESTILITY.m_tokenServerUrl == null) { checkSessionCookie(); } return RESTILITY.m_tokenServerUrl; } /** * Returns authentication server logout url * * @return authentication server logout url */ protected static String getTokenServerLogoutUrl() { if (RESTILITY.m_tokenServerLogoutUrl == null) { checkSessionCookie(); } return RESTILITY.m_tokenServerLogoutUrl; } /** * Returns the name of the currently logged in user or null * if the current user is not logged in. * * @return user name */ public static String getUsername() { if (RESTILITY.m_username == null) { checkSessionCookie(); } return RESTILITY.m_username; } /** * Returns best matched locale * * @return best matched locale */ protected static String getBestLocale() { if (RESTILITY.m_bestLocale != null) { return RESTILITY.m_bestLocale; } else { RESTILITY.m_bestLocale = Cookies.getCookie(LOCALE_COOKIE); return RESTILITY.m_bestLocale; } } public static List<RESTLoginCallBack> getLoginListeners() { return g_loginListeners; } /** * Make an HTTP call and get the results as a JSON object. This method handles * cases like login, error parsing, and configuration requests. * * @param url the REST url to call * @param data the data to pass to the URL * @param method the HTTP method, defaults to GET * @param callback the callback object for handling the request results */ public static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback) { callREST(url, data, method, callback, false, null); } /** * Make an HTTP call and get the results as a JSON object. This method handles * cases like login, error parsing, and configuration requests. * * @param url the REST url to call * @param data the data to pass to the URL * @param method the HTTP method, defaults to GET * @param callback the callback object for handling the request results * @param etag the option etag for this request */ public static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback, String etag) { callREST(url, data, method, callback, false, etag); } /** * The client can't really handle the test for all SQL injection attacks, but we can * do some general sanity checking. * * @param data the data to check * * @return true if the data is valid and false otherwise */ private static boolean hasPotentialXss(final String data) { if (data == null) { return false; } String uppercaseData = data.toUpperCase(); if (uppercaseData.indexOf("<SCRIPT") > -1) { return true; } if (uppercaseData.indexOf("DELETE") > -1) { return true; } if (uppercaseData.indexOf("DROP") > -1) { return true; } if (uppercaseData.indexOf("UPDATE") > -1) { return true; } if (uppercaseData.indexOf("INSERT") > -1) { return true; } return false; } /** * Make an HTTP call and get the results as a JSON object. This method handles * cases like login, error parsing, and configuration requests. * * @param url the REST url to call * @param data the data to pass to the URL * @param method the HTTP method, defaults to GET * @param callback the callback object for handling the request results * @param isLoginRequest * true if this is a request to login and false otherwise * @param etag the option etag for this request * */ protected static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback, boolean isLoginRequest, String etag) { callREST(url, data, method, callback, isLoginRequest, true, etag); } /** * Make an HTTP call and get the results as a JSON object. This method handles * cases like login, error parsing, and configuration requests. * * @param url the REST url to call * @param data the data to pass to the URL * @param method the HTTP method, defaults to GET * @param callback the callback object for handling the request results * @param isLoginRequest * true if this is a request to login and false otherwise * @param shouldReplay true if this request should repeat after a login request * if this request returns a 401 * @param etag the option etag for this request */ public static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback, boolean isLoginRequest, boolean shouldReplay, String etag) { if (hasPotentialXss(data)) { callback.onError(new RESTException(RESTException.XSS_ERROR, "", STRINGS.noServerContact(), new HashMap<String, String>(), -1, url)); return; } RESTILITY.m_restCalls.put(callback, new RESTCallStruct(url, data, method, shouldReplay, etag)); RequestBuilder builder = new RESTRequestBuilder(method.getMethod(), URL.encode(url)); /* Set our headers */ builder.setHeader("Accept", "application/json"); builder.setHeader("Accept-Charset", "UTF-8"); if (RESTILITY.m_bestLocale != null) { /* * The REST end points use the Accept-Language header to determine * the locale to use for the contents of the REST request. Normally * the browser will fill this in with the browser locale and that * doesn't always match the preferred locale from the Identity Vault * so we need to set this value with the correct preferred locale. */ builder.setHeader("Accept-Language", RESTILITY.m_bestLocale); } if (getUserToken() != null && getTokenServerUrl() != null) { builder.setHeader("Authorization", getFullAuthToken()); builder.setHeader("TS-URL", getTokenServerUrl()); } if (etag != null) { builder.setHeader("If-Match", etag); } if (data != null) { /* Set our request data */ builder.setRequestData(data); //b/c jaxb/jersey chokes when there is no data when content-type is json builder.setHeader("Content-Type", "application/json"); } builder.setCallback(RESTILITY.new RESTRequestCallback(callback)); try { /* If we are in the process of logging in then all other requests will just return with a 401 until the login is finished. We want to delay those requests until the login is complete when we will replay all of them. */ if (isLoginRequest || !g_inLoginProcess) { builder.send(); } } catch (RequestException e) { MessageUtil.showFatalError(e.getMessage()); } } /** * The RESTCallBack object that implements the RequestCallback interface */ private class RESTRequestCallback implements RequestCallback { private RESTCallback m_origCallback; public RESTRequestCallback(RESTCallback callback) { m_origCallback = callback; } /** * Check the server response for an NCAC formatted fault and parse it into a RESTException * if it is . * * @param val the JSON value returned from the server * @param response the server response * * @return the RESTException if the server response contains an NCAC formatted fault */ private RESTException handleNcacFault(JSONValue val, Response response) { RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback); RESTException exception = JSONUtil.getRESTException(val, response.getStatusCode(), struct.getUrl()); if (exception == null) { return null; } else { if (RESTException.AUTH_SERVER_UNAVAILABLE.equals(exception.getSubcode())) { /* * This is a special case where the server can't connect to the * authentication server to validate the token. */ MessageUtil.showFatalError(STRINGS.unabledAuthServer()); } return exception; } } /** * Handles an unauthorized (401) response from the server * * @param struct the struct for this request * @param exception the exception for this request if available * @param response the response object * * @return true if this is an invalid request and false otherwise */ private boolean handleUnauthorized(RESTCallStruct struct, RESTException exception, Response response) { if (response.getStatusCode() == Response.SC_UNAUTHORIZED) { /* * For return values of 401 we need to show the login dialog */ try { for (RESTLoginCallBack listener : g_loginListeners) { listener.loginPrompt(); } String code = null; if (exception != null) { code = exception.getSubcode(); } doLogin(m_origCallback, response, struct.getUrl(), code); } catch (RESTException e) { RESTILITY.m_restCalls.remove(m_origCallback); m_origCallback.onError(e); } return true; } else { return false; } } @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 0) { /* This means we couldn't contact the server. It might be that the server is down or that we have a network timeout */ RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback); m_origCallback.onError(new RESTException(RESTException.NO_SERVER_RESPONSE, "", STRINGS.noServerContact(), new HashMap<String, String>(), response.getStatusCode(), struct.getUrl())); return; } if (!checkJSON(response.getText())) { RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback); m_origCallback.onError(new RESTException(RESTException.UNPARSABLE_RESPONSE, "", "", new HashMap<String, String>(), response.getStatusCode(), struct.getUrl())); return; } JSONValue val = null; RESTException exception = null; if (response.getText() != null && response.getText().trim().length() > 1) { val = null; try { val = JSONParser.parseStrict(response.getText()); } catch (JavaScriptException e) { /* This means we couldn't parse the response this is unlikely because we have already checked it, but it is possible. */ RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback); exception = new RESTException(RESTException.UNPARSABLE_RESPONSE, "", response.getText(), new HashMap<String, String>(), response.getStatusCode(), struct.getUrl()); } exception = handleNcacFault(val, response); } RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback); if (handleUnauthorized(struct, exception, response)) { /* Then this is a 401 and the login will handle it */ return; } else { handleSuccessfulResponse(val, exception, response); } } /** * Handle successful REST responses which have parsable JSON, aren't NCAC faults, * and don't contain login requests. * * @param val the JSON value returned from the server * @param exception the exception generated by the response if available * @param response the server response */ private void handleSuccessfulResponse(JSONValue val, RESTException exception, Response response) { RESTILITY.m_restCalls.remove(m_origCallback); if (exception != null) { m_origCallback.onError(exception); } else { RESTILITY.m_callCount++; /* * You have to have at least three valid REST calls before * we show the application UI. This covers the build info * and the successful login with and invalid token. It * would be really nice if we didn't have to worry about * this at this level, but then the UI will flash sometimes * before the user has logged in. Hackito Ergo Sum. */ if (RESTILITY.m_callCount > 2) { RESTILITY.m_hasLoggedIn = true; if (!RESTILITY.m_logInListenerCalled) { for (RESTLoginCallBack listener : g_loginListeners) { listener.onLoginSuccess(); } RESTILITY.m_logInListenerCalled = true; } } if (response.getHeader("ETag") != null && m_origCallback instanceof ConcurrentRESTCallback) { ((ConcurrentRESTCallback) m_origCallback).setETag(response.getHeader("ETag")); } m_origCallback.onSuccess(val); } } public void onError(Request request, Throwable exception) { MessageUtil.showFatalError(exception.getMessage()); } } private static native boolean checkJSON(String json) /*-{ return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( json.replace(/"(\\.|[^"\\])*"/g, ''))); }-*/; /** * Add login listeners * * @param callback listeners to be added */ public static void addLoginListener(RESTLoginCallBack callback) { RESTility.g_loginListeners.add(callback); } /** * Remove login listeners * * @param callback listeners to be removed */ public static void removeLoginListener(RESTLoginCallBack callback) { RESTility.g_loginListeners.remove(callback); } } /** * A struct for holding data about a REST request */ class RESTCallStruct { private String m_url; private String m_data; private RESTility.HTTPMethod m_method; private boolean m_shouldReplay; private String m_etag; /** * Creates a new RESTCallStruct * * @param url the URL for this REST call * @param data the data for this REST call * @param method the method for this REST call * @param shouldReplay should this request be repeated if we get a 401 */ protected RESTCallStruct(String url, String data, RESTility.HTTPMethod method, boolean shouldReplay, String etag) { m_url = url; m_data = data; m_method = method; m_shouldReplay = shouldReplay; m_etag = etag; } /** * Gets the URL * * @return the URL */ public String getUrl() { return m_url; } /** * Gets the data * * @return the data */ public String getData() { return m_data; } /** * Gets the HTTP method * * @return the method */ public RESTility.HTTPMethod getMethod() { return m_method; } /** * Gets the ETag for this call * * @return the ETag */ public String getETag() { return m_etag; } /** * Should this request repeat * * @return true if it should repeat, false otherwise */ public boolean shouldReplay() { return m_shouldReplay; } } /** * This class extends RequestBuilder so we can call PUT and DELETE */ class RESTRequestBuilder extends RequestBuilder { /** * Creates a new RESTRequestBuilder * * @param method the HTTP method * @param url the request URL */ public RESTRequestBuilder(String method, String url) { super(method, url); } }
package org.vaadin.viritin.fields; import com.vaadin.data.Property; import com.vaadin.data.Validator; import com.vaadin.server.FontAwesome; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.CustomField; import com.vaadin.ui.GridLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.TextField; import com.vaadin.util.ReflectTools; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.vaadin.viritin.MBeanFieldGroup; import org.vaadin.viritin.MBeanFieldGroup.FieldGroupListener; /** * A field to edit simple map structures like string to Integer/Double/Float * maps. The field is still EXPERIMENTAL, so the should be considered less * stable than other Viritin API. * * @author Matti Tahvonen * @param <K> The type of key in the edited map * @param <V> The type of value in the edited map */ public class MapField<K, V> extends CustomField<Map> { private static final Method ADDED_METHOD; private static final Method REMOVED_METHOD; static { ADDED_METHOD = ReflectTools.findMethod(ElementAddedListener.class, "elementAdded", ElementAddedEvent.class); REMOVED_METHOD = ReflectTools.findMethod(ElementRemovedListener.class, "elementRemoved", ElementRemovedEvent.class); } private GridLayout mainLayout = new GridLayout(3, 1); private Class<K> keyType; private Class<V> valueType; private Class<?> editorType; protected K newInstance; private final FieldGroupListener fieldGroupListener = new FieldGroupListener() { @Override public void onFieldGroupChange(MBeanFieldGroup beanFieldGroup) { if (beanFieldGroup.getItemDataSource().getBean() == newInstance) { if (!getFieldGroupFor(newInstance).valueEditor.isValid()) { return; } getAndEnsureValue().put(newInstance, null); fireEvent(new ElementAddedEvent(MapField.this, newInstance)); setPersisted(newInstance, true); onElementAdded(); } // TODO could optimize for only repainting on changed validity fireValueChange(false); } }; private boolean allowNewItems = true; private boolean allowRemovingItems = true; private boolean allowEditItems = true; private final Map<K, EntryEditor> pojoToEditor = new HashMap<>(); private EntryEditor newEntryEditor; public MapField() { } public MapField(Class<K> elementType, Class<?> formType) { this.keyType = elementType; this.editorType = formType; } private void ensureInited() { if (mainLayout.getComponentCount() == 0) { mainLayout.addComponent(new Label("Key ->")); mainLayout.addComponent(new Label("Value")); mainLayout.addComponent(new Label("Delete entry")); } } @Override public Class<? extends Map> getType() { return Map.class; } public MapField<K, V> addElementAddedListener( ElementAddedListener<K> listener) { addListener(ElementAddedEvent.class, listener, ADDED_METHOD); return this; } public MapField<K, V> removeElementAddedListener( ElementAddedListener listener) { removeListener(ElementAddedEvent.class, listener, ADDED_METHOD); return this; } public MapField<K, V> addElementRemovedListener( ElementRemovedListener<K> listener) { addListener(ElementRemovedEvent.class, listener, REMOVED_METHOD); return this; } public MapField<K, V> removeElementRemovedListener( ElementRemovedListener listener) { removeListener(ElementRemovedEvent.class, listener, REMOVED_METHOD); return this; } public boolean isAllowNewItems() { return allowNewItems; } public boolean isAllowRemovingItems() { return allowRemovingItems; } public boolean isAllowEditItems() { return allowEditItems; } public MapField<K, V> setAllowEditItems(boolean allowEditItems) { this.allowEditItems = allowEditItems; return this; } public MapField<K, V> setAllowRemovingItems(boolean allowRemovingItems) { this.allowRemovingItems = allowRemovingItems; return this; } public MapField<K, V> withCaption(String caption) { setCaption(caption); return this; } @Override public void validate() throws Validator.InvalidValueException { super.validate(); Map<K, V> v = getValue(); if (v != null) { for (K o : v.keySet()) { // TODO, should validate both key and value // for (Field f : getFieldGroupFor((K) o).getFields()) { // f.validate(); } } } private Map<K, V> getAndEnsureValue() { Map<K, V> value = getValue(); if (value == null) { if (getPropertyDataSource() == null) { // this should never happen :-) return new HashMap(); } Class fieldType = getPropertyDataSource().getType(); if (fieldType.isInterface()) { value = new HashMap<>(); } else { try { value = (Map) fieldType.newInstance(); } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException( "Could not instantiate the used colleciton type", ex); } } getPropertyDataSource().setValue(value); } return value; } public MapField<K, V> setAllowNewElements( boolean allowNewItems) { this.allowNewItems = allowNewItems; return this; } public Class<K> getKeyType() { return keyType; } protected TextField createKeyEditorInstance() { MTextField tf = new MTextField().withInputPrompt("key"); return tf; } protected TextField createValueEditorInstance() { MTextField tf = new MTextField().withInputPrompt("value"); return tf; } private void replaceValue(K key, String value) { if (key == null) { // new value without proper key, ignore return; } K tKey; try { tKey = (K) key; } catch (ClassCastException e) { try { tKey = keyType.getConstructor(String.class).newInstance(key); } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex) { throw new RuntimeException("No suitable constructor found", ex); } } V tVal; try { tVal = (V) value; } catch (ClassCastException e) { try { tVal = valueType.getConstructor(String.class).newInstance(value); } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex) { throw new RuntimeException("No suitable constructor found", ex); } } getAndEnsureValue().put(tKey, tVal); } private void renameValue(K oldKey, String key) { K tKey; try { tKey = (K) key; } catch (ClassCastException e) { try { tKey = keyType.getConstructor(String.class).newInstance(key); } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex) { throw new RuntimeException("No suitable constructor found", ex); } } EntryEditor e; V value; if (oldKey != null) { value = getAndEnsureValue().remove(oldKey); e = pojoToEditor.remove(oldKey); } else { e = newEntryEditor; String strValue = newEntryEditor.valueEditor.getValue(); try { value = (V) strValue; } catch (ClassCastException ex) { try { value = valueType.getConstructor(String.class).newInstance(strValue); } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex1) { value = null; } } e.delete.setEnabled(true); // Old editor is used for the new value, create a new one createNewEntryRow(); } e.oldKey = tKey; getAndEnsureValue().put(tKey, value); pojoToEditor.put(tKey, e); } private EntryEditor getFieldGroupFor(K key) { EntryEditor ee = pojoToEditor.get(key); if (ee == null) { final TextField k = createKeyEditorInstance(); final TextField v = createValueEditorInstance(); // TODO fieldgroup listener final EntryEditor ee1 = ee = new EntryEditor(k, v, key); // TODO listen for all changes for proper modified/validity changes pojoToEditor.put(key, ee); } return ee; } public void addElement(K key, V value) { getAndEnsureValue().put(key, value); addInternalElement(key, value); fireValueChange(false); fireEvent(new ElementAddedEvent<>(this, key)); } public void removeElement(K keyToBeRemoved) { removeInternalElement(keyToBeRemoved); getAndEnsureValue().remove(keyToBeRemoved); fireValueChange(false); fireEvent(new ElementRemovedEvent<>(this, keyToBeRemoved)); } @Override protected Component initContent() { return getLayout(); } @Override protected void setInternalValue(Map newValue) { super.setInternalValue(newValue); clearCurrentEditors(); Map<K, V> value = newValue; if (value != null) { for (Map.Entry<K, V> entry : value.entrySet()) { K key = entry.getKey(); V value1 = entry.getValue(); addInternalElement(key, value1); } } if (isAllowNewItems()) { createNewEntryRow(); } onElementAdded(); } private void createNewEntryRow() throws ReadOnlyException { TextField keyEditor = createKeyEditorInstance(); TextField valueEditor = createKeyEditorInstance(); newEntryEditor = new EntryEditor(keyEditor, valueEditor, null); addRowForEntry(newEntryEditor, null, null); } protected void addInternalElement(K k, V v) { ensureInited(); EntryEditor fieldGroupFor = getFieldGroupFor(k); addRowForEntry(fieldGroupFor, k, v); } private void addRowForEntry(EntryEditor editor, K k, V v) throws ReadOnlyException { editor.bindValues(k, v); getLayout().addComponents(editor.keyEditor, editor.valueEditor, editor.delete); } protected void setPersisted(K v, boolean persisted) { // TODO create new "draft row" } protected void removeInternalElement(K v) { // TODO remove from layout } protected Layout getLayout() { return mainLayout; } protected void onElementAdded() { System.out.println("What now!?"); } private void clearCurrentEditors() { while (mainLayout.getRows() > 1) { mainLayout.removeRow(1); } } public static class ElementAddedEvent<K> extends Component.Event { private final K key; public ElementAddedEvent(MapField source, K element) { super(source); this.key = element; } public K getKey() { return key; } } public static class ElementRemovedEvent<K> extends Component.Event { private final K key; public ElementRemovedEvent(MapField source, K element) { super(source); this.key = element; } public K getKey() { return key; } } public interface ElementAddedListener<K> extends Serializable { void elementAdded(ElementAddedEvent<K> e); } public interface ElementRemovedListener<K> extends Serializable { void elementRemoved(ElementRemovedEvent<K> e); } public interface Instantiator<ET> extends Serializable { ET create(); } private class EntryEditor implements Serializable { TextField keyEditor; TextField valueEditor; Button delete; K oldKey; public EntryEditor(TextField ke, TextField valueEditor, K k) { this.keyEditor = ke; this.valueEditor = valueEditor; delete = new Button(FontAwesome.TRASH); delete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Object removed = getValue().remove(oldKey); pojoToEditor.remove(oldKey); Iterator<Component> iterator = mainLayout.iterator(); int idx = 0; while(iterator.next() != keyEditor) { idx++; } mainLayout.removeRow((int) idx/3); } }); this.oldKey = k; if (oldKey == null) { delete.setEnabled(false); } } private void bindValues(K k, V v) { keyEditor.setValue(k == null ? null : k.toString()); valueEditor.setValue(v == null ? null : v.toString()); keyEditor.addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(Property.ValueChangeEvent event) { renameValue(EntryEditor.this.oldKey, EntryEditor.this.keyEditor.getValue()); } }); valueEditor.addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(Property.ValueChangeEvent event) { replaceValue((K) EntryEditor.this.oldKey, EntryEditor.this.valueEditor.getValue()); } }); } } }