answer
stringlengths
17
10.2M
package com.jwetherell.algorithms.data_structures; import com.jwetherell.algorithms.data_structures.interfaces.IQueue; @SuppressWarnings("unchecked") public interface Queue<T> extends IQueue<T> { /** * This queue implementation is backed by an array. * * @author Justin Wetherell <phishman3579@gmail.com> */ public static class ArrayQueue<T> implements Queue<T> { private static final int MINIMUM_SIZE = 1024; private T[] array = (T[]) new Object[MINIMUM_SIZE]; private int lastIndex = 0; private int firstIndex = 0; /** * {@inheritDoc} */ @Override public boolean offer(T value) { if (size() >= array.length) grow(size()); array[lastIndex % array.length] = value; lastIndex++; return true; } /** * {@inheritDoc} */ @Override public T poll() { int size = lastIndex - firstIndex; if (size < 0) return null; T t = array[firstIndex % array.length]; array[firstIndex % array.length] = null; firstIndex++; size = lastIndex - firstIndex; if (size <= 0) { // Removed last element lastIndex = 0; firstIndex = 0; } int shrinkSize = array.length>>1; if (shrinkSize >= MINIMUM_SIZE && size < shrinkSize) shrink(); return t; } /** * {@inheritDoc} */ @Override public T peek() { return array[firstIndex % array.length]; } /** * {@inheritDoc} */ @Override public boolean remove(T value) { for (int i=0; i < array.length; i++) { T obj = array[i]; // if obj is null, it should return false (not NPE) if (value.equals(obj)) return remove(i); } return false; } private boolean remove(int index) { if (index<0 || index >= array.length) return false; if (index==firstIndex) return (poll()!=null); int adjIndex = index % array.length; int adjLastIndex = (lastIndex-1) % array.length; if (adjIndex != adjLastIndex) { // Shift the array down one spot System.arraycopy(array, index+1, array, index, (array.length - (index+1))); if (adjLastIndex < firstIndex) { //Wrapped around array array[array.length-1] = array[0]; System.arraycopy(array, 1, array, 0, firstIndex-1); } } array[adjLastIndex] = null; int shrinkSize = array.length>>1; if (shrinkSize >= MINIMUM_SIZE && size() < shrinkSize) shrink(); lastIndex return true; } // Grow the array by 50% and rearrange to make sequential private void grow(int size) { int growSize = (size + (size<<1)); T[] temp = (T[]) new Object[growSize]; // Since the array can wrap around, make sure you grab the first chunk int adjLast = lastIndex % array.length; if (adjLast < firstIndex) { System.arraycopy(array, 0, temp, array.length-adjLast, adjLast+1); } // Copy the remaining System.arraycopy(array, firstIndex, temp, 0, array.length-firstIndex); array = null; array = temp; lastIndex = (lastIndex - firstIndex); firstIndex = 0; } // Shrink the array by 50% and rearrange to make sequential private void shrink() { int shrinkSize = array.length>>1; T[] temp = (T[]) new Object[shrinkSize]; // Since the array can wrap around, make sure you grab the first chunk int adjLast = lastIndex % array.length; int endIndex = (lastIndex>array.length)?array.length:lastIndex; if (adjLast <= firstIndex) { System.arraycopy(array, 0, temp, array.length-firstIndex, adjLast); } // Copy the remaining System.arraycopy(array, firstIndex, temp, 0, endIndex-firstIndex); array = null; array = temp; lastIndex = (lastIndex - firstIndex); firstIndex = 0; } /** * {@inheritDoc} */ @Override public void clear() { firstIndex = 0; lastIndex = 0; } /** * {@inheritDoc} */ @Override public boolean contains(T value) { for (int i=0; i < array.length; i++) { T obj = array[i]; // if obj is null, it should return false (not NPE) if (value.equals(obj)) return true; } return false; } /** * {@inheritDoc} */ @Override public boolean validate() { if (size()==0) return true; int localSize = 0; int realFirst = firstIndex; if (firstIndex>array.length) realFirst = firstIndex%array.length; int realLast = lastIndex; if (lastIndex>array.length) realLast = lastIndex%array.length; for (int i=0; i<array.length; i++) { T t = array[i]; if ((realFirst==realLast) || (realFirst<realLast && (i>=realFirst && i<realLast)) || (realLast<realFirst && (i<realLast || i>=realFirst)) ) { if (t==null) return false; localSize++; } else { if (t!=null) return false; } } return (localSize==size()); } /** * {@inheritDoc} */ @Override public int size() { return lastIndex - firstIndex; } /** * {@inheritDoc} */ @Override public java.util.Queue<T> toQueue() { return (new JavaCompatibleArrayQueue<T>(this)); } /** * {@inheritDoc} */ @Override public java.util.Collection<T> toCollection() { return (new JavaCompatibleArrayQueue<T>(this)); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); for (int i = lastIndex - 1; i >= firstIndex; i builder.append(array[i%array.length]).append(", "); } return builder.toString(); } } /** * This queue implementation is backed by a linked list. * * @author Justin Wetherell <phishman3579@gmail.com> */ public static class LinkedQueue<T> implements Queue<T> { private Node<T> head = null; private Node<T> tail = null; private int size = 0; public LinkedQueue() { head = null; tail = null; size = 0; } /** * {@inheritDoc} */ @Override public boolean offer(T value) { return add(new Node<T>(value)); } /** * Enqueue the node in the queue. * * @param node * to enqueue. */ private boolean add(Node<T> node) { if (head == null) { head = node; tail = node; } else { Node<T> oldHead = head; head = node; node.next = oldHead; oldHead.prev = node; } size++; return true; } /** * {@inheritDoc} */ @Override public T poll() { T result = null; if (tail != null) { result = tail.value; Node<T> prev = tail.prev; if (prev != null) { prev.next = null; tail = prev; } else { head = null; tail = null; } size } return result; } /** * {@inheritDoc} */ @Override public T peek() { return (tail!=null)?tail.value:null; } /** * {@inheritDoc} */ @Override public boolean remove(T value) { // Find the node Node<T> node = head; while (node != null && (!node.value.equals(value))) { node = node.next; } if (node == null) return false; return remove(node); } private boolean remove(Node<T> node) { // Update the tail, if needed if (node.equals(tail)) tail = node.prev; Node<T> prev = node.prev; Node<T> next = node.next; if (prev != null && next != null) { prev.next = next; next.prev = prev; } else if (prev != null && next == null) { prev.next = null; } else if (prev == null && next != null) { // Node is the head next.prev = null; head = next; } else { // prev==null && next==null head = null; } size return true; } /** * {@inheritDoc} */ @Override public void clear() { head = null; size = 0; } /** * {@inheritDoc} */ @Override public boolean contains(T value) { if (head == null) return false; Node<T> node = head; while (node != null) { if (node.value.equals(value)) return true; node = node.next; } return false; } /** * {@inheritDoc} */ @Override public int size() { return size; } /** * {@inheritDoc} */ @Override public boolean validate() { java.util.Set<T> keys = new java.util.HashSet<T>(); Node<T> node = head; if (node!=null) { keys.add(node.value); if (node.prev!=null) return false; Node<T> child = node.next; while (child!=null) { if (!validate(child,keys)) return false; child = child.next; } } return (keys.size()==size()); } private boolean validate(Node<T> node, java.util.Set<T> keys) { if (node.value==null) return false; keys.add(node.value); Node<T> child = node.next; if (child!=null) { if (!child.prev.equals(node)) return false; if (!validate(child,keys)) return false; } else { if (!node.equals(tail)) return false; } return true; } /** * {@inheritDoc} */ @Override public java.util.Queue<T> toQueue() { return (new JavaCompatibleLinkedQueue<T>(this)); } /** * {@inheritDoc} */ @Override public java.util.Collection<T> toCollection() { return (new JavaCompatibleLinkedQueue<T>(this)); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); Node<T> node = head; while (node != null) { builder.append(node.value).append(", "); node = node.next; } return builder.toString(); } private static class Node<T> { private T value = null; private Node<T> prev = null; private Node<T> next = null; private Node(T value) { this.value = value; } /** * {@inheritDoc} */ @Override public String toString() { return "value=" + value + " previous=" + ((prev != null) ? prev.value : "NULL") + " next=" + ((next != null) ? next.value : "NULL"); } } } public static class JavaCompatibleArrayQueue<T> extends java.util.AbstractQueue<T> { private ArrayQueue<T> queue = null; public JavaCompatibleArrayQueue(ArrayQueue<T> queue) { this.queue = queue; } /** * {@inheritDoc} */ @Override public boolean add(T value) { return queue.offer(value); } /** * {@inheritDoc} */ @Override public boolean remove(Object value) { return queue.remove((T)value); } /** * {@inheritDoc} */ @Override public boolean contains(Object value) { return queue.contains((T)value); } /** * {@inheritDoc} */ @Override public boolean offer(T value) { return queue.offer(value); } /** * {@inheritDoc} */ @Override public T peek() { return queue.peek(); } /** * {@inheritDoc} */ @Override public T poll() { return queue.poll(); } /** * {@inheritDoc} */ @Override public int size() { return queue.size(); } /** * {@inheritDoc} */ @Override public java.util.Iterator<T> iterator() { return (new ArrayQueueIterator<T>(queue)); } private static class ArrayQueueIterator<T> implements java.util.Iterator<T> { private ArrayQueue<T> queue = null; private int last = -1; private int index = 0; //offset from first private ArrayQueueIterator(ArrayQueue<T> queue) { this.queue = queue; } /** * {@inheritDoc} */ @Override public boolean hasNext() { return ((queue.firstIndex+index) < queue.lastIndex); } /** * {@inheritDoc} */ @Override public T next() { if (queue.firstIndex+index < queue.lastIndex) { last = queue.firstIndex+index; return queue.array[queue.firstIndex+index++]; } return null; } /** * {@inheritDoc} */ @Override public void remove() { queue.remove(last); } } } public static class JavaCompatibleLinkedQueue<T> extends java.util.AbstractQueue<T> { private LinkedQueue<T> queue = null; public JavaCompatibleLinkedQueue(LinkedQueue<T> queue) { this.queue = queue; } /** * {@inheritDoc} */ @Override public boolean add(T value) { return queue.offer(value); } /** * {@inheritDoc} */ @Override public boolean remove(Object value) { return queue.remove((T)value); } /** * {@inheritDoc} */ @Override public boolean contains(Object value) { return queue.contains((T)value); } /** * {@inheritDoc} */ @Override public boolean offer(T value) { return queue.offer(value); } /** * {@inheritDoc} */ @Override public T peek() { return queue.peek(); } /** * {@inheritDoc} */ @Override public T poll() { return queue.poll(); } /** * {@inheritDoc} */ @Override public int size() { return queue.size(); } /** * {@inheritDoc} */ @Override public java.util.Iterator<T> iterator() { return (new LinkedQueueIterator<T>(queue)); } private static class LinkedQueueIterator<T> implements java.util.Iterator<T> { private LinkedQueue<T> queue = null; private LinkedQueue.Node<T> lastNode = null; private LinkedQueue.Node<T> nextNode = null; private LinkedQueueIterator(LinkedQueue<T> queue) { this.queue = queue; this.nextNode = queue.tail; } /** * {@inheritDoc} */ @Override public boolean hasNext() { return (nextNode!=null); } /** * {@inheritDoc} */ @Override public T next() { LinkedQueue.Node<T> current = nextNode; lastNode = current; if (current!=null) { nextNode = current.prev; return current.value; } return null; } /** * {@inheritDoc} */ @Override public void remove() { queue.remove(lastNode); } } } }
package com.lukehutch.classpathscanner; //NB requires the import of some Log class if you want logging. import gribbit.util.Log; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; 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.LinkedList; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ClasspathScanner { /** * List of directory path prefixes to scan (produced from list of package prefixes passed into the * constructor) */ private String[] pathsToScan; /** * Initialize a classpath scanner, with a list of package prefixes to scan. * * @param pacakagesToScan * A list of package prefixes to scan. */ public ClasspathScanner(String[] pacakagesToScan) { this.pathsToScan = Stream.of(pacakagesToScan).map(p -> p.replace('.', '/') + "/") .toArray(String[]::new); } /** The method to run when a subclass of a specific class is found on the classpath. */ @FunctionalInterface public interface SubclassMatchProcessor<T> { public void processMatch(Class<? extends T> matchingClass); } /** * Call the given ClassMatchProcessor if classes are found on the classpath that extend the specified * superclass. * * @param superclass * The superclass to match (i.e. the class that subclasses need to extend to match). * @param classMatchProcessor * the ClassMatchProcessor to call when a match is found. */ @SuppressWarnings("unchecked") public <T> ClasspathScanner matchSubclassesOf(final Class<T> superclass, final SubclassMatchProcessor<T> classMatchProcessor) { if (superclass.isInterface()) { // No support yet for scanning for interfaces that extend other interfaces throw new IllegalArgumentException(superclass.getName() + " is an interface, not a regular class"); } if (superclass.isAnnotation()) { // No support yet for scanning for interfaces that extend other interfaces throw new IllegalArgumentException(superclass.getName() + " is an annotation, not a regular class"); } classMatchers.add(() -> { ClassInfo superclassInfo = classNameToClassInfo.get(superclass.getName()); boolean foundMatches = false; if (superclassInfo != null) { // For all subclasses of the given superclass for (ClassInfo subclassInfo : superclassInfo.allSubclasses) { try { // Load class Class<? extends T> klass = (Class<? extends T>) Class.forName(subclassInfo.name); // Process match classMatchProcessor.processMatch(klass); foundMatches = true; } catch (ClassNotFoundException | NoClassDefFoundError e) { throw new RuntimeException(e); } } } if (!foundMatches) { Log.info("No classes found with superclass " + superclass.getName()); } }); return this; } /** The method to run when a class implementing a specific interface is found on the classpath. */ @FunctionalInterface public interface InterfaceMatchProcessor<T> { public void processMatch(Class<? extends T> matchingClass); } /** * Call the given ClassMatchProcessor if classes are found on the classpath that implement the specified * interface. * * @param iface * The interface to match (i.e. the interface that classes need to implement to match). * @param interfaceMatchProcessor * the ClassMatchProcessor to call when a match is found. */ @SuppressWarnings("unchecked") public <T> ClasspathScanner matchClassesImplementing(final Class<T> iface, final InterfaceMatchProcessor<T> interfaceMatchProcessor) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface.getName() + " is not an interface"); } classMatchers.add(() -> { ArrayList<String> classesImplementingIface = interfaceToClasses.get(iface.getName()); if (classesImplementingIface != null) { // For all classes implementing the given interface for (String implClass : classesImplementingIface) { try { // Load class Class<? extends T> klass = (Class<? extends T>) Class.forName(implClass); // Process match interfaceMatchProcessor.processMatch(klass); } catch (ClassNotFoundException | NoClassDefFoundError e) { throw new RuntimeException(e); } } } else { Log.info("No classes found implementing interface " + iface.getName()); } }); return this; } /** The method to run when a class with the right matching annotation is found on the classpath. */ @FunctionalInterface public interface ClassAnnotationMatchProcessor { public void processMatch(Class<?> matchingClass); } /** * Call the given ClassMatchProcessor if classes are found on the classpath that have the given * annotation. * * @param annotation * The class annotation to match. * @param classMatchProcessor * the ClassMatchProcessor to call when a match is found. */ public ClasspathScanner matchClassesWithAnnotation(final Class<?> annotation, final ClassAnnotationMatchProcessor classMatchProcessor) { if (!annotation.isAnnotation()) { throw new IllegalArgumentException("Class " + annotation.getName() + " is not an annotation"); } classMatchers.add(() -> { ArrayList<String> classesWithAnnotation = annotationToClasses.get(annotation.getName()); if (classesWithAnnotation != null) { // For all classes with the given annotation for (String classWithAnnotation : classesWithAnnotation) { try { // Load class Class<?> klass = Class.forName(classWithAnnotation); // Process match classMatchProcessor.processMatch(klass); } catch (ClassNotFoundException | NoClassDefFoundError e) { throw new RuntimeException(e); } } } else { Log.info("No classes found with annotation " + annotation.getName()); } }); return this; } /** The method to run when a matching file is found on the classpath. */ @FunctionalInterface public interface FileMatchProcessor { public void processMatch(String path, InputStream inputStream); } /** * Call the given FileMatchProcessor if files are found on the classpath with the given regex pattern in * their path. * * @param filenameMatchPattern * The regex to match, e.g. "app/templates/.*\\.html" * @param fileMatchProcessor * The FileMatchProcessor to call when each match is found. */ public ClasspathScanner matchFilenamePattern(final String filenameMatchPattern, final FileMatchProcessor fileMatchProcessor) { filePathMatchers.add(new FilePathMatcher(Pattern.compile(filenameMatchPattern), fileMatchProcessor)); return this; } /** An interface used for testing if a file path matches a specified pattern. */ private static class FilePathMatcher { Pattern pattern; FileMatchProcessor fileMatchProcessor; public FilePathMatcher(Pattern pattern, FileMatchProcessor fileMatchProcessor) { this.pattern = pattern; this.fileMatchProcessor = fileMatchProcessor; } } /** * A list of file path matchers to call when a directory or subdirectory on the classpath matches a given * regexp. */ private ArrayList<FilePathMatcher> filePathMatchers = new ArrayList<>(); /** A functional interface used for testing if a class matches specified criteria. */ @FunctionalInterface private static interface ClassMatcher { public abstract void lookForMatches(); } /** A list of class matchers to call once all classes have been read in from classpath. */ private ArrayList<ClassMatcher> classMatchers = new ArrayList<>(); /** * An object to hold class information. For speed purposes, this is reconstructed directly from the * classfile header without calling the classloader. */ private static class ClassInfo { /** Class name */ String name; /** * Set to true when this class is encountered in the classpath (false if the class is so far only * cited as a superclass) */ boolean encountered; /** Direct superclass */ ClassInfo directSuperclass; /** Direct subclasses */ ArrayList<ClassInfo> directSubclasses = new ArrayList<>(); /** All superclasses, including java.lang.Object. */ HashSet<ClassInfo> allSuperclasses = new HashSet<>(); /** All subclasses */ HashSet<ClassInfo> allSubclasses = new HashSet<>(); /** All interfaces */ HashSet<String> interfaces = new HashSet<>(); /** All annotations */ HashSet<String> annotations = new HashSet<>(); /** This class was encountered on the classpath. */ public ClassInfo(String name, ArrayList<String> interfaces, HashSet<String> annotations) { this.name = name; this.encounter(interfaces, annotations); } /** * If called by another class, this class was previously cited as a superclass, and now has been * itself encountered on the classpath. */ public void encounter(ArrayList<String> interfaces, HashSet<String> annotations) { this.encountered = true; this.interfaces.addAll(interfaces); this.annotations.addAll(annotations); } /** This class was referenced as a superclass of the given subclass. */ public ClassInfo(String name, ClassInfo subclass) { this.name = name; this.encountered = false; addSubclass(subclass); } /** Connect this class to a subclass. */ public void addSubclass(ClassInfo subclass) { if (subclass.directSuperclass != null && subclass.directSuperclass != this) { throw new RuntimeException(subclass.name + " has two superclasses: " + subclass.directSuperclass.name + ", " + this.name); } subclass.directSuperclass = this; subclass.allSuperclasses.add(this); this.directSubclasses.add(subclass); this.allSubclasses.add(subclass); } @Override public String toString() { return name; } } /** * Direct and ancestral interfaces of a given interface. */ private static class InterfaceInfo { ArrayList<String> superInterfaces = new ArrayList<>(); HashSet<String> allSuperInterfaces = new HashSet<>(); public InterfaceInfo(ArrayList<String> superInterfaces) { this.superInterfaces.addAll(superInterfaces); } } /** A map from fully-qualified class name to the corresponding ClassInfo object. */ private final HashMap<String, ClassInfo> classNameToClassInfo = new HashMap<>(); /** A map from fully-qualified class name to the corresponding InterfaceInfo object. */ private final HashMap<String, InterfaceInfo> interfaceNameToInterfaceInfo = new HashMap<>(); /** Reverse mapping from annotation to classes that have the annotation */ private final HashMap<String, ArrayList<String>> annotationToClasses = new HashMap<>(); /** Reverse mapping from interface to classes that implement the interface */ private final HashMap<String, ArrayList<String>> interfaceToClasses = new HashMap<>(); /** * Recursively find all subclasses for each class; called by finalizeClassHierarchy. */ private static void finalizeClassHierarchyRec(ClassInfo curr) { // DFS through subclasses for (ClassInfo subclass : curr.directSubclasses) { finalizeClassHierarchyRec(subclass); } // Postorder traversal of curr node to accumulate subclasses for (ClassInfo subclass : curr.directSubclasses) { curr.allSubclasses.addAll(subclass.allSubclasses); } } /** * Recursively find all superinterfaces of each interface; called by finalizeClassHierarchy. */ private void finalizeInterfaceHierarchyRec(InterfaceInfo interfaceInfo) { // Interface inheritance is a DAG; don't double-visit nodes if (interfaceInfo.allSuperInterfaces.isEmpty() && !interfaceInfo.superInterfaces.isEmpty()) { interfaceInfo.allSuperInterfaces.addAll(interfaceInfo.superInterfaces); for (String iface : interfaceInfo.superInterfaces) { InterfaceInfo superinterfaceInfo = interfaceNameToInterfaceInfo.get(iface); if (superinterfaceInfo != null) { finalizeInterfaceHierarchyRec(superinterfaceInfo); // Merge all ancestral interfaces into list of all superinterfaces for this interface interfaceInfo.allSuperInterfaces.addAll(superinterfaceInfo.allSuperInterfaces); } } } } /** * Find all superclasses and subclasses for each class once all classes have been read. */ private void finalizeClassHierarchy() { if (classNameToClassInfo.isEmpty() && interfaceNameToInterfaceInfo.isEmpty()) { // If no classes or interfaces were matched, there is no hierarchy to build return; } // Find all root nodes (most classes and interfaces have java.lang.Object as a superclass) ArrayList<ClassInfo> roots = new ArrayList<>(); for (ClassInfo classInfo : classNameToClassInfo.values()) { if (classInfo.directSuperclass == null) { roots.add(classInfo); } } // Accumulate all superclasses and interfaces along each branch of class hierarchy. // Traverse top down / breadth first from roots. LinkedList<ClassInfo> nodes = new LinkedList<>(); nodes.addAll(roots); while (!nodes.isEmpty()) { ClassInfo head = nodes.removeFirst(); if (head.directSuperclass != null) { // Accumulate superclasses from ancestral classes head.allSuperclasses.addAll(head.directSuperclass.allSuperclasses); } // Add subclasses to queue for BFS for (ClassInfo subclass : head.directSubclasses) { nodes.add(subclass); } } // Accumulate all subclasses along each branch of class hierarchy. // Traverse depth first, postorder from roots. for (ClassInfo root : roots) { finalizeClassHierarchyRec(root); } // Create reverse mapping from annotation to classes that have the annotation for (ClassInfo classInfo : classNameToClassInfo.values()) { for (String annotation : classInfo.annotations) { ArrayList<String> classList = annotationToClasses.get(annotation); if (classList == null) { annotationToClasses.put(annotation, classList = new ArrayList<String>()); } classList.add(classInfo.name); } } for (InterfaceInfo ii : interfaceNameToInterfaceInfo.values()) { finalizeInterfaceHierarchyRec(ii); } // Create reverse mapping from interface to classes that implement the interface for (ClassInfo classInfo : classNameToClassInfo.values()) { // Find all interfaces and superinterfaces of a class HashSet<String> interfaceAndSuperinterfaces = new HashSet<>(); for (String iface : classInfo.interfaces) { interfaceAndSuperinterfaces.add(iface); InterfaceInfo ii = interfaceNameToInterfaceInfo.get(iface); if (ii != null) { interfaceAndSuperinterfaces.addAll(ii.allSuperInterfaces); } } // Add a mapping from the interface or super-interface back to the class for (String iface : interfaceAndSuperinterfaces) { ArrayList<String> classList = interfaceToClasses.get(iface); if (classList == null) { interfaceToClasses.put(iface, classList = new ArrayList<String>()); } classList.add(classInfo.name); } } } /** * Read annotation entry from classfile. */ private String readAnnotation(final DataInputStream inp, Object[] constantPool) throws IOException { String annotationFieldDescriptor = readRefdString(inp, constantPool); String annotationClassName; if (annotationFieldDescriptor.charAt(0) == 'L' && annotationFieldDescriptor.charAt(annotationFieldDescriptor.length() - 1) == ';') { // Lcom/xyz/Annotation; -> com.xyz.Annotation annotationClassName = annotationFieldDescriptor.substring(1, annotationFieldDescriptor.length() - 1).replace('/', '.'); } else { // Should not happen annotationClassName = annotationFieldDescriptor; } int numElementValuePairs = inp.readUnsignedShort(); for (int i = 0; i < numElementValuePairs; i++) { inp.skipBytes(2); // element_name_index readAnnotationElementValue(inp, constantPool); } return annotationClassName; } /** * Read annotation element value from classfile. */ private void readAnnotationElementValue(final DataInputStream inp, Object[] constantPool) throws IOException { int tag = inp.readUnsignedByte(); switch (tag) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': // const_value_index inp.skipBytes(2); break; case 'e': // enum_const_value inp.skipBytes(4); break; case 'c': // class_info_index inp.skipBytes(2); break; case '@': // Complex (nested) annotation readAnnotation(inp, constantPool); break; case '[': // array_value final int count = inp.readUnsignedShort(); for (int l = 0; l < count; ++l) { // Nested annotation element value readAnnotationElementValue(inp, constantPool); } break; default: throw new ClassFormatError("Invalid annotation element type tag: 0x" + Integer.toHexString(tag)); } } /** * Read a string reference from a classfile, then look up the string in the constant pool. */ private static String readRefdString(DataInputStream inp, Object[] constantPool) throws IOException { int constantPoolIdx = inp.readUnsignedShort(); Object constantPoolObj = constantPool[constantPoolIdx]; return (constantPoolObj instanceof Integer ? (String) constantPool[(Integer) constantPoolObj] : (String) constantPoolObj); } /** * Directly examine contents of classfile binary header. */ private void readClassInfoFromClassfileHeader(final InputStream inputStream) throws IOException { DataInputStream inp = new DataInputStream(new BufferedInputStream(inputStream, 1024)); // Magic if (inp.readInt() != 0xCAFEBABE) { // Not classfile return; } // Minor version inp.readUnsignedShort(); // Major version inp.readUnsignedShort(); // Constant pool count (1-indexed, zeroth entry not used) int cpCount = inp.readUnsignedShort(); // Constant pool Object[] constantPool = new Object[cpCount]; for (int i = 1; i < cpCount; ++i) { final int tag = inp.readUnsignedByte(); switch (tag) { case 1: // Modified UTF8 constantPool[i] = inp.readUTF(); break; case 3: // int case 4: // float inp.skipBytes(4); break; case 5: // long case 6: // double inp.skipBytes(8); i++; // double slot break; case 7: // Class case 8: // String // Forward or backward reference a Modified UTF8 entry constantPool[i] = inp.readUnsignedShort(); break; case 9: // field ref case 10: // method ref case 11: // interface ref case 12: // name and type inp.skipBytes(4); // two shorts break; case 15: // method handle inp.skipBytes(3); break; case 16: // method type inp.skipBytes(2); break; case 18: // invoke dynamic inp.skipBytes(4); break; default: throw new ClassFormatError("Unkown tag value for constant pool entry: " + tag); } } // Access flags int flags = inp.readUnsignedShort(); boolean isInterface = (flags & 0x0200) != 0; // This class name, with slashes replaced with dots String className = readRefdString(inp, constantPool).replace('/', '.'); // Superclass name, with slashes replaced with dots String superclassName = readRefdString(inp, constantPool).replace('/', '.'); // Interfaces int interfaceCount = inp.readUnsignedShort(); ArrayList<String> interfaces = new ArrayList<>(); for (int i = 0; i < interfaceCount; i++) { interfaces.add(readRefdString(inp, constantPool).replace('/', '.')); } // Fields int fieldCount = inp.readUnsignedShort(); for (int i = 0; i < fieldCount; i++) { inp.skipBytes(6); // access_flags, name_index, descriptor_index int attributesCount = inp.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { inp.skipBytes(2); // attribute_name_index int attributeLength = inp.readInt(); inp.skipBytes(attributeLength); } } // Methods int methodCount = inp.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { inp.skipBytes(6); // access_flags, name_index, descriptor_index int attributesCount = inp.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { inp.skipBytes(2); // attribute_name_index int attributeLength = inp.readInt(); inp.skipBytes(attributeLength); } } // Attributes (including class annotations) HashSet<String> annotations = new HashSet<>(); int attributesCount = inp.readUnsignedShort(); for (int i = 0; i < attributesCount; i++) { String attributeName = readRefdString(inp, constantPool); int attributeLength = inp.readInt(); if ("RuntimeVisibleAnnotations".equals(attributeName)) { int annotationCount = inp.readUnsignedShort(); for (int m = 0; m < annotationCount; m++) { String annotationName = readAnnotation(inp, constantPool); annotations.add(annotationName); } } else { inp.skipBytes(attributeLength); } } if (isInterface) { // Save the info recovered from the classfile for an interface // Look up InterfaceInfo object for this interface InterfaceInfo thisInterfaceInfo = interfaceNameToInterfaceInfo.get(className); if (thisInterfaceInfo == null) { // This interface has not been encountered before on the classpath interfaceNameToInterfaceInfo .put(className, thisInterfaceInfo = new InterfaceInfo(interfaces)); } else { // An interface of this fully-qualified name has been encountered already earlier on // the classpath, so this interface is shadowed, ignore it return; } } else { // Save the info recovered from the classfile for a class // Look up ClassInfo object for this class ClassInfo thisClassInfo = classNameToClassInfo.get(className); if (thisClassInfo == null) { // This class has not been encountered before on the classpath classNameToClassInfo.put(className, thisClassInfo = new ClassInfo(className, interfaces, annotations)); } else if (thisClassInfo.encountered) { // A class of this fully-qualified name has been encountered already earlier on // the classpath, so this class is shadowed, ignore it return; } else { // This is the first time this class has been encountered on the classpath, but // it was previously cited as a superclass of another class thisClassInfo.encounter(interfaces, annotations); } // Look up ClassInfo object for superclass, and connect it to this class ClassInfo superclassInfo = classNameToClassInfo.get(superclassName); if (superclassInfo == null) { classNameToClassInfo.put(superclassName, superclassInfo = new ClassInfo(superclassName, thisClassInfo)); } else { superclassInfo.addSubclass(thisClassInfo); } } } /** * Scan a file. */ private void scanFile(File file, String path) throws IOException { if (path.endsWith(".class")) { // Found a classfile try (InputStream inputStream = new FileInputStream(file)) { // Inspect header of classfile readClassInfoFromClassfileHeader(inputStream); } } else { // For non-classfiles, match file paths against path patterns for (FilePathMatcher fileMatcher : filePathMatchers) { if (fileMatcher.pattern.matcher(path).matches()) { // If there's a match, open the file as a stream and call the match processor try (InputStream inputStream = new FileInputStream(file)) { fileMatcher.fileMatchProcessor.processMatch(path, inputStream); } } } } } /** * Scan a directory for matching file path patterns. */ private void scanDir(File dir, int ignorePrefixLen) throws IOException { String rawPath = dir.getPath(); String path = ignorePrefixLen > rawPath.length() ? "" : rawPath.substring(ignorePrefixLen); boolean scanDirs = false, scanFiles = false; for (String pathToScan : pathsToScan) { if (path.startsWith(pathToScan)) { // In a path that has a whitelisted path as a prefix -- can start scanning files scanDirs = scanFiles = true; break; } if (pathToScan.startsWith(path)) { // In a path that is a prefix of a whitelisted path -- keep recursively scanning dirs scanDirs = true; } } if (scanDirs || scanFiles) { File[] subFiles = dir.listFiles(); for (final File subFile : subFiles) { if (subFile.isDirectory()) { // Recurse into subdirectory scanDir(subFile, ignorePrefixLen); } else if (scanFiles && subFile.isFile()) { // Scan file scanFile(subFile, path + "/" + subFile.getName()); } } } } /** * Scan a zipfile for matching file path patterns. (Does not recurse into zipfiles within zipfiles.) */ private void scanZipfile(final ZipFile zipFile) throws IOException { for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) { // Scan for matching filenames final ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { // Only process file entries (zipfile indices contain both directory entries and // separate file entries for files within each directory, in lexicographic order) String path = entry.getName(); boolean scanFile = false; for (String pathToScan : pathsToScan) { if (path.startsWith(pathToScan)) { // File path has a whitelisted path as a prefix -- can scan file scanFile = true; break; } } if (scanFile) { if (path.endsWith(".class")) { // Found a classfile, open it as a stream and inspect header try (InputStream inputStream = zipFile.getInputStream(entry)) { readClassInfoFromClassfileHeader(inputStream); } } else { // For non-classfiles, match file paths against path patterns for (FilePathMatcher fileMatcher : filePathMatchers) { if (fileMatcher.pattern.matcher(path).matches()) { // There's a match, open the file as a stream and call the match processor try (InputStream inputStream = zipFile.getInputStream(entry)) { fileMatcher.fileMatchProcessor.processMatch(path, inputStream); } } } } } } } } /** * Scan classpath for matching files. This should be called once only, after all match processors have * been added. */ public void scan() { long scanStart = System.currentTimeMillis(); // Scan classpath components try { String[] pathElements = System.getProperty("java.class.path").split(File.pathSeparator); for (String pathElement : pathElements) { File file = new File(pathElement); String pathElementLower = pathElement.toLowerCase(); if (file.isDirectory()) { // Scan within dir path element scanDir(file, file.getPath().length() + 1); } else if (file.isFile()) { if (pathElementLower.endsWith(".jar") || pathElementLower.endsWith(".zip")) { // Scan within jar/zipfile path element scanZipfile(new ZipFile(file)); } else { // File listed directly on classpath scanFile(file, ""); } } else { Log.info("Skipping non-file/non-dir on classpath: " + file.getCanonicalPath()); } } } catch (IOException e) { throw new RuntimeException(e); } // Finalize class hierarchy, then look for class matches finalizeClassHierarchy(); for (ClassMatcher classMatcher : classMatchers) { classMatcher.lookForMatches(); } Log.info("Classpath scanning took: " + (System.currentTimeMillis() - scanStart) + " ms"); } }
package com.ninchat.client.transport; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import com.ninchat.client.transport.actions.CloseSession; import com.ninchat.client.transport.actions.ResumeSession; import com.ninchat.client.transport.events.MessageReceived; import com.ninchat.client.transport.payloads.MessagePayload; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Kari Lavikka */ public class WebSocketTransport extends AbstractTransport { private final static Logger logger = Logger.getLogger(WebSocketTransport.class.getName()); private WebSocketAdapter webSocketAdapter; private int payloadFramesLeft; private Event currentEvent; private static final long TIMEOUT_ACTION = 20 * 1000; // TODO: Configurable private static final long TIMEOUT_CHECK_LAST_EVENT = 5 * 1000; // TODO: Configurable private static final long WAIT_BEFORE_PING = 90 * 1000; // TODO: Configurable private volatile QueueHog queueHog; private volatile TimeoutMonitor timeoutMonitor; private final Gson gson = new Gson(); /** * TimeoutWatcher waits in this object */ private final Object messageSentToWebsocketHook = new Object(); public WebSocketTransport() { init(); } public void terminate() { setStatus(Status.TERMINATING); if (queueHog != null) { queueHog.interrupt(); try { queueHog.join(10000); // Timeout just for sure. Shouldn't be needed. TODO: Remove. } catch (InterruptedException e) { logger.warning("Interrupted while waiting for thread to join."); } queueHog = null; } try { // TODO: Better approach would be to signal QueueHog about termination. It's just not properly implemented. // There's already a graceful shutdown handling for "close_session" and it actually calls this terminate method. webSocketAdapter.disconnect(); } catch (WebSocketAdapterException e) { logger.log(Level.FINE, "Can not terminate", e); } super.terminate(); } /** * Prepares this transport for new session. Effectively clears all queues and initializes new worker threads */ protected void init() { super.init(); payloadFramesLeft = 0; currentEvent = null; if (queueHog == null) { queueHog = new QueueHog(); } else { logger.warning("init(): QueueHog is not null!"); } } public void setWebSocketAdapter(WebSocketAdapter webSocketAdapter) { this.webSocketAdapter = webSocketAdapter; webSocketAdapter.setWebSocketTransport(this); } @Override public Long enqueue(Action action) { synchronized (queueHog) { if (!queueHog.isAlive()) { queueHog.start(); } } return super.enqueue(action); } /** * Connects to server. It may be synchronous or asynchronous - depending on WebSocket implementation * * @return true if no errors were encountered */ private boolean connect() { if (status != Status.CLOSED) { logger.fine("Trying to connect but status is not CLOSED. Ignoring."); return false; } try { setStatus(Status.OPENING); URI uri = new URI("wss://" + host + "/socket"); logger.info("Connecting to " + uri); webSocketAdapter.setURI(uri); webSocketAdapter.connect(); return true; } catch (Exception e) { logger.log(Level.WARNING, "Can not connect", e); setStatus(Status.CLOSED); } return false; } void onOpen() { toggleTimeoutMonitor(true); setStatus(Status.OPENED); } void onClose(String reason) { toggleTimeoutMonitor(false); setStatus(Status.CLOSED); } private class DummyEvent extends Event { @Override public boolean verify() { return false; } @Override public String getEventName() { return null; } } void onMessage(Object message) { String text = (String)message; // TODO: Support binary frames if (payloadFramesLeft > 0) { logger.finest("Receiving payload: " + text); if (currentEvent instanceof PayloadEvent) { PayloadEvent pe = (PayloadEvent)currentEvent; if (currentEvent instanceof MessageReceived) { Class <? extends MessagePayload> payloadClass = MessagePayload.messageClasses.get(((MessageReceived)currentEvent).getMessageType()); try { pe.payloads[pe.payloads.length - payloadFramesLeft] = gson.fromJson(text, payloadClass); } catch (JsonSyntaxException e) { logger.log(Level.WARNING, "Can not parse JSON", e); } } else { logger.warning("Only message_received event supports payloads atm..."); } } else { logger.warning("Receiving payloadFrame although we should not!?"); } payloadFramesLeft } else { if (logger.isLoggable(Level.FINEST)) logger.finest("Receiving header: " + text); if (text == null || text.length() == 0 || text.charAt(0) != '{') { logger.finest("Empty frame!"); return; } try { String eventName = null; assert payloadFramesLeft == 0; // First we have to view received object briefly to figure out a concrete event type and the number of expected payload frames JsonReader reader = new JsonReader(new StringReader(text)); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if ("event".equals(name)) { eventName = reader.nextString(); } else if ("frames".equals(name)) { payloadFramesLeft = reader.nextInt(); } else { reader.skipValue(); } } if (eventName == null) { logger.warning("Received a header but it does not contain an event type: " + text + " ... ignoring it."); return; } Class<? extends Event> eventClass = EventClassRegistry.eventClasses.get(eventName); if (eventClass == null) { logger.warning("Can not find a concrete class for event: " + eventName + " ... ignoring it."); return; } currentEvent = gson.fromJson(text, eventClass); if (currentEvent instanceof PayloadEvent) { ((PayloadEvent)currentEvent).payloads = new Payload[payloadFramesLeft]; } // We really should not get into these exception handlers. There's a risk that we mess up payload // counters and transport state gets corrupted. TODO: Session should probably get terminated now... } catch (JsonSyntaxException e) { logger.log(Level.SEVERE, "Error while parsing websocket message: " + message, e); } catch (IOException e) { logger.log(Level.SEVERE, "Error while parsing websocket message: " + message, e); } } if (payloadFramesLeft <= 0) { // First remove action from queue Action action = removeActionFromQueue(currentEvent); // Then call generic listeners that are bound to transport and model onCompleteEvent(currentEvent); // Finally call specific listener that is bound to individual event. Now model is already updated when // listener gets a notification. if (action != null && action.isExpectActionId()) { acknowledge(action, currentEvent); } } } private void timeout() { logger.info("Timeout! Closing connection..."); try { webSocketAdapter.disconnect(); } catch (WebSocketAdapterException e) { logger.log(Level.WARNING, "Can not disconnect", e); } } private void toggleTimeoutMonitor(boolean run) { if (run) { if (timeoutMonitor == null || !timeoutMonitor.isAlive()) { timeoutMonitor = new TimeoutMonitor(); timeoutMonitor.start(); } } else { if (timeoutMonitor != null) { timeoutMonitor.interrupt(); timeoutMonitor = null; } } } private class TimeoutMonitor extends Thread { @Override public void run() { try { setName("TimeoutMonitor"); } catch (SecurityException e) { logger.log(Level.WARNING, "Can not set thread name", e); } logger.info("TimeoutMonitor: started!"); try { while (!isInterrupted()) { Action action = null; // Pick tail of the queue synchronized (queue) { if (!queue.isEmpty()) { action = queue.last(); } } if (action != null && action.getSent() > Long.MIN_VALUE) { // Found an unacknowledged action. This logic is somewhat complicated because actions are // acknowledged when they are picked from queue for processing. Timeout may get triggered // if processing is too slow. This can be worked around by adding yet another queue, but // that would be overly complicated. Currently the problem is mitigated by checking the timestamp // of the previous acknowledged action. If it was just a while ago, we are probably busy // processing the event. An "inEventListener" variable could also be introduced. logger.finer("TimeoutMonitor: Found an unacknowledged action #" + action.getId() + " from queue."); long currentTime = System.currentTimeMillis(); long timeLeft = action.getSent() + TIMEOUT_ACTION - currentTime; if (timeLeft < 0) { // Already beyond timeout logger.fine("TimeoutMonitor: Found a timed out action " + action + " which was sent " + (currentTime - action.getSent()) + " ms ago"); long lastAck = currentTime - lastAcknowledgedActionTimestamp.get(); if (currentTime - lastAcknowledgedActionTimestamp.get() < TIMEOUT_CHECK_LAST_EVENT) { long nap = TIMEOUT_CHECK_LAST_EVENT - lastAck; logger.fine("TimeoutMonitor: However, previous event was acknowledged just " + lastAck + " ms ago. Let's wait " + nap + " ms. Maybe we are just so busy handling response events."); sleep(nap); } else { timeout(); } } else { logger.finer("TimeoutMonitor: Waiting " + timeLeft + "ms for timeout."); // Wait until timeout sleep(timeLeft); // And check if action is still unacknowledged boolean acknowledged; synchronized (queue) { acknowledged = !queue.contains(action); } if (!acknowledged) { // Still in queue. Check time left again because it might have been modified during sleep. timeLeft = action.getSent() + TIMEOUT_ACTION - currentTime; if (timeLeft < 0) { logger.fine("TimeoutMonitor: Action #" + action.getId() + " timed out while waiting for acknowledgement! " + action.toString()); timeout(); } } else { logger.finer("TimeoutMonitor: Action #" + action.getId() + " was acknowledged during wait."); } } } else { // There are no unacknowledged actions // TODO: Ping logic probably needs some polishment. Doesn't look that nice... long timeUntilPing = Math.max(lastSentActionTimestamp.get(), lastAcknowledgedActionTimestamp.get()) - System.currentTimeMillis() + WAIT_BEFORE_PING; timeUntilPing = Math.max(timeUntilPing, 5000); // Wait at least 5 sec. Kluns... logger.finest("TimeoutMonitor: Queue is empty. Waiting " + timeUntilPing + "ms, until a message has been sent to WebSocket or it is time to PING."); synchronized (messageSentToWebsocketHook) { messageSentToWebsocketHook.wait(timeUntilPing); } // Check whether wake up was for a ping or a new queued message timeUntilPing = Math.max(lastSentActionTimestamp.get(), lastAcknowledgedActionTimestamp.get()) - System.currentTimeMillis() + WAIT_BEFORE_PING; if (timeUntilPing < 0 && status == Status.OPENED && sessionId != null) { // Only ping if session is established ping(); } } } } catch (InterruptedException e) { logger.fine("TimeoutMonitor: Thread interrupted"); } logger.info("TimeoutMonitor: Thread terminates"); } }; private class QueueHog extends Thread { final long initialReconnectDelay = 1000; long reconnectDelay = initialReconnectDelay; @Override public void run() { try { setName("QueueHog"); } catch (SecurityException e) { logger.log(Level.WARNING, "Can not set thread name", e); } logger.info("QueueHog: Thread started!"); try { pickFromQueue: while (!isInterrupted()) { Action action; // Wait for something to send synchronized (queue) { do { if (lastSentAction == null) { // Pick first if nothing has been sent before action = queue.isEmpty() ? null : queue.first(); } else { // Or the next one action = queue.higher(lastSentAction); } if (action == null) { logger.fine("QueueHog: Got nothing from queue. Waiting for action."); queue.wait(); } } while (action == null); } // Open connection if it is closed while (status != Status.OPENED) { if (status == Status.CLOSED) { logger.fine("QueueHog: calling connect()"); connect(); } synchronized (statusHook) { if (status == Status.OPENING) { logger.info("QueueHog: Waiting for opened connection"); statusHook.wait(); // WebSocket onOpen callback wakes me up } } if (status == Status.CLOSED) { logger.fine("QueueHog: Connection attempt failed"); // If connect failed ... logger.fine("QueueHog: Sleeping " + reconnectDelay + "ms before trying again"); sleep(reconnectDelay); reconnectDelay *= 1.5; } else if (status == Status.OPENED) { if (sessionId != null) { logger.fine("QueueHog: Resuming session"); // If connection was opened and session is is present try { Action r = new ResumeSession(); r.setSessionId(sessionId); r.setEventId(eventId.get()); JsonElement element = gson.toJsonTree(r); element.getAsJsonObject().addProperty("action", r.getActionName()); String json = gson.toJson(element); logger.finer("QueueHog: sending resume_session to WebSocket: " + json); webSocketAdapter.send(json); // If resume_session fails, we get an error event with error type "session_not_found" reconnectDelay = initialReconnectDelay; // TODO: This should probably be set after successful session negotiation rewindQueue(); continue pickFromQueue; } catch (Exception e) { logger.log(Level.WARNING, "Can't send resume_session", e); // TODO: Terminate session gracefully } } else { logger.fine("QueueHog: Got a connection"); reconnectDelay = initialReconnectDelay; // TODO: This should probably be set after successful session negotiation } } } // Include action name and payload count JsonElement element = gson.toJsonTree(action); element.getAsJsonObject().addProperty("action", action.getActionName()); if (action instanceof PayloadAction) { element.getAsJsonObject().addProperty("frames", ((PayloadAction)action).getPayloadCount()); } String header = gson.toJson(element); boolean closingRequest = action instanceof CloseSession; if (closingRequest) { logger.fine("QueueHog: Sending close_session action. I'll quit after this action!"); } try { logger.finer("QueueHog: sending header to WebSocket: " + header); webSocketAdapter.send(header); if (action instanceof PayloadAction) { Payload [] payloads = ((PayloadAction)action).getPayloads(); if (payloads != null && payloads.length >= 1) { for (Payload payload : payloads) { String json = "{}"; if (payload != null) { json = gson.toJson(payload); } logger.finer("QueueHog: sending payload to WebSocket: " + json); webSocketAdapter.send(json); } } } lastSentActionTimestamp.set(System.currentTimeMillis()); if (action.isExpectActionId()) { action.flagSent(); synchronized (messageSentToWebsocketHook) { messageSentToWebsocketHook.notifyAll(); } synchronized (queue) { lastSentAction = action; } } else { // Actions without actionId must not be retransmitted or tracked by TimeoutMonitor synchronized (queue) { queue.remove(action); } } } catch (WebSocketAdapterException e) { logger.log(Level.WARNING, "Problem with WebSocket.", e); setStatus(Status.CLOSED); } if (closingRequest) { logger.fine("QueueHog: Terminating transport and stopping QueueHog."); terminate(); return; } } } catch (InterruptedException e) { logger.fine("QueueHog: Thread interrupted"); } finally { logger.fine("QueueHog: Thread terminates"); } } } }
package battleships.backend.classhelpers; public class DeployPieceCounter { private boolean piecesLeftToDeploy; private int piecesOfLenghtTwo; private int piecesOfLenghtThree; private int piecesOfLenghtFour; private int piecesOfLenghtFive; private int totalPiecesToDeploy; public DeployPieceCounter() { this(true, 4, 3, 2, 1); } public DeployPieceCounter(boolean piecesLeftToDeploy, int piecesOfLengthTwo, int piecesOfLengthThree, int piecesOfLengthFour, int piecesOfLengthFive) { this.piecesLeftToDeploy = piecesLeftToDeploy; this.piecesOfLenghtTwo = piecesOfLengthTwo; this.piecesOfLenghtThree = piecesOfLengthThree; this.piecesOfLenghtFour = piecesOfLengthFour; this.piecesOfLenghtFive = piecesOfLengthFive; this.totalPiecesToDeploy = piecesOfLengthTwo + piecesOfLengthThree + piecesOfLengthFour + piecesOfLengthFive; } public boolean hasPiecesLeftToDeploy() { return piecesLeftToDeploy; } public boolean deployPieceOfLenghtTwo() { if (piecesOfLenghtTwo>0) { piecesOfLenghtTwo decreaseTotalPieces(); return true; } return false; } public void decreaseTotalPieces() { this.totalPiecesToDeploy if (totalPiecesToDeploy==0) piecesLeftToDeploy = false; } public boolean deployPieceOfLenghtThree() { if (piecesOfLenghtThree>0) { piecesOfLenghtThree decreaseTotalPieces(); return true; } return false; } public boolean deployPieceOfLenghtFour() { if (piecesOfLenghtFour>0) { piecesOfLenghtFour decreaseTotalPieces(); return true; } return false; } public boolean deployPieceOfLenghtFive() { if (piecesOfLenghtFive>0) { piecesOfLenghtFive decreaseTotalPieces(); return true; } return false; } public int getPiecesOfLengthTwo() { return piecesOfLenghtTwo; } public int getPiecesOfLengthThree() { return piecesOfLenghtThree; } public int getPiecesOfLengthFour() { return piecesOfLenghtFour; } public int getPiecesOfLengthFive() { return piecesOfLenghtFive; } }
package lpn.parser; import java.util.Properties; public class Variable { private String name; private String type; protected String initValue; private String initRate; private String port; public Variable(String name, String type) { this.name = name; this.type = type; } public Variable(String name, String type, String initValue) { this.name = name; this.type = type; this.initValue = initValue; } public Variable(String name, String type, Properties initCond) { if (type.equals(CONTINUOUS)) { this.name = name; this.type = type; this.initValue = initCond.getProperty("value"); this.initRate = initCond.getProperty("rate"); } } public Variable(String name, String type, String initValue, String port) { this.name = name; this.type = type; this.initValue = initValue; this.port = port; } public void addInitValue(String initValue) { this.initValue = initValue; } public void addInitRate(String initRate) { this.initRate = initRate; } public void addInitCond(Properties initCond) { if (type.equals(CONTINUOUS)) { this.initValue = initCond.getProperty("value"); this.initRate = initCond.getProperty("rate"); } } public String getName() { return name; } public String getInitValue() { return initValue; } public String getInitRate() { return initRate; } public boolean isInput() { if (port != null) { return port.equals(INPUT); } return false; } public boolean isOutput() { if (port != null) { return port.equals(OUTPUT); } return false; } public boolean isInternal() { if (port != null) { return port.equals(INTERNAL); } return true; } public String getPort() { return port; } public String getType() { return type; } public void setPort(String newPort) { port = newPort; } @Override public String toString() { return name; } @Override public boolean equals(Object var) { return name.equals(var.toString()); } public static final String BOOLEAN = "boolean"; public static final String INTEGER = "integer"; public static final String CONTINUOUS = "continuous"; public static final String INPUT = "input"; public static final String OUTPUT = "output"; public static final String INTERNAL = "internal"; }
package com.redhat.ceylon.compiler.js; import static java.lang.Character.toUpperCase; import java.io.IOException; import java.io.Writer; import java.util.List; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Getter; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AndOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnnotationList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AssignOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeGetterDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeSetterDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseTypeExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BinaryOperatorExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Block; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Body; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CharLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompareOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.tree.Tree.DifferenceOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.EqualOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ExecutableStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ExtendedType; import com.redhat.ceylon.compiler.typechecker.tree.Tree.FloatLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Tree.IdenticalOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Import; import com.redhat.ceylon.compiler.typechecker.tree.Tree.InterfaceDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.InterfaceDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.InvocationExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.LargeAsOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.LargerOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NamedArgument; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NamedArgumentList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NaturalLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NegativeOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NotEqualOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.NotOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ObjectDefinition; import com.redhat.ceylon.compiler.typechecker.tree.Tree.OrOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Outer; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Parameter; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ParameterList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgument; import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgumentList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositiveOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.PowerOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ProductOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberOrTypeExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedTypeExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QuotientOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.RemainderOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Return; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SatisfiedTypes; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SequenceEnumeration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SequencedArgument; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SimpleType; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SmallAsOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SmallerOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Statement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.StringLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SumOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Super; import com.redhat.ceylon.compiler.typechecker.tree.Tree.This; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Writer out; boolean prototypeStyle; @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } public GenerateJsVisitor(Writer out, boolean prototypeStyle) { this.out = out; this.prototypeStyle=prototypeStyle; } private void out(String code) { try { out.write(code); } catch (IOException ioe) { ioe.printStackTrace(); } } int indentLevel = 0; private void indent() { for (int i=0;i<indentLevel;i++) { out(" "); } } private void endLine() { out("\n"); indent(); } private void beginBlock() { indentLevel++; out("{"); endLine(); } private void endBlock() { indentLevel endLine(); out("}"); endLine(); } private void location(Node node) { out(" at "); out(node.getUnit().getFilename()); out(" ("); out(node.getLocation()); out(")"); } @Override public void visit(CompilationUnit that) { Module clm = that.getUnit().getPackage().getModule() .getLanguageModule(); require(clm.getPackage(clm.getNameAsString())); super.visit(that); } @Override public void visit(Import that) { require(that.getImportList().getImportedPackage()); } private void require(Package pkg) { out("var "); packageAlias(pkg); out("=require('"); scriptPath(pkg); out("');"); endLine(); } private void packageAlias(Package pkg) { out("$$$"); //out(pkg.getNameAsString().replace('.', '$')); for (String s: pkg.getName()) { out(s.substring(0,1)); } out(Integer.toString(pkg.getQualifiedNameString().length())); } private void scriptPath(Package pkg) { out(pkg.getModule().getNameAsString().replace('.', '/')); out("/"); if (!pkg.getModule().isDefault()) { out(pkg.getModule().getVersion()); out("/"); } out(pkg.getNameAsString()); } @Override public void visit(Parameter that) { out(that.getDeclarationModel().getName()); } @Override public void visit(ParameterList that) { out("("); boolean first=true; for (Parameter param: that.getParameters()) { if (!first) out(","); out(param.getDeclarationModel().getName()); first = false; } out(")"); } @Override public void visit(Body that) { List<Statement> stmnts = that.getStatements(); for (int i=0; i<stmnts.size(); i++) { Statement s = stmnts.get(i); s.visit(this); if (s instanceof ExecutableStatement) { endLine(); } } } @Override public void visit(Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); endLine(); } else { beginBlock(); for (int i=0; i<stmnts.size(); i++) { Statement s = stmnts.get(i); s.visit(this); if (i<stmnts.size()-1 && s instanceof ExecutableStatement) { endLine(); } } endBlock(); } } private void comment(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration that) { endLine(); out(" out(that.getNodeType()); out(" "); out(that.getDeclarationModel().getName()); location(that); endLine(); } private void var(Declaration d) { out("var "); out(d.getName()); out("="); } private void share(Declaration d) { if (d.isShared() || prototypeStyle && d.isCaptured()) { outerSelf(d); out("."); out(d.getName()); out("="); out(d.getName()); out(";"); endLine(); } } @Override public void visit(ClassDeclaration that) { Class d = that.getDeclarationModel(); comment(that); var(d); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel() .getDeclaration(); qualify(that,dec); out(dec.getName()); out(";"); endLine(); superRef(d); share(d); } @Override public void visit(InterfaceDeclaration that) { Interface d = that.getDeclarationModel(); comment(that); var(d); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel() .getDeclaration(); qualify(that,dec); out(";"); share(d); } private void newObject() { out("new CeylonObject;"); } private void function() { out("function "); } @Override public void visit(InterfaceDefinition that) { Interface d = that.getDeclarationModel(); comment(that); defineType(d); copyInterfacePrototypes(that.getSatisfiedTypes(), d); for (Statement s: that.getInterfaceBody().getStatements()) { addToPrototype(d, s); } function(); out(d.getName()); out("("); self(); out(")"); beginBlock(); declareSelf(d); that.getInterfaceBody().visit(this); returnSelf(d); endBlock(); share(d); } @Override public void visit(ClassDefinition that) { Class d = that.getDeclarationModel(); comment(that); defineType(d); copySuperclassPrototype(that.getExtendedType(),d); copyInterfacePrototypes(that.getSatisfiedTypes(), d); for (Statement s: that.getClassBody().getStatements()) { addToPrototype(d, s); } function(); out(d.getName()); out("("); for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } self(); out(")"); beginBlock(); declareSelf(d); callSuperclass(that.getExtendedType(), d); callInterfaces(that.getSatisfiedTypes(), d); if (prototypeStyle) { for (Parameter p: that.getParameterList().getParameters()) { if (p.getDeclarationModel().isCaptured()) { self(); out("."); out(p.getDeclarationModel().getName()); out("="); out(p.getDeclarationModel().getName()); out(";"); endLine(); } } } that.getClassBody().visit(this); returnSelf(d); endBlock(); share(d); } private void callSuperclass(ExtendedType extendedType, Class d) { if (extendedType!=null) { out(extendedType.getType().getDeclarationModel().getName()); out("("); for (PositionalArgument arg: extendedType.getInvocationExpression() .getPositionalArgumentList().getPositionalArguments()) { arg.visit(this); out(","); } self(); out(")"); out(";"); endLine(); } } private void callInterfaces(SatisfiedTypes satisfiedTypes, Class d) { if (satisfiedTypes!=null) for (SimpleType st: satisfiedTypes.getTypes()) { out(st.getDeclarationModel().getName()); out("("); self(); out(")"); out(";"); endLine(); } } private void defineType(ClassOrInterface d) { if (prototypeStyle) { function(); out("$"); out(d.getName()); out("(){}"); endLine(); } } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, Statement s) { prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } if (s instanceof AttributeSetterDefinition) { addSetterToPrototype(d, (AttributeSetterDefinition)s); } if (s instanceof AttributeDeclaration) { addGetterAndSetterToPrototype(d, (AttributeDeclaration)s); } prototypeOwner = null; } private void declareSelf(ClassOrInterface d) { out("if ("); self(); out("===undefined)"); self(); out("="); if (prototypeStyle) { out("new $"); out(d.getName()); out(";"); } else { newObject(); } endLine(); out("var "); self(d); out("="); self(); out(";"); endLine(); } private void instantiateSelf(ClassOrInterface d) { out("var "); self(); out("="); if (prototypeStyle) { out("new $"); out(d.getName()); out(";"); } else { newObject(); } endLine(); } private void returnSelf(ClassOrInterface d) { out("return "); self(); out(";"); } private void copyMembersToPrototype(SimpleType that, Declaration d) { copyMembersToPrototype("$"+that.getDeclarationModel().getName(), d); } private void copyMembersToPrototype(String from, Declaration d) { out("for(var $ in "); out(from); out(".prototype){$"); out(d.getName()); out(".prototype[$]="); out(from); out(".prototype[$]}"); endLine(); out("for(var $ in "); out(from); out(".prototype){$"); out(d.getName()); out(".prototype[$+'$']="); out(from); out(".prototype[$]}"); endLine(); } private void copySuperclassPrototype(ExtendedType that, Declaration d) { if (prototypeStyle) { if (that==null) { copyMembersToPrototype("CeylonObject", d); } else { copyMembersToPrototype(that.getType(), d); } } } private void copyInterfacePrototypes(SatisfiedTypes that, Declaration d) { if (prototypeStyle && that!=null) { for (Tree.SimpleType st: that.getTypes()) { copyMembersToPrototype(st, d); } } } @Override public void visit(ObjectDefinition that) { Value d = that.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); comment(that); defineType(c); copySuperclassPrototype(that.getExtendedType(),d); copyInterfacePrototypes(that.getSatisfiedTypes(),d); for (Statement s: that.getClassBody().getStatements()) { addToPrototype(c, s); } out("var $"); out(d.getName()); out("="); function(); out(d.getName()); out("()"); beginBlock(); instantiateSelf(c); callSuperclass(that.getExtendedType(), c); callInterfaces(that.getSatisfiedTypes(), c); that.getClassBody().visit(this); returnSelf(c); indentLevel endLine(); out("}();"); endLine(); if (d.isShared()) { outerSelf(d); out("."); out(getter(d)); out("="); } function(); out(getter(d)); out("()"); beginBlock(); out("return $"); out(d.getName()); out(";"); endBlock(); } private void superRef(Declaration d) { if (d.isActual()) { outerSelf(d); out("."); out(d.getName()); out("$="); outerSelf(d); out("."); out(d.getName()); out(";"); endLine(); } } private void superGetterRef(Declaration d) { if (d.isActual()) { outerSelf(d); out("."); out(getter(d)); out("$="); outerSelf(d); out("."); out(getter(d)); out(";"); endLine(); } } private void superSetterRef(Declaration d) { if (d.isActual()) { outerSelf(d); out("."); out(setter(d)); out("$="); outerSelf(d); out("."); out(setter(d)); out(";"); endLine(); } } @Override public void visit(MethodDeclaration that) {} @Override public void visit(MethodDefinition that) { Method d = that.getDeclarationModel(); if (prototypeStyle&&d.isClassOrInterfaceMember()) return; comment(that); function(); out(d.getName()); //TODO: if there are multiple parameter lists // do the inner function declarations super.visit(that); superRef(d); share(d); } private void addMethodToPrototype(Declaration outer, MethodDefinition that) { Method d = that.getDeclarationModel(); if (!prototypeStyle||!d.isClassOrInterfaceMember()) return; comment(that); out("$"); out(outer.getName()); out(".prototype."); out(d.getName()); out("="); function(); out(d.getName()); //TODO: if there are multiple parameter lists // do the inner function declarations super.visit(that); } @Override public void visit(AttributeGetterDefinition that) { Getter d = that.getDeclarationModel(); if (prototypeStyle&&d.isClassOrInterfaceMember()) return; comment(that); function(); out(getter(d)); out("()"); super.visit(that); superGetterRef(d); shareGetter(d); } private void addGetterToPrototype(Declaration outer, AttributeGetterDefinition that) { Getter d = that.getDeclarationModel(); if (!prototypeStyle||!d.isClassOrInterfaceMember()) return; comment(that); out("$"); out(outer.getName()); out(".prototype."); out(getter(d)); out("="); function(); out(getter(d)); out("()"); super.visit(that); } private void shareGetter(MethodOrValue d) { if (d.isShared() || prototypeStyle && d.isCaptured()) { outerSelf(d); out("."); out(getter(d)); out("="); out(getter(d)); out(";"); endLine(); } } @Override public void visit(AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if (prototypeStyle&&d.isClassOrInterfaceMember()) return; comment(that); function(); out(setter(d)); out("("); out(d.getName()); out(")"); super.visit(that); superSetterRef(d); shareSetter(d); } private void addSetterToPrototype(Declaration outer, AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if (!prototypeStyle||!d.isClassOrInterfaceMember()) return; comment(that); out("$"); out(outer.getName()); out(".prototype."); out(setter(d)); out("="); function(); out(setter(d)); out("("); out(d.getName()); out(")"); super.visit(that); } private void shareSetter(MethodOrValue d) { if (d.isShared() || prototypeStyle && d.isCaptured()) { outerSelf(d); out("."); out(setter(d)); out("="); out(setter(d)); out(";"); endLine(); } } @Override public void visit(AttributeDeclaration that) { Value d = that.getDeclarationModel(); if (!d.isFormal()) { comment(that); if (prototypeStyle&&d.isClassOrInterfaceMember()) { if (that.getSpecifierOrInitializerExpression()!=null) { outerSelf(d); out("."); out(d.getName()); out("="); super.visit(that); out(";"); endLine(); } } else { out("var $"); out(d.getName()); if (that.getSpecifierOrInitializerExpression()!=null) { out("="); } super.visit(that); out(";"); endLine(); function(); out(getter(d)); out("()"); beginBlock(); out("return $"); out(d.getName()); out(";"); endBlock(); superGetterRef(d); shareGetter(d); if (d.isVariable()) { function(); out(setter(d)); out("("); out(d.getName()); out(")"); beginBlock(); out("$"); out(d.getName()); out("="); out(d.getName()); out(";"); endBlock(); superSetterRef(d); shareSetter(d); } } } } private void addGetterAndSetterToPrototype(Declaration outer, AttributeDeclaration that) { Value d = that.getDeclarationModel(); if (!prototypeStyle||d.isToplevel()) return; if (!d.isFormal()) { comment(that); out("$"); out(outer.getName()); out(".prototype."); out(getter(d)); out("="); function(); out(getter(d)); out("()"); beginBlock(); out("return this."); out(d.getName()); out(";"); endBlock(); if (d.isVariable()) { out("$"); out(outer.getName()); out(".prototype."); out(setter(d)); out("="); function(); out(setter(d)); out("("); out(d.getName()); out(")"); beginBlock(); out("this."); out(d.getName()); out("="); out(d.getName()); out(";"); endBlock(); } } } private void clAlias() { out("$$$cl15"); } @Override public void visit(CharLiteral that) { clAlias(); out(".Character("); out(that.getText().replace('`', '"')); out(")"); } @Override public void visit(StringLiteral that) { clAlias(); out(".String("); out(that.getText()); out(")"); } @Override public void visit(FloatLiteral that) { clAlias(); out(".Float("); out(that.getText()); out(")"); } @Override public void visit(NaturalLiteral that) { clAlias(); out(".Integer("); out(that.getText()); out(")"); } @Override public void visit(This that) { //TODO: not quite correct cos of control structures! if (prototypeStyle && !(that.getScope() instanceof ClassOrInterface)) { out("this"); } else { self(); } } @Override public void visit(Super that) { if (prototypeStyle && !(that.getScope() instanceof ClassOrInterface)) { //TODO: not quite correct cos of control structures! out("this"); } else { self(); } } @Override public void visit(Outer that) { self(that.getTypeModel().getDeclaration()); } @Override public void visit(BaseMemberExpression that) { qualify(that, that.getDeclaration()); if (that.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter || that.getDeclaration() instanceof Method) { out(that.getDeclaration().getName()); } else { out(getter(that.getDeclaration())); out("()"); } } @Override public void visit(QualifiedMemberExpression that) { super.visit(that); boolean sup = that.getPrimary() instanceof Super; //Big TODO: make sure the member is actually // refined by the current class! out("."); if (that.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter || that.getDeclaration() instanceof Method) { out(that.getDeclaration().getName()); if (sup) out("$"); } else { out(getter(that.getDeclaration())); if (sup) out("$"); out("()"); } } @Override public void visit(BaseTypeExpression that) { qualify(that, that.getDeclaration()); out(that.getDeclaration().getName()); } @Override public void visit(QualifiedTypeExpression that) { super.visit(that); out("."); out(that.getDeclaration().getName()); } @Override public void visit(InvocationExpression that) { if (that.getNamedArgumentList()!=null) { out("(function (){"); that.getNamedArgumentList().visit(this); out("return "); that.getPrimary().visit(this); out("("); if (that.getPrimary().getDeclaration() instanceof Functional) { Functional f = (Functional) that.getPrimary().getDeclaration(); if (!f.getParameterLists().isEmpty()) { boolean first=true; for (com.redhat.ceylon.compiler.typechecker.model.Parameter p: f.getParameterLists().get(0).getParameters()) { if (!first) out(","); out("$"); out(p.getName()); first = false; } } } out(")}())"); } else { super.visit(that); } } @Override public void visit(PositionalArgumentList that) { out("("); boolean first=true; boolean sequenced=false; for (PositionalArgument arg: that.getPositionalArguments()) { if (!first) out(","); if (!sequenced && arg.getParameter().isSequenced()) { sequenced=true; clAlias(); out(".ArraySequence(["); } arg.visit(this); first = false; } if (sequenced) { out("])"); } out(")"); } @Override public void visit(NamedArgumentList that) { for (NamedArgument arg: that.getNamedArguments()) { out("var $"); out(arg.getParameter().getName()); out("="); arg.visit(this); out(";"); } SequencedArgument sarg = that.getSequencedArgument(); if (sarg!=null) { out("var $"); out(sarg.getParameter().getName()); out("="); sarg.visit(this); out(";"); } } @Override public void visit(SequencedArgument that) { clAlias(); out(".ArraySequence(["); boolean first=true; for (Expression arg: that.getExpressionList().getExpressions()) { if (!first) out(","); arg.visit(this); first = false; } out("])"); } @Override public void visit(SequenceEnumeration that) { clAlias(); out(".ArraySequence(["); boolean first=true; for (Expression arg: that.getExpressionList().getExpressions()) { if (!first) out(","); arg.visit(this); first = false; } out("])"); } @Override public void visit(SpecifierStatement that) { BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getBaseMemberExpression(); qualify(that, bme.getDeclaration()); out(bme.getDeclaration().getName()); out("="); that.getSpecifierExpression().visit(this); } @Override public void visit(AssignOp that) { BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getLeftTerm(); qualify(that, bme.getDeclaration()); out(setter(bme.getDeclaration())); out("("); that.getRightTerm().visit(this); if (bme.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter) {} else { out(")"); } } private void qualify(Node that, Declaration d) { if (isImported(that, d)) { packageAlias(d.getUnit().getPackage()); out("."); } else if (prototypeStyle) { if (d.isClassOrInterfaceMember() && !(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (d.getContainer().equals(prototypeOwner)) { out("this"); } else if (id==null) { self(); } else if (id.equals(prototypeOwner)) { out("this"); } else { self(id); } out("."); } } else if (d.isShared() && d.isClassOrInterfaceMember()) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { self(); } else { self(id); } out("."); } } private boolean isImported(Node that, Declaration d) { return !d.getUnit().getPackage() .equals(that.getUnit().getPackage()); } @Override public void visit(ExecutableStatement that) { super.visit(that); out(";"); } @Override public void visit(Expression that) { if (prototypeStyle && that.getTerm() instanceof QualifiedMemberOrTypeExpression) { QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); if (term.getDeclaration() instanceof Functional) { out("function(){var $="); term.getPrimary().visit(this); out(";$."); out(term.getDeclaration().getName()); out(".apply($,arguments)}"); return; } } super.visit(that); } @Override public void visit(Return that) { out("return "); super.visit(that); } @Override public void visit(AnnotationList that) {} private void self(TypeDeclaration d) { out("$$"); out(d.getName().substring(0,1).toLowerCase()); out(d.getName().substring(1)); } private void self() { out("$$"); } private void outerSelf(Declaration d) { if (d.isToplevel()) { out("this"); } else { self(); } } private String setter(Declaration d) { return "set" + toUpperCase(d.getName().charAt(0)) + d.getName().substring(1); } private String getter(Declaration d) { return "get" + toUpperCase(d.getName().charAt(0)) + d.getName().substring(1); } @Override public void visit(SumOp that) { that.getLeftTerm().visit(this); out(".plus("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(DifferenceOp that) { that.getLeftTerm().visit(this); out(".minus("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(ProductOp that) { that.getLeftTerm().visit(this); out(".times("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(QuotientOp that) { that.getLeftTerm().visit(this); out(".divided("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(RemainderOp that) { that.getLeftTerm().visit(this); out(".remainder("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(PowerOp that) { that.getLeftTerm().visit(this); out(".power("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(NegativeOp that) { that.getTerm().visit(this); out(".negativeValue()"); } @Override public void visit(PositiveOp that) { that.getTerm().visit(this); out(".positiveValue()"); } @Override public void visit(EqualOp that) { leftEqualsRight(that); } @Override public void visit(NotEqualOp that) { leftEqualsRight(that); equalsFalse(); } @Override public void visit(NotOp that) { that.getTerm().visit(this); equalsFalse(); } @Override public void visit(IdenticalOp that) { out("("); that.getLeftTerm().visit(this); out("==="); that.getRightTerm().visit(this); thenTrueElseFalse(); out(")"); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { leftCompareRight(that); out(".equals("); clAlias(); out(".getSmaller())"); } @Override public void visit(LargerOp that) { leftCompareRight(that); out(".equals("); clAlias(); out(".getLarger())"); } @Override public void visit(SmallAsOp that) { out("("); leftCompareRight(that); out("!=="); clAlias(); out(".getLarger()"); thenTrueElseFalse(); out(")"); } @Override public void visit(LargeAsOp that) { out("("); leftCompareRight(that); out("!=="); clAlias(); out(".getSmaller()"); thenTrueElseFalse(); out(")"); } private void leftEqualsRight(BinaryOperatorExpression that) { that.getLeftTerm().visit(this); out(".equals("); that.getRightTerm().visit(this); out(")"); } private void clTrue() { clAlias(); out(".getTrue()"); } private void clFalse() { clAlias(); out(".getFalse()"); } private void equalsFalse() { out(".equals("); clFalse(); out(")"); } private void thenTrueElseFalse() { out("?"); clTrue(); out(":"); clFalse(); } private void leftCompareRight(BinaryOperatorExpression that) { that.getLeftTerm().visit(this); out(".compare("); that.getRightTerm().visit(this); out(")"); } @Override public void visit(AndOp that) { out("("); that.getLeftTerm().visit(this); out("==="); clTrue(); out("?"); that.getRightTerm().visit(this); out(":"); clFalse(); out(")"); } @Override public void visit(OrOp that) { out("("); that.getLeftTerm().visit(this); out("==="); clTrue(); out("?"); clTrue(); out(":"); that.getRightTerm().visit(this); out(")"); } }
package org.broad.igv.feature.tribble; import org.broad.igv.variant.vcf.VCFVariant; import org.broad.tribble.FeatureCodec; import org.broad.tribble.source.BasicFeatureSource; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; public class CachingFeatureReaderTest { String path = "test/largedata/CEU.SRP000032.2010_03.genotypes.vcf.gz"; BasicFeatureSource baseReader; CachingFeatureReader cacheReader; @Before public void setUp() throws IOException { FeatureCodec codec = CodecFactory.getCodec(path); baseReader = BasicFeatureSource.getFeatureSource(path, codec); cacheReader = new CachingFeatureReader(baseReader); } @Test /* 1 182773022 182773023 1 182773812 182773813 1 182774171 182774172 1 182774425 182774426 1 182774496 182774497 1 182774630 182774631 1 182774894 182774895 1 182775195 182775196 1 182775253 182775254 1 182776704 182776705 1 182776741 182776742 */ public void testGetSequenceNames() throws Exception { List<String> seqNames = cacheReader.getSequenceNames(); assertEquals(23, seqNames.size()); } @Test public void testQuery() throws Exception { Set<String> baseReaderLoci = new HashSet(); final int start = 182773022; final int end = 182776742; final String chr = "1"; Iterator<VCFVariant> iter = baseReader.query(chr, start, end); while (iter.hasNext()) { VCFVariant var = iter.next(); assertEquals(chr, var.getChr()); assertTrue(var.getEnd() >= start && var.getStart() <= end); baseReaderLoci.add(getLocusString(var)); } assertTrue(baseReaderLoci.size() > 0); // Now use CachingFeatureReader and insure results are the same Set<String> cacheReaderLoci = new HashSet(); iter = cacheReader.query(chr, start, end); while (iter.hasNext()) { VCFVariant var = iter.next(); assertEquals(chr, var.getChr()); assertTrue(var.getEnd() >= start && var.getStart() <= end); cacheReaderLoci.add(getLocusString(var)); } assertEquals(baseReaderLoci.size(), cacheReaderLoci.size()); for (String locus : cacheReaderLoci) { assertTrue(baseReaderLoci.contains(locus)); } } String getLocusString(VCFVariant variant) { return variant.getChr() + ":" + variant.getStart() + "-" + variant.getEnd(); } }
package com.redhat.ceylon.model.loader.model; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.JDKUtils; import com.redhat.ceylon.model.cmr.PathFilter; import com.redhat.ceylon.model.loader.AbstractModelLoader; import com.redhat.ceylon.model.loader.ContentAwareArtifactResult; import com.redhat.ceylon.model.loader.JvmBackendUtil; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.model.Package; public abstract class LazyModule extends Module { private boolean isJava = false; protected Set<String> jarPackages = new HashSet<String>(); public LazyModule() { } @Override public Package getDirectPackage(String name) { return findPackageInModule(this, name); } @Override public Package getPackage(String name) { // try here first Package pkg = null; // unless we're the default module, in which case we have to check this at the end, // since every package can be part of the default module boolean defaultModule = isDefault(); if(!defaultModule){ pkg = findPackageInModule(this, name); if(pkg != null) return pkg; } // then try in dependencies Set<Module> visited = new HashSet<Module>(); for(ModuleImport dependency : getImports()){ // we don't have to worry about the default module here since we can't depend on it pkg = findPackageInImport(name, dependency, visited); if(pkg != null) return pkg; } // The JDK uses arrays, which we pretend are in java.lang, and ByteArray needs ceylon.language.Byte, // so we pretend the JDK imports the language module if(JDKUtils.isJDKModule(getNameAsString()) || JDKUtils.isOracleJDKModule(getNameAsString())){ Module languageModule = getModelLoader().getLanguageModule(); if(languageModule instanceof LazyModule){ pkg = findPackageInModule((LazyModule) languageModule, name); if(pkg != null) return pkg; } } // never try to load java packages from the default module because it would // work and appear to come from there if(JDKUtils.isJDKAnyPackage(name) || JDKUtils.isOracleJDKAnyPackage(name)){ return null; } // do the lookup of the default module last if(defaultModule) pkg = getModelLoader().findExistingPackage(this, name); return pkg; } private Package findPackageInImport(String name, ModuleImport dependency, Set<Module> visited) { Module module = dependency.getModule(); // only visit modules once if(!visited.add(module)) return null; if (module instanceof LazyModule) { // this is the equivalent of getDirectPackage, it does not recurse Package pkg = findPackageInModule((LazyModule) dependency.getModule(), name); if(pkg != null) return pkg; // not found, try in its exported dependencies for(ModuleImport dep : module.getImports()){ if(!dep.isExport()) continue; pkg = findPackageInImport(name, dep, visited); if(pkg != null) return pkg; } // not found return null; } else return module.getPackage(name); } private Package findPackageInModule(LazyModule module, String name) { if(module.containsPackage(name)){ // first try the already loaded packages from that module AbstractModelLoader modelLoader = getModelLoader(); synchronized(modelLoader.getLock()){ for(Package pkg : module.getPackages()){ if(pkg.getNameAsString().equals(name)) return pkg; } // create/load a new one return getModelLoader().findExistingPackage(module, name); } } return null; } public Package findPackageNoLazyLoading(String name) { // make sure we don't call any overloaded getPackages() that might trigger lazy loading for(Package pkg : super.getPackages()){ if(pkg.getNameAsString().equals(name)) return pkg; } return null; } protected abstract AbstractModelLoader getModelLoader(); public boolean isJava() { return isJava; } public void setJava(boolean isJava) { this.isJava = isJava; } public void loadPackageList(ArtifactResult artifact) { if (artifact instanceof ContentAwareArtifactResult) { for (String entry : ((ContentAwareArtifactResult) artifact).getEntries()) { addPackageForPath(entry, artifact.filter()); } } else { File file = artifact.artifact(); if (file != null) { ZipFile zipFile; try { zipFile = new ZipFile(artifact.artifact()); } catch (IOException e) { throw new RuntimeException("Error accessing artifact: " + artifact.artifact(), e); } try{ Enumeration<? extends ZipEntry> entries = zipFile.entries(); while(entries.hasMoreElements()) loadPackageList(entries.nextElement(), artifact.filter()); }finally{ try { zipFile.close(); } catch (IOException e) { // ignore } } } } } private void loadPackageList(ZipEntry entry, PathFilter pathFilter) { if(!entry.isDirectory()){ String path = entry.getName(); addPackageForPath(path, pathFilter); } } private void addPackageForPath(String path, PathFilter pathFilter) { if(path.toLowerCase().endsWith(".class")){ int sep = path.lastIndexOf('/'); if(sep != -1) path = path.substring(0, sep); else path = "";// default package String pkg = path; // make sure we unquote any package part pkg = pkg.replace("$", ""); String pathQuery; if(path.isEmpty()) pathQuery = pkg; else pathQuery = pkg+"/"; if(pathFilter == null || pathFilter.accept(pathQuery)){ pkg = pkg.replace('/', '.'); jarPackages.add(pkg); } } } public boolean containsPackage(String pkgName){ String moduleName = getNameAsString(); if(!isJava){ List<Package> superPackages = super.getPackages(); for(int i=0,l=superPackages.size();i<l;i++){ if(superPackages.get(i).getNameAsString().equals(pkgName)) return true; } // The language module is in the classpath and does not have its jarPackages loaded if(moduleName.equals(Module.LANGUAGE_MODULE_NAME)){ return JvmBackendUtil.isSubPackage(moduleName, pkgName) || pkgName.startsWith("com.redhat.ceylon.compiler.java.runtime") || pkgName.startsWith("com.redhat.ceylon.compiler.java.language") || pkgName.startsWith("com.redhat.ceylon.compiler.java.metadata"); } return jarPackages.contains(pkgName); }else{ // special rules for the JDK which we don't load from the repo if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)) return true; // otherwise we have the list of packages contained in that module jar return jarPackages.contains(pkgName); } } @Override protected boolean isJdkModule(String moduleName) { return JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName); } @Override protected boolean isJdkPackage(String moduleName, String packageName) { return JDKUtils.isJDKPackage(moduleName, packageName) || JDKUtils.isOracleJDKPackage(moduleName, packageName); } public void addPackage(Package pkg){ // make sure we don't call any overloaded getPackages() that might trigger lazy loading super.getPackages().add(pkg); } }
package com.haxademic.demo.math; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.draw.context.OpenGLUtil; import com.haxademic.core.file.DemoAssets; import com.haxademic.core.file.FileUtil; import com.haxademic.core.math.MathUtil; import processing.core.PImage; public class Demo_MathUtil_scaleToTarget extends PAppletHax { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } PImage img; public void setup() { super.setup(); img = DemoAssets.justin(); OpenGLUtil.setTextureQualityHigh(p.g); } public void drawApp() { p.background(0); DrawUtil.setDrawCenter(p); p.ambient(127); p.lightSpecular(230, 230, 230); p.directionalLight(200, 200, 200, -0.0f, -0.0f, 1); p.directionalLight(200, 200, 200, 0.0f, 0.0f, -1); p.specular(p.color(200)); p.emissive(p.color(20)); p.shininess(5.0f); float imageSize = 300f; float imgScale = MathUtil.scaleToTarget(img.height, imageSize); p.translate(p.width / 2, p.height / 2); p.rotateY(0.2f * P.sin(p.frameCount * 0.03f)); // draw image at 300 pixels tall p.image(img, 0, 0, img.width * imgScale, img.height * imgScale); // put down floor p.translate(0, img.height * imgScale / 2); p.rotateX(P.HALF_PI); p.fill(100,0,100); p.rect(0, 0, imageSize, imageSize); } }
package ru.job4j.StoreSQL; import java.sql.*; import java.util.Collections; import java.util.List; public class StoreSQL implements AutoCloseable { private final Config config; private Connection connect; public StoreSQL(Config config) { this.config = config; } public void generate(int size) { for (int i = 0; i < size; i++) { String s1 = "INSERT INTO test(i) VALUES (?)"; try (PreparedStatement statement = connect.prepareStatement(s1);) { statement.setString(1, s1); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } public static void createNewDatabase(String fileName) { String url = "jdbc:sqlite:C:/sqlite/db/" + fileName; try (Connection conn = DriverManager.getConnection(url)) { if (conn != null) { DatabaseMetaData meta = conn.getMetaData(); System.out.println("The driver name is " + meta.getDriverName()); System.out.println("A new database has been created."); } } catch (SQLException e) { System.out.println(e.getMessage()); } } public List<Entry> load() { return Collections.EMPTY_LIST; } @Override public void close() throws Exception { if (connect != null) { connect.close(); } } public static void main(String[] args) { createNewDatabase("test.db"); } }
package com.interview.dynamic; import java.util.*; public class MinimumNumberOfPerfectSquares { public int numSquaresUsingDP(int n) { int count = (int)Math.ceil(Math.sqrt(n)); int[] T = new int[n + 1]; T[0] = 0; for (int i = 1; i < T.length; i++) { T[i] = Integer.MAX_VALUE; for (int j = 1; j <= count; j++) { if (i < j*j) { break; } T[i] = Math.min(T[i], T[i - j*j] + 1); } } return T[n]; } public int numSquaresUsingBFS(int n) { List<Integer> perfectSquares = new ArrayList<>(); int i = 1; Queue<Integer> queue = new LinkedList<>(); Set<Integer> visited = new HashSet<>(); while (true) { int square = i * i; if (square == n) { return 1; } if (square > n) { break; } perfectSquares.add(square); queue.offer(square); visited.add(square); i++; } int distance = 1; while (!queue.isEmpty()) { int size = queue.size(); distance++; for (int j = 0; j < size; j++) { int node = queue.poll(); for (int square : perfectSquares) { int sum = node + square; if (sum == n) { return distance; } else if (!visited.contains(sum)) { visited.add(sum); queue.add(sum); } else if (sum > n) { break; } } } } return distance; } }
package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Style.Overflow; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; import com.google.gwt.user.client.ui.TextBox; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.EventId; import com.vaadin.terminal.gwt.client.Focusable; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.VTooltip; /** * Client side implementation of the Select component. * * TODO needs major refactoring (to be extensible etc) */ @SuppressWarnings("deprecation") public class VFilterSelect extends Composite implements Paintable, Field, KeyDownHandler, KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable { /** * Represents a suggestion in the suggestion popup box */ public class FilterSelectSuggestion implements Suggestion, Command { private final String key; private final String caption; private String iconUri; /** * Constructor * * @param uidl * The UIDL recieved from the server */ public FilterSelectSuggestion(UIDL uidl) { key = uidl.getStringAttribute("key"); caption = uidl.getStringAttribute("caption"); if (uidl.hasAttribute("icon")) { iconUri = client.translateVaadinUri(uidl .getStringAttribute("icon")); } } /** * Gets the visible row in the popup as a HTML string. The string * contains an image tag with the rows icon (if an icon has been * specified) and the caption of the item */ public String getDisplayString() { final StringBuffer sb = new StringBuffer(); if (iconUri != null) { sb.append("<img src=\""); sb.append(Util.escapeAttribute(iconUri)); sb.append("\" alt=\"\" class=\"v-icon\" />"); } sb.append("<span>" + Util.escapeHTML(caption) + "</span>"); return sb.toString(); } /** * Get a string that represents this item. This is used in the text box. */ public String getReplacementString() { return caption; } /** * Get the option key which represents the item on the server side. * * @return The key of the item */ public int getOptionKey() { return Integer.parseInt(key); } /** * Get the URI of the icon. Used when constructing the displayed option. * * @return */ public String getIconUri() { return iconUri; } /** * Executes a selection of this item. */ public void execute() { onSuggestionSelected(this); } } /** * Represents the popup box with the selection options. Wraps a suggestion * menu. */ public class SuggestionPopup extends VOverlay implements PositionCallback, CloseHandler<PopupPanel> { private static final String Z_INDEX = "30000"; private final SuggestionMenu menu; private final Element up = DOM.createDiv(); private final Element down = DOM.createDiv(); private final Element status = DOM.createDiv(); private boolean isPagingEnabled = true; private long lastAutoClosed; private int popupOuterPadding = -1; private int topPosition; /** * Default constructor */ SuggestionPopup() { super(true, false, true); menu = new SuggestionMenu(); setWidget(menu); setStyleName(CLASSNAME + "-suggestpopup"); DOM.setStyleAttribute(getElement(), "zIndex", Z_INDEX); final Element root = getContainerElement(); DOM.setInnerHTML(up, "<span>Prev</span>"); DOM.sinkEvents(up, Event.ONCLICK); DOM.setInnerHTML(down, "<span>Next</span>"); DOM.sinkEvents(down, Event.ONCLICK); DOM.insertChild(root, up, 0); DOM.appendChild(root, down); DOM.appendChild(root, status); DOM.setElementProperty(status, "className", CLASSNAME + "-status"); DOM.sinkEvents(root, Event.ONMOUSEDOWN | Event.ONMOUSEWHEEL); addCloseHandler(this); } /** * Shows the popup where the user can see the filtered options * * @param currentSuggestions * The filtered suggestions * @param currentPage * The current page number * @param totalSuggestions * The total amount of suggestions */ public void showSuggestions( Collection<FilterSelectSuggestion> currentSuggestions, int currentPage, int totalSuggestions) { // Add TT anchor point DOM.setElementProperty(getElement(), "id", "VAADIN_COMBOBOX_OPTIONLIST"); menu.setSuggestions(currentSuggestions); final int x = VFilterSelect.this.getAbsoluteLeft(); topPosition = tb.getAbsoluteTop(); topPosition += tb.getOffsetHeight(); setPopupPosition(x, topPosition); int nullOffset = (nullSelectionAllowed && "".equals(lastFilter) ? 1 : 0); boolean firstPage = (currentPage == 0); final int first = currentPage * pageLength + 1 - (firstPage ? 0 : nullOffset); final int last = first + currentSuggestions.size() - 1 - (firstPage && "".equals(lastFilter) ? nullOffset : 0); final int matches = totalSuggestions - nullOffset; if (last > 0) { // nullsel not counted, as requested by user DOM.setInnerText(status, (matches == 0 ? 0 : first) + "-" + last + "/" + matches); } else { DOM.setInnerText(status, ""); } // We don't need to show arrows or statusbar if there is only one // page if (totalSuggestions <= pageLength || pageLength == 0) { setPagingEnabled(false); } else { setPagingEnabled(true); } setPrevButtonActive(first > 1); setNextButtonActive(last < matches); // clear previously fixed width menu.setWidth(""); DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()), "width", ""); setPopupPositionAndShow(this); } /** * Should the next page button be visible to the user? * * @param active */ private void setNextButtonActive(boolean active) { if (active) { DOM.sinkEvents(down, Event.ONCLICK); DOM.setElementProperty(down, "className", CLASSNAME + "-nextpage"); } else { DOM.sinkEvents(down, 0); DOM.setElementProperty(down, "className", CLASSNAME + "-nextpage-off"); } } /** * Should the previous page button be visible to the user * * @param active */ private void setPrevButtonActive(boolean active) { if (active) { DOM.sinkEvents(up, Event.ONCLICK); DOM.setElementProperty(up, "className", CLASSNAME + "-prevpage"); } else { DOM.sinkEvents(up, 0); DOM.setElementProperty(up, "className", CLASSNAME + "-prevpage-off"); } } /** * Selects the next item in the filtered selections */ public void selectNextItem() { final MenuItem cur = menu.getSelectedItem(); final int index = 1 + menu.getItems().indexOf(cur); if (menu.getItems().size() > index) { final MenuItem newSelectedItem = menu.getItems().get(index); menu.selectItem(newSelectedItem); tb.setText(newSelectedItem.getText()); tb.setSelectionRange(lastFilter.length(), newSelectedItem .getText().length() - lastFilter.length()); } else if (hasNextPage()) { lastIndex = index - 1; // save for paging filterOptions(currentPage + 1, lastFilter); } } /** * Selects the previous item in the filtered selections */ public void selectPrevItem() { final MenuItem cur = menu.getSelectedItem(); final int index = -1 + menu.getItems().indexOf(cur); if (index > -1) { final MenuItem newSelectedItem = menu.getItems().get(index); menu.selectItem(newSelectedItem); tb.setText(newSelectedItem.getText()); tb.setSelectionRange(lastFilter.length(), newSelectedItem .getText().length() - lastFilter.length()); } else if (index == -1) { if (currentPage > 0) { lastIndex = index + 1; // save for paging filterOptions(currentPage - 1, lastFilter); } } else { final MenuItem newSelectedItem = menu.getItems().get( menu.getItems().size() - 1); menu.selectItem(newSelectedItem); tb.setText(newSelectedItem.getText()); tb.setSelectionRange(lastFilter.length(), newSelectedItem .getText().length() - lastFilter.length()); } } /* * Using a timer to scroll up or down the pages so when we receive lots * of consecutive mouse wheel events the pages does not flicker. */ private LazyPageScroller lazyPageScroller = new LazyPageScroller(); private class LazyPageScroller extends Timer { private int pagesToScroll = 0; @Override public void run() { if (pagesToScroll != 0) { filterOptions(currentPage + pagesToScroll, lastFilter); pagesToScroll = 0; } } public void scrollUp() { if (currentPage + pagesToScroll > 0) { pagesToScroll cancel(); schedule(100); } } public void scrollDown() { if (totalMatches > (currentPage + pagesToScroll + 1) * pageLength) { pagesToScroll++; cancel(); schedule(100); } } } /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt * .user.client.Event) */ @Override public void onBrowserEvent(Event event) { if (event.getTypeInt() == Event.ONCLICK) { final Element target = DOM.eventGetTarget(event); if (target == up || target == DOM.getChild(up, 0)) { lazyPageScroller.scrollUp(); } else if (target == down || target == DOM.getChild(down, 0)) { lazyPageScroller.scrollDown(); } } else if (event.getTypeInt() == Event.ONMOUSEWHEEL) { int velocity = event.getMouseWheelVelocityY(); if (velocity > 0) { lazyPageScroller.scrollDown(); } else { lazyPageScroller.scrollUp(); } } /* * Prevent the keyboard focus from leaving the textfield by * preventing the default behaviour of the browser. Fixes #4285. */ handleMouseDownEvent(event); } /** * Should paging be enabled. If paging is enabled then only a certain * amount of items are visible at a time and a scrollbar or buttons are * visible to change page. If paging is turned of then all options are * rendered into the popup menu. * * @param paging * Should the paging be turned on? */ public void setPagingEnabled(boolean paging) { if (isPagingEnabled == paging) { return; } if (paging) { DOM.setStyleAttribute(down, "display", ""); DOM.setStyleAttribute(up, "display", ""); DOM.setStyleAttribute(status, "display", ""); } else { DOM.setStyleAttribute(down, "display", "none"); DOM.setStyleAttribute(up, "display", "none"); DOM.setStyleAttribute(status, "display", "none"); } isPagingEnabled = paging; } /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.PopupPanel$PositionCallback#setPosition * (int, int) */ public void setPosition(int offsetWidth, int offsetHeight) { int top = -1; int left = -1; // reset menu size and retrieve its "natural" size menu.setHeight(""); if (currentPage > 0) { // fix height to avoid height change when getting to last page menu.fixHeightTo(pageLength); } offsetHeight = getOffsetHeight(); final int desiredWidth = getMainWidth(); int naturalMenuWidth = DOM.getElementPropertyInt( DOM.getFirstChild(menu.getElement()), "offsetWidth"); if (popupOuterPadding == -1) { popupOuterPadding = Util.measureHorizontalPaddingAndBorder( getElement(), 2); } if (naturalMenuWidth < desiredWidth) { menu.setWidth((desiredWidth - popupOuterPadding) + "px"); DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()), "width", "100%"); naturalMenuWidth = desiredWidth; } if (BrowserInfo.get().isIE()) { /* * IE requires us to specify the width for the container * element. Otherwise it will be 100% wide */ int rootWidth = naturalMenuWidth - popupOuterPadding; DOM.setStyleAttribute(getContainerElement(), "width", rootWidth + "px"); } if (offsetHeight + getPopupTop() > Window.getClientHeight() + Window.getScrollTop()) { // popup on top of input instead top = getPopupTop() - offsetHeight - VFilterSelect.this.getOffsetHeight(); if (top < 0) { top = 0; } } else { top = getPopupTop(); /* * Take popup top margin into account. getPopupTop() returns the * top value including the margin but the value we give must not * include the margin. */ int topMargin = (top - topPosition); top -= topMargin; } // fetch real width (mac FF bugs here due GWT popups overflow:auto ) offsetWidth = DOM.getElementPropertyInt( DOM.getFirstChild(menu.getElement()), "offsetWidth"); if (offsetWidth + getPopupLeft() > Window.getClientWidth() + Window.getScrollLeft()) { left = VFilterSelect.this.getAbsoluteLeft() + VFilterSelect.this.getOffsetWidth() + Window.getScrollLeft() - offsetWidth; if (left < 0) { left = 0; } } else { left = getPopupLeft(); } setPopupPosition(left, top); } /** * Was the popup just closed? * * @return true if popup was just closed */ public boolean isJustClosed() { final long now = (new Date()).getTime(); return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200); } /* * (non-Javadoc) * * @see * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google * .gwt.event.logical.shared.CloseEvent) */ @Override public void onClose(CloseEvent<PopupPanel> event) { if (event.isAutoClosed()) { lastAutoClosed = (new Date()).getTime(); } } /** * Updates style names in suggestion popup to help theme building. */ public void updateStyleNames(UIDL uidl) { if (uidl.hasAttribute("style")) { setStyleName(CLASSNAME + "-suggestpopup"); final String[] styles = uidl.getStringAttribute("style").split( " "); for (int i = 0; i < styles.length; i++) { addStyleDependentName(styles[i]); } } } } /** * The menu where the suggestions are rendered */ public class SuggestionMenu extends MenuBar implements SubPartAware, LoadHandler { private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor( 100, new ScheduledCommand() { public void execute() { if (suggestionPopup.isVisible() && suggestionPopup.isAttached()) { setWidth(""); DOM.setStyleAttribute( DOM.getFirstChild(getElement()), "width", ""); suggestionPopup .setPopupPositionAndShow(suggestionPopup); } } }); /** * Default constructor */ SuggestionMenu() { super(true); setStyleName(CLASSNAME + "-suggestmenu"); addDomHandler(this, LoadEvent.getType()); } /** * Fixes menus height to use same space as full page would use. Needed * to avoid height changes when quickly "scrolling" to last page */ public void fixHeightTo(int pagelenth) { if (currentSuggestions.size() > 0) { final int pixels = pagelenth * (getOffsetHeight() - 2) / currentSuggestions.size(); setHeight((pixels + 2) + "px"); } } /** * Sets the suggestions rendered in the menu * * @param suggestions * The suggestions to be rendered in the menu */ public void setSuggestions( Collection<FilterSelectSuggestion> suggestions) { clearItems(); final Iterator<FilterSelectSuggestion> it = suggestions.iterator(); while (it.hasNext()) { final FilterSelectSuggestion s = it.next(); final MenuItem mi = new MenuItem(s.getDisplayString(), true, s); Util.sinkOnloadForImages(mi.getElement()); this.addItem(mi); if (s == currentSuggestion) { selectItem(mi); } } } /** * Send the current selection to the server. Triggered when a selection * is made or on a blur event. */ public void doSelectedItemAction() { // do not send a value change event if null was and stays selected final String enteredItemValue = tb.getText(); if (nullSelectionAllowed && "".equals(enteredItemValue) && selectedOptionKey != null && !"".equals(selectedOptionKey)) { if (nullSelectItem) { reset(); return; } // null is not visible on pages != 0, and not visible when // filtering: handle separately client.updateVariable(paintableId, "filter", "", false); client.updateVariable(paintableId, "page", 0, false); client.updateVariable(paintableId, "selected", new String[] {}, immediate); suggestionPopup.hide(); return; } selectItemWhenReponseIsReceived = waitingForFilteringReponse; if (!waitingForFilteringReponse) { doPostFilterSelectedItemAction(); } } /** * Triggered after a selection has been made */ public void doPostFilterSelectedItemAction() { final MenuItem item = getSelectedItem(); final String enteredItemValue = tb.getText(); selectItemWhenReponseIsReceived = false; // check for exact match in menu int p = getItems().size(); if (p > 0) { for (int i = 0; i < p; i++) { final MenuItem potentialExactMatch = getItems().get(i); if (potentialExactMatch.getText().equals(enteredItemValue)) { selectItem(potentialExactMatch); // do not send a value change event if null was and // stays selected if (!"".equals(enteredItemValue) || (selectedOptionKey != null && !"" .equals(selectedOptionKey))) { doItemAction(potentialExactMatch, true); } suggestionPopup.hide(); return; } } } if (allowNewItem) { if (!prompting && !enteredItemValue.equals(lastNewItemString)) { /* * Store last sent new item string to avoid double sends */ lastNewItemString = enteredItemValue; client.updateVariable(paintableId, "newitem", enteredItemValue, immediate); } } else if (item != null && !"".equals(lastFilter) && (filteringmode == FILTERINGMODE_CONTAINS ? item .getText().toLowerCase() .contains(lastFilter.toLowerCase()) : item .getText().toLowerCase() .startsWith(lastFilter.toLowerCase()))) { doItemAction(item, true); } else { // currentSuggestion has key="" for nullselection if (currentSuggestion != null && !currentSuggestion.key.equals("")) { // An item (not null) selected String text = currentSuggestion.getReplacementString(); tb.setText(text); selectedOptionKey = currentSuggestion.key; } else { // Null selected tb.setText(""); selectedOptionKey = null; } } suggestionPopup.hide(); } private static final String SUBPART_PREFIX = "item"; public Element getSubPartElement(String subPart) { int index = Integer.parseInt(subPart.substring(SUBPART_PREFIX .length())); MenuItem item = getItems().get(index); return item.getElement(); } public String getSubPartName(Element subElement) { if (!getElement().isOrHasChild(subElement)) { return null; } Element menuItemRoot = subElement; while (menuItemRoot != null && !menuItemRoot.getTagName().equalsIgnoreCase("td")) { menuItemRoot = menuItemRoot.getParentElement().cast(); } // "menuItemRoot" is now the root of the menu item final int itemCount = getItems().size(); for (int i = 0; i < itemCount; i++) { if (getItems().get(i).getElement() == menuItemRoot) { String name = SUBPART_PREFIX + i; return name; } } return null; } public void onLoad(LoadEvent event) { if (BrowserInfo.get().isIE6()) { // Ensure PNG transparency works in IE6 Util.doIE6PngFix((Element) Element.as(event.getNativeEvent() .getEventTarget())); } // Handle icon onload events to ensure shadow is resized // correctly delayedImageLoadExecutioner.trigger(); } } public static final int FILTERINGMODE_OFF = 0; public static final int FILTERINGMODE_STARTSWITH = 1; public static final int FILTERINGMODE_CONTAINS = 2; private static final String CLASSNAME = "v-filterselect"; private static final String STYLE_NO_INPUT = "no-input"; protected int pageLength = 10; private final FlowPanel panel = new FlowPanel(); /** * The text box where the filter is written */ private final TextBox tb = new TextBox() { /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.TextBoxBase#onBrowserEvent(com.google * .gwt.user.client.Event) */ @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (client != null) { client.handleTooltipEvent(event, VFilterSelect.this); } } @Override // Overridden to avoid selecting text when text input is disabled public void setSelectionRange(int pos, int length) { if (textInputEnabled) { super.setSelectionRange(pos, length); } else { super.setSelectionRange(getValue().length(), 0); } }; }; private final SuggestionPopup suggestionPopup = new SuggestionPopup(); /** * Used when measuring the width of the popup */ private final HTML popupOpener = new HTML("") { /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt * .user.client.Event) */ @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (client != null) { client.handleTooltipEvent(event, VFilterSelect.this); } /* * Prevent the keyboard focus from leaving the textfield by * preventing the default behaviour of the browser. Fixes #4285. */ handleMouseDownEvent(event); } }; private final Image selectedItemIcon = new Image(); private ApplicationConnection client; private String paintableId; private int currentPage; /** * A collection of available suggestions (options) as received from the * server. */ private final Collection<FilterSelectSuggestion> currentSuggestions = new ArrayList<FilterSelectSuggestion>(); private boolean immediate; private String selectedOptionKey; private boolean waitingForFilteringReponse = false; private boolean selectItemWhenReponseIsReceived = false; private boolean tabPressedWhenPopupOpen = false; private boolean initDone = false; private String lastFilter = ""; private int lastIndex = -1; // last selected index when using arrows /** * The current suggestion selected from the dropdown. This is one of the * values in currentSuggestions except when filtering, in this case * currentSuggestion might not be in currentSuggestions. */ private FilterSelectSuggestion currentSuggestion; private int totalMatches; private boolean allowNewItem; private boolean nullSelectionAllowed; private boolean nullSelectItem; private boolean enabled; private boolean readonly; private int filteringmode = FILTERINGMODE_OFF; // shown in unfocused empty field, disappears on focus (e.g "Search here") private static final String CLASSNAME_PROMPT = "prompt"; private static final String ATTR_INPUTPROMPT = "prompt"; public static final String ATTR_NO_TEXT_INPUT = "noInput"; private String inputPrompt = ""; private boolean prompting = false; // Set true when popupopened has been clicked. Cleared on each UIDL-update. // This handles the special case where are not filtering yet and the // selected value has changed on the server-side. See #2119 private boolean popupOpenerClicked; private String width = null; private int textboxPadding = -1; private int componentPadding = -1; private int suggestionPopupMinWidth = 0; private int popupWidth = -1; /* * Stores the last new item string to avoid double submissions. Cleared on * uidl updates */ private String lastNewItemString; private boolean focused = false; private int horizPaddingAndBorder = 2; /** * If set to false, the component should not allow entering text to the * field even for filtering. */ private boolean textInputEnabled = true; /** * Default constructor */ public VFilterSelect() { selectedItemIcon.setStyleName("v-icon"); selectedItemIcon.addLoadHandler(new LoadHandler() { public void onLoad(LoadEvent event) { updateRootWidth(); updateSelectedIconPosition(); /* * Workaround for an IE bug where the text is positioned below * the icon (#3991) */ if (BrowserInfo.get().isIE()) { Util.setStyleTemporarily(tb.getElement(), "paddingLeft", "0"); } } }); tb.sinkEvents(VTooltip.TOOLTIP_EVENTS); popupOpener.sinkEvents(VTooltip.TOOLTIP_EVENTS | Event.ONMOUSEDOWN); panel.add(tb); panel.add(popupOpener); initWidget(panel); setStyleName(CLASSNAME); tb.addKeyDownHandler(this); tb.addKeyUpHandler(this); tb.setStyleName(CLASSNAME + "-input"); tb.addFocusHandler(this); tb.addBlurHandler(this); tb.addClickHandler(this); popupOpener.setStyleName(CLASSNAME + "-button"); popupOpener.addClickHandler(this); } /** * Does the Select have more pages? * * @return true if a next page exists, else false if the current page is the * last page */ public boolean hasNextPage() { if (totalMatches > (currentPage + 1) * pageLength) { return true; } else { return false; } } /** * Filters the options at a certain page. Uses the text box input as a * filter * * @param page * The page which items are to be filtered */ public void filterOptions(int page) { filterOptions(page, tb.getText()); } /** * Filters the options at certain page using the given filter * * @param page * The page to filter * @param filter * The filter to apply to the components */ public void filterOptions(int page, String filter) { if (filter.equals(lastFilter) && currentPage == page) { if (!suggestionPopup.isAttached()) { suggestionPopup.showSuggestions(currentSuggestions, currentPage, totalMatches); } return; } if (!filter.equals(lastFilter)) { // we are on subsequent page and text has changed -> reset page if ("".equals(filter)) { // let server decide page = -1; } else { page = 0; } } waitingForFilteringReponse = true; client.updateVariable(paintableId, "filter", filter, false); client.updateVariable(paintableId, "page", page, true); lastFilter = filter; currentPage = page; } /* * (non-Javadoc) * * @see * com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal * .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection) */ @SuppressWarnings("deprecation") public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { paintableId = uidl.getId(); this.client = client; readonly = uidl.hasAttribute("readonly"); enabled = !uidl.hasAttribute("disabled"); tb.setEnabled(enabled); updateReadOnly(); if (client.updateComponent(this, uidl, true)) { return; } // Inverse logic here to make the default case (text input enabled) // work without additional UIDL messages boolean noTextInput = uidl.hasAttribute(ATTR_NO_TEXT_INPUT) && uidl.getBooleanAttribute(ATTR_NO_TEXT_INPUT); setTextInputEnabled(!noTextInput); // not a FocusWidget -> needs own tabindex handling if (uidl.hasAttribute("tabindex")) { tb.setTabIndex(uidl.getIntAttribute("tabindex")); } if (uidl.hasAttribute("filteringmode")) { filteringmode = uidl.getIntAttribute("filteringmode"); } immediate = uidl.hasAttribute("immediate"); nullSelectionAllowed = uidl.hasAttribute("nullselect"); nullSelectItem = uidl.hasAttribute("nullselectitem") && uidl.getBooleanAttribute("nullselectitem"); currentPage = uidl.getIntVariable("page"); if (uidl.hasAttribute("pagelength")) { pageLength = uidl.getIntAttribute("pagelength"); } if (uidl.hasAttribute(ATTR_INPUTPROMPT)) { // input prompt changed from server inputPrompt = uidl.getStringAttribute(ATTR_INPUTPROMPT); } else { inputPrompt = ""; } suggestionPopup.setPagingEnabled(true); suggestionPopup.updateStyleNames(uidl); allowNewItem = uidl.hasAttribute("allownewitem"); lastNewItemString = null; currentSuggestions.clear(); if (!waitingForFilteringReponse) { /* * Clear the current suggestions as the server response always * includes the new ones. Exception is when filtering, then we need * to retain the value if the user does not select any of the * options matching the filter. */ currentSuggestion = null; /* * Also ensure no old items in menu. Unless cleared the old values * may cause odd effects on blur events. Suggestions in menu might * not necessary exist in select at all anymore. */ suggestionPopup.menu.clearItems(); } final UIDL options = uidl.getChildUIDL(0); if (uidl.hasAttribute("totalMatches")) { totalMatches = uidl.getIntAttribute("totalMatches"); } // used only to calculate minimum popup width String captions = Util.escapeHTML(inputPrompt); for (final Iterator<?> i = options.getChildIterator(); i.hasNext();) { final UIDL optionUidl = (UIDL) i.next(); final FilterSelectSuggestion suggestion = new FilterSelectSuggestion( optionUidl); currentSuggestions.add(suggestion); if (optionUidl.hasAttribute("selected")) { if (!waitingForFilteringReponse || popupOpenerClicked) { String newSelectedOptionKey = Integer.toString(suggestion .getOptionKey()); if (!newSelectedOptionKey.equals(selectedOptionKey) || suggestion.getReplacementString().equals( tb.getText())) { // Update text field if we've got a new selection // Also update if we've got the same text to retain old // text selection behavior setPromptingOff(suggestion.getReplacementString()); selectedOptionKey = newSelectedOptionKey; } } currentSuggestion = suggestion; setSelectedItemIcon(suggestion.getIconUri()); } // Collect captions so we can calculate minimum width for textarea if (captions.length() > 0) { captions += "|"; } captions += Util.escapeHTML(suggestion.getReplacementString()); } if ((!waitingForFilteringReponse || popupOpenerClicked) && uidl.hasVariable("selected") && uidl.getStringArrayVariable("selected").length == 0) { // select nulled if (!waitingForFilteringReponse || !popupOpenerClicked) { if (!focused) { /* * client.updateComponent overwrites all styles so we must * ALWAYS set the prompting style at this point, even though * we think it has been set already... */ prompting = false; setPromptingOn(); } else { // we have focus in field, prompting can't be set on, // instead just clear the input tb.setValue(""); } } selectedOptionKey = null; } if (waitingForFilteringReponse && lastFilter.toLowerCase().equals( uidl.getStringVariable("filter"))) { suggestionPopup.showSuggestions(currentSuggestions, currentPage, totalMatches); waitingForFilteringReponse = false; if (!popupOpenerClicked && lastIndex != -1) { // we're paging w/ arrows MenuItem activeMenuItem; if (lastIndex == 0) { // going up, select last item int lastItem = pageLength - 1; List<MenuItem> items = suggestionPopup.menu.getItems(); /* * The first page can contain less than 10 items if the null * selection item is filtered away */ if (lastItem >= items.size()) { lastItem = items.size() - 1; } activeMenuItem = items.get(lastItem); suggestionPopup.menu.selectItem(activeMenuItem); } else { // going down, select first item activeMenuItem = suggestionPopup.menu.getItems().get(0); suggestionPopup.menu.selectItem(activeMenuItem); } setTextboxText(activeMenuItem.getText()); tb.setSelectionRange(lastFilter.length(), activeMenuItem .getText().length() - lastFilter.length()); lastIndex = -1; // reset } if (selectItemWhenReponseIsReceived) { suggestionPopup.menu.doPostFilterSelectedItemAction(); } } // Calculate minumum textarea width suggestionPopupMinWidth = minWidth(captions); popupOpenerClicked = false; if (!initDone) { updateRootWidth(); } // Focus dependent style names are lost during the update, so we add // them here back again if (focused) { addStyleDependentName("focus"); } initDone = true; } private void updateReadOnly() { tb.setReadOnly(readonly || !textInputEnabled); } private void setTextInputEnabled(boolean textInputEnabled) { // Always update styles as they might have been overwritten if (textInputEnabled) { removeStyleDependentName(STYLE_NO_INPUT); } else { addStyleDependentName(STYLE_NO_INPUT); } if (this.textInputEnabled == textInputEnabled) { return; } this.textInputEnabled = textInputEnabled; updateReadOnly(); } /** * Sets the text in the text box using a deferred command if on Gecko. This * is required for performance reasons (see #3663). * * @param text * the text to set in the text box */ private void setTextboxText(final String text) { if (BrowserInfo.get().isFF3()) { Scheduler.get().scheduleDeferred(new Command() { public void execute() { tb.setText(text); } }); } else { tb.setText(text); } } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.Composite#onAttach() */ @Override protected void onAttach() { super.onAttach(); /* * We need to recalculate the root width when the select is attached, so * #2974 won't happen. */ updateRootWidth(); } /** * Turns prompting on. When prompting is turned on a command prompt is shown * in the text box if nothing has been entered. */ private void setPromptingOn() { if (!prompting) { prompting = true; addStyleDependentName(CLASSNAME_PROMPT); } setTextboxText(inputPrompt); } /** * Turns prompting off. When prompting is turned on a command prompt is * shown in the text box if nothing has been entered. * * @param text * The text the text box should contain. */ private void setPromptingOff(String text) { setTextboxText(text); if (prompting) { prompting = false; removeStyleDependentName(CLASSNAME_PROMPT); } } /** * Triggered when a suggestion is selected * * @param suggestion * The suggestion that just got selected. */ public void onSuggestionSelected(FilterSelectSuggestion suggestion) { selectItemWhenReponseIsReceived = false; currentSuggestion = suggestion; String newKey; if (suggestion.key.equals("")) { // "nullselection" newKey = ""; } else { // normal selection newKey = String.valueOf(suggestion.getOptionKey()); } String text = suggestion.getReplacementString(); if ("".equals(newKey) && !focused) { setPromptingOn(); } else { setPromptingOff(text); } setSelectedItemIcon(suggestion.getIconUri()); if (!(newKey.equals(selectedOptionKey) || ("".equals(newKey) && selectedOptionKey == null))) { selectedOptionKey = newKey; client.updateVariable(paintableId, "selected", new String[] { selectedOptionKey }, immediate); // currentPage = -1; // forget the page } suggestionPopup.hide(); } /** * Sets the icon URI of the selected item. The icon is shown on the left * side of the item caption text. Set the URI to null to remove the icon. * * @param iconUri * The URI of the icon */ private void setSelectedItemIcon(String iconUri) { if (iconUri == null || iconUri == "") { panel.remove(selectedItemIcon); updateRootWidth(); } else { panel.insert(selectedItemIcon, 0); selectedItemIcon.setUrl(iconUri); updateRootWidth(); updateSelectedIconPosition(); } } /** * Positions the icon vertically in the middle. Should be called after the * icon has loaded */ private void updateSelectedIconPosition() { // Position icon vertically to middle int availableHeight = 0; if (BrowserInfo.get().isIE6()) { getElement().getStyle().setOverflow(Overflow.HIDDEN); availableHeight = getOffsetHeight(); getElement().getStyle().setProperty("overflow", ""); } else { availableHeight = getOffsetHeight(); } int iconHeight = Util.getRequiredHeight(selectedItemIcon); int marginTop = (availableHeight - iconHeight) / 2; DOM.setStyleAttribute(selectedItemIcon.getElement(), "marginTop", marginTop + "px"); } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt * .event.dom.client.KeyDownEvent) */ public void onKeyDown(KeyDownEvent event) { if (enabled && !readonly) { if (suggestionPopup.isAttached()) { popupKeyDown(event); } else { inputFieldKeyDown(event); } } } /** * Triggered when a key is pressed in the text box * * @param event * The KeyDownEvent */ private void inputFieldKeyDown(KeyDownEvent event) { switch (event.getNativeKeyCode()) { case KeyCodes.KEY_DOWN: case KeyCodes.KEY_UP: case KeyCodes.KEY_PAGEDOWN: case KeyCodes.KEY_PAGEUP: // open popup as from gadget filterOptions(-1, ""); lastFilter = ""; tb.selectAll(); break; case KeyCodes.KEY_ENTER: /* * This only handles the case when new items is allowed, a text is * entered, the popup opener button is clicked to close the popup * and enter is then pressed (see #7560). */ if (!allowNewItem) { return; } if (currentSuggestion != null && tb.getText().equals( currentSuggestion.getReplacementString())) { // Retain behavior from #6686 by returning without stopping // propagation if there's nothing to do return; } suggestionPopup.menu.doSelectedItemAction(); event.stopPropagation(); break; } } /** * Triggered when a key was pressed in the suggestion popup. * * @param event * The KeyDownEvent of the key */ private void popupKeyDown(KeyDownEvent event) { // Propagation of handled events is stopped so other handlers such as // shortcut key handlers do not also handle the same events. switch (event.getNativeKeyCode()) { case KeyCodes.KEY_DOWN: suggestionPopup.selectNextItem(); DOM.eventPreventDefault(DOM.eventGetCurrentEvent()); event.stopPropagation(); break; case KeyCodes.KEY_UP: suggestionPopup.selectPrevItem(); DOM.eventPreventDefault(DOM.eventGetCurrentEvent()); event.stopPropagation(); break; case KeyCodes.KEY_PAGEDOWN: if (hasNextPage()) { filterOptions(currentPage + 1, lastFilter); } event.stopPropagation(); break; case KeyCodes.KEY_PAGEUP: if (currentPage > 0) { filterOptions(currentPage - 1, lastFilter); } event.stopPropagation(); break; case KeyCodes.KEY_TAB: tabPressedWhenPopupOpen = true; filterOptions(currentPage); // onBlur() takes care of the rest break; case KeyCodes.KEY_ENTER: filterOptions(currentPage); if (currentSuggestions.size() == 1 && !allowNewItem) { // If there is only one suggestion, select that suggestionPopup.menu.selectItem(suggestionPopup.menu.getItems() .get(0)); } suggestionPopup.menu.doSelectedItemAction(); event.stopPropagation(); break; } } /** * Triggered when a key was depressed * * @param event * The KeyUpEvent of the key depressed */ public void onKeyUp(KeyUpEvent event) { if (enabled && !readonly) { switch (event.getNativeKeyCode()) { case KeyCodes.KEY_ENTER: case KeyCodes.KEY_TAB: case KeyCodes.KEY_SHIFT: case KeyCodes.KEY_CTRL: case KeyCodes.KEY_ALT: case KeyCodes.KEY_DOWN: case KeyCodes.KEY_UP: case KeyCodes.KEY_PAGEDOWN: case KeyCodes.KEY_PAGEUP: ; // NOP break; case KeyCodes.KEY_ESCAPE: reset(); break; default: if (textInputEnabled) { filterOptions(currentPage); } break; } } } /** * Resets the Select to its initial state */ private void reset() { if (currentSuggestion != null) { String text = currentSuggestion.getReplacementString(); setPromptingOff(text); selectedOptionKey = currentSuggestion.key; } else { if (focused) { setPromptingOff(""); } else { setPromptingOn(); } selectedOptionKey = null; } lastFilter = ""; suggestionPopup.hide(); } /** * Listener for popupopener */ public void onClick(ClickEvent event) { if (textInputEnabled && event.getNativeEvent().getEventTarget().cast() == tb .getElement()) { // Don't process clicks on the text field if text input is enabled return; } if (enabled && !readonly) { // ask suggestionPopup if it was just closed, we are using GWT // Popup's auto close feature if (!suggestionPopup.isJustClosed()) { filterOptions(-1, ""); popupOpenerClicked = true; lastFilter = ""; } DOM.eventPreventDefault(DOM.eventGetCurrentEvent()); focus(); tb.selectAll(); } } /** * Calculate minimum width for FilterSelect textarea */ private native int minWidth(String captions) /*-{ if(!captions || captions.length <= 0) return 0; captions = captions.split("|"); var d = $wnd.document.createElement("div"); var html = ""; for(var i=0; i < captions.length; i++) { html += "<div>" + captions[i] + "</div>"; // TODO apply same CSS classname as in suggestionmenu } d.style.position = "absolute"; d.style.top = "0"; d.style.left = "0"; d.style.visibility = "hidden"; d.innerHTML = html; $wnd.document.body.appendChild(d); var w = d.offsetWidth; $wnd.document.body.removeChild(d); return w; }-*/; /** * A flag which prevents a focus event from taking place */ boolean iePreventNextFocus = false; /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event * .dom.client.FocusEvent) */ public void onFocus(FocusEvent event) { /* * When we disable a blur event in ie we need to refocus the textfield. * This will cause a focus event we do not want to process, so in that * case we just ignore it. */ if (BrowserInfo.get().isIE() && iePreventNextFocus) { iePreventNextFocus = false; return; } focused = true; if (prompting && !readonly) { setPromptingOff(""); } addStyleDependentName("focus"); if (client.hasEventListeners(this, EventId.FOCUS)) { client.updateVariable(paintableId, EventId.FOCUS, "", true); } } /** * A flag which cancels the blur event and sets the focus back to the * textfield if the Browser is IE */ boolean preventNextBlurEventInIE = false; /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event * .dom.client.BlurEvent) */ public void onBlur(BlurEvent event) { if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) { /* * Clicking in the suggestion popup or on the popup button in IE * causes a blur event to be sent for the field. In other browsers * this is prevented by canceling/preventing default behavior for * the focus event, in IE we handle it here by refocusing the text * field and ignoring the resulting focus event for the textfield * (in onFocus). */ preventNextBlurEventInIE = false; Element focusedElement = Util.getIEFocusedElement(); if (getElement().isOrHasChild(focusedElement) || suggestionPopup.getElement() .isOrHasChild(focusedElement)) { // IF the suggestion popup or another part of the VFilterSelect // was focused, move the focus back to the textfield and prevent // the triggered focus event (in onFocus). iePreventNextFocus = true; tb.setFocus(true); return; } } focused = false; if (!readonly) { // much of the TAB handling takes place here if (tabPressedWhenPopupOpen) { tabPressedWhenPopupOpen = false; suggestionPopup.menu.doSelectedItemAction(); suggestionPopup.hide(); } else if (!suggestionPopup.isAttached() || suggestionPopup.isJustClosed()) { suggestionPopup.menu.doSelectedItemAction(); } if (selectedOptionKey == null) { setPromptingOn(); } else if (currentSuggestion != null) { setPromptingOff(currentSuggestion.caption); } } removeStyleDependentName("focus"); if (client.hasEventListeners(this, EventId.BLUR)) { client.updateVariable(paintableId, EventId.BLUR, "", true); } } /* * (non-Javadoc) * * @see com.vaadin.terminal.gwt.client.Focusable#focus() */ public void focus() { focused = true; if (prompting && !readonly) { setPromptingOff(""); } tb.setFocus(true); } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.UIObject#setWidth(java.lang.String) */ @Override public void setWidth(String width) { if (width == null || width.equals("")) { this.width = null; } else { this.width = width; } if (BrowserInfo.get().isIE6()) { // Required in IE when textfield is wider than this.width getElement().getStyle().setOverflow(Overflow.HIDDEN); horizPaddingAndBorder = Util.setWidthExcludingPaddingAndBorder( this, width, horizPaddingAndBorder); getElement().getStyle().setProperty("overflow", ""); } else { horizPaddingAndBorder = Util.setWidthExcludingPaddingAndBorder( this, width, horizPaddingAndBorder); } if (initDone) { updateRootWidth(); } } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.UIObject#setHeight(java.lang.String) */ @Override public void setHeight(String height) { super.setHeight(height); Util.setHeightExcludingPaddingAndBorder(tb, height, 3); } /** * Calculates the width of the select if the select has undefined width. * Should be called when the width changes or when the icon changes. */ private void updateRootWidth() { if (width == null) { /* * When the width is not specified we must specify width for root * div so the popupopener won't wrap to the next line and also so * the size of the combobox won't change over time. */ int tbWidth = Util.getRequiredWidth(tb); if (popupWidth < 0) { /* * Only use the first page popup width so the textbox will not * get resized whenever the popup is resized. */ popupWidth = Util.getRequiredWidth(popupOpener); } /* * Note: iconWidth is here calculated as a negative pixel value so * you should consider this in further calculations. */ int iconWidth = selectedItemIcon.isAttached() ? Util .measureMarginLeft(tb.getElement()) - Util.measureMarginLeft(selectedItemIcon.getElement()) : 0; int w = tbWidth + popupWidth + iconWidth; /* * When the select has a undefined with we need to check that we are * only setting the text box width relative to the first page width * of the items. If this is not done the text box width will change * when the popup is used to view longer items than the text box is * wide. */ if ((!initDone || currentPage + 1 < 0) && suggestionPopupMinWidth > w) { setTextboxWidth(suggestionPopupMinWidth); w = suggestionPopupMinWidth; } else { /* * Firefox3 has its own way of doing rendering so we need to * specify the width for the TextField to make sure it actually * is rendered as wide as FF3 says it is */ tb.setWidth((tbWidth - getTextboxPadding()) + "px"); } super.setWidth((w) + "px"); // Freeze the initial width, so that it won't change even if the // icon size changes width = w + "px"; } else { /* * When the width is specified we also want to explicitly specify * widths for textbox and popupopener */ setTextboxWidth(getMainWidth() - getComponentPadding()); } } /** * Get the width of the select in pixels where the text area and icon has * been included. * * @return The width in pixels */ private int getMainWidth() { int componentWidth; if (BrowserInfo.get().isIE6()) { // Required in IE when textfield is wider than this.width getElement().getStyle().setOverflow(Overflow.HIDDEN); componentWidth = getOffsetWidth(); getElement().getStyle().setProperty("overflow", ""); } else { componentWidth = getOffsetWidth(); } return componentWidth; } /** * Sets the text box width in pixels. * * @param componentWidth * The width of the text box in pixels */ private void setTextboxWidth(int componentWidth) { int padding = getTextboxPadding(); int popupOpenerWidth = Util.getRequiredWidth(popupOpener); int iconWidth = selectedItemIcon.isAttached() ? Util .getRequiredWidth(selectedItemIcon) : 0; int textboxWidth = componentWidth - padding - popupOpenerWidth - iconWidth; if (textboxWidth < 0) { textboxWidth = 0; } tb.setWidth(textboxWidth + "px"); } /** * Gets the horizontal padding of the text box in pixels. The measurement * includes the border width. * * @return The padding in pixels */ private int getTextboxPadding() { if (textboxPadding < 0) { textboxPadding = Util.measureHorizontalPaddingAndBorder( tb.getElement(), 4); } return textboxPadding; } /** * Gets the horizontal padding of the select. The measurement includes the * border width. * * @return The padding in pixels */ private int getComponentPadding() { if (componentPadding < 0) { componentPadding = Util.measureHorizontalPaddingAndBorder( getElement(), 3); } return componentPadding; } /** * Handles special behavior of the mouse down event * * @param event */ private void handleMouseDownEvent(Event event) { /* * Prevent the keyboard focus from leaving the textfield by preventing * the default behaviour of the browser. Fixes #4285. */ if (event.getTypeInt() == Event.ONMOUSEDOWN) { event.preventDefault(); event.stopPropagation(); /* * In IE the above wont work, the blur event will still trigger. So, * we set a flag here to prevent the next blur event from happening. * This is not needed if do not already have focus, in that case * there will not be any blur event and we should not cancel the * next blur. */ if (BrowserInfo.get().isIE() && focused) { preventNextBlurEventInIE = true; } } } @Override protected void onDetach() { super.onDetach(); suggestionPopup.hide(); } }
package com.interview.linklist; public class CopyLinkListWIthArbitPointer { public Node copy(Node head){ if(head == null){ return null; } Node current = head; //create new node with same value as current and insert it after current while(current != null){ Node newNode = Node.newNode(current.data); newNode.next = current.next; newNode.child = current.child; current.next = newNode; current = newNode.next; } //copy arbit position of current for the copy current = head; while(current != null){ current.next.child = current.child.next; current = current.next.next; } //now separate copy from the main list Node newHead = null; Node newCurrent = null; current = head; while(current != null){ if(newHead == null){ newHead = current.next; current.next = current.next.next; newCurrent = newHead; }else{ newCurrent.next = current.next; current.next = current.next.next; newCurrent = newCurrent.next; } current = current.next; } return newHead; } public void printList(Node head){ while(head != null){ System.out.println(head.data + " " + head.child.data); head = head.next; } } public static void main(String args[]){ LinkList ll = new LinkList(); Node head = null; head = ll.addNode(1, head); head = ll.addNode(2, head); head = ll.addNode(3, head); head = ll.addNode(4, head); Node n1 = ll.find(head,1); Node n2 = ll.find(head,2); Node n3 = ll.find(head,3); Node n4 = ll.find(head,4); n1.child = n2; n2.child = n4; n3.child = n1; n4.child = n1; CopyLinkListWIthArbitPointer cll = new CopyLinkListWIthArbitPointer(); Node newHead = cll.copy(head); cll.printList(head); cll.printList(newHead); } }
package git4idea.actions; import com.intellij.dvcs.DvcsUtil; import com.intellij.history.Label; import com.intellij.history.LocalHistory; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; import com.intellij.openapi.vcs.update.ActionInfo; import com.intellij.openapi.vcs.update.UpdateInfoTree; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.vcs.ViewUpdateInfoNotification; import git4idea.GitRevisionNumber; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.commands.*; import git4idea.merge.GitConflictResolver; import git4idea.merge.GitMergeCommittingConflictResolver; import git4idea.merge.GitMerger; import git4idea.merge.MergeChangeCollector; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitUIUtil; import git4idea.util.GitUntrackedFilesHelper; import git4idea.util.LocalChangesWouldBeOverwrittenHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import static git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector.Operation.MERGE; import static java.util.Collections.singletonList; abstract class GitMergeAction extends GitRepositoryAction { protected static class DialogState { final VirtualFile selectedRoot; final String progressTitle; final Computable<GitLineHandler> handlerProvider; DialogState(@NotNull VirtualFile root, @NotNull String title, @NotNull Computable<GitLineHandler> provider) { selectedRoot = root; progressTitle = title; handlerProvider = provider; } } @Nullable protected abstract DialogState displayDialog(@NotNull Project project, @NotNull List<VirtualFile> gitRoots, @NotNull VirtualFile defaultRoot); @Override protected void perform(@NotNull Project project, @NotNull List<VirtualFile> gitRoots, @NotNull VirtualFile defaultRoot) { DialogState dialogState = displayDialog(project, gitRoots, defaultRoot); if (dialogState == null) { return; } VirtualFile selectedRoot = dialogState.selectedRoot; Computable<GitLineHandler> handlerProvider = dialogState.handlerProvider; Label beforeLabel = LocalHistory.getInstance().putSystemLabel(project, "Before update"); new Task.Backgroundable(project, dialogState.progressTitle, true) { @Override public void run(@NotNull ProgressIndicator indicator) { GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project); Git git = Git.getInstance(); GitLocalChangesWouldBeOverwrittenDetector localChangesDetector = new GitLocalChangesWouldBeOverwrittenDetector(selectedRoot, MERGE); GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector = new GitUntrackedFilesOverwrittenByOperationDetector(selectedRoot); GitSimpleEventDetector mergeConflict = new GitSimpleEventDetector(GitSimpleEventDetector.Event.MERGE_CONFLICT); try (AccessToken ignore = DvcsUtil.workingTreeChangeStarted(project, getActionName())) { GitCommandResult result = git.runCommand(() -> { GitLineHandler handler = handlerProvider.compute(); handler.addLineListener(localChangesDetector); handler.addLineListener(untrackedFilesDetector); handler.addLineListener(mergeConflict); return handler; }); GitRepository repository = repositoryManager.getRepositoryForRoot(selectedRoot); assert repository != null : "Repository can't be null for root " + selectedRoot; String revision = repository.getCurrentRevision(); if (revision == null) { return; } GitRevisionNumber currentRev = new GitRevisionNumber(revision); handleResult(result, project, mergeConflict, localChangesDetector, untrackedFilesDetector, repository, currentRev, beforeLabel); } } }.queue(); } private void handleResult(@NotNull GitCommandResult result, @NotNull Project project, @NotNull GitSimpleEventDetector mergeConflictDetector, @NotNull GitLocalChangesWouldBeOverwrittenDetector localChangesDetector, @NotNull GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector, @NotNull GitRepository repository, @NotNull GitRevisionNumber currentRev, @NotNull Label beforeLabel) { VirtualFile root = repository.getRoot(); if (mergeConflictDetector.hasHappened()) { new GitMergeCommittingConflictResolver(project, Git.getInstance(), new GitMerger(project), singletonList(root), new GitConflictResolver.Params(project), true).merge(); } if (result.success() || mergeConflictDetector.hasHappened()) { VfsUtil.markDirtyAndRefresh(false, true, false, root); List<VcsException> exceptions = new ArrayList<>(); showUpdates(project, exceptions, root, currentRev, beforeLabel, getActionName()); repository.update(); GitVcs.getInstance(project).showErrors(exceptions, getActionName()); } else if (localChangesDetector.wasMessageDetected()) { LocalChangesWouldBeOverwrittenHelper.showErrorNotification(project, repository.getRoot(), getActionName(), localChangesDetector.getRelativeFilePaths()); } else if (untrackedFilesDetector.wasMessageDetected()) { GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, root, untrackedFilesDetector.getRelativeFilePaths(), getActionName(), null); } else { GitUIUtil.notifyError(project, "Git " + getActionName() + " Failed", result.getErrorOutputAsJoinedString(), true, null); repository.update(); } } private static void showUpdates(@NotNull Project project, @NotNull List<VcsException> exceptions, @NotNull VirtualFile root, @NotNull GitRevisionNumber currentRev, @NotNull Label beforeLabel, @NotNull String actionName) { UpdatedFiles files = UpdatedFiles.create(); MergeChangeCollector collector = new MergeChangeCollector(project, root, currentRev); collector.collect(files, exceptions); if (!exceptions.isEmpty()) return; GuiUtils.invokeLaterIfNeeded(() -> { ProjectLevelVcsManagerEx manager = (ProjectLevelVcsManagerEx)ProjectLevelVcsManager.getInstance(project); UpdateInfoTree tree = manager.showUpdateProjectInfo(files, actionName, ActionInfo.UPDATE, false); if (tree != null) { tree.setBefore(beforeLabel); tree.setAfter(LocalHistory.getInstance().putSystemLabel(project, "After update")); ViewUpdateInfoNotification.focusUpdateInfoTree(project, tree); } }, ModalityState.defaultModalityState()); } }
package com.wordwise.client; import java.util.List; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.Protocol; import org.restlet.resource.ClientResource; import com.wordwise.gameengine.ServerCommunication; import com.wordwise.server.model.Difficulty; import com.wordwise.server.model.Language; import com.wordwise.server.model.Quality; import com.wordwise.server.model.Rate; import com.wordwise.server.model.Translation; import com.wordwise.server.model.parameter.ListTranslationParameters; import com.wordwise.server.resource.DifficultyResource; import com.wordwise.server.resource.QualityResource; import com.wordwise.server.resource.RateResource; import com.wordwise.server.resource.TranslationResource; public class RESTfullServerCommunication implements ServerCommunication { // 192.168.112.1 private static final String BASE_CLIENT_URL = "http://192.168.1.100:8080/WordWiseServer/"; private static final TranslationResource translationResource = getTranslationResource(); private static final RateResource rateResource = getRateResource(); private static final QualityResource qualityResource = getQualityResource(); private static final DifficultyResource difficultyResource = getDifficultyResource(); private static TranslationResource getTranslationResource() { ClientResource clientResource = new ClientResource(BASE_CLIENT_URL + TranslationResource.RESOURCE_NAME); Context context = new Context(); context.getParameters().add("socketTimeout", "1000"); clientResource.setNext(new Client(context, Protocol.HTTP)); clientResource.setRetryOnError(false); return clientResource.wrap(TranslationResource.class); } private static RateResource getRateResource() { ClientResource clientResource = new ClientResource(BASE_CLIENT_URL + RateResource.RESOURCE_NAME); Context context = new Context(); context.getParameters().add("socketTimeout", "1000"); clientResource.setNext(new Client(context, Protocol.HTTP)); clientResource.setRetryOnError(false); return clientResource.wrap(RateResource.class); } private static QualityResource getQualityResource() { ClientResource clientResource = new ClientResource(BASE_CLIENT_URL + QualityResource.RESOURCE_NAME); Context context = new Context(); context.getParameters().add("socketTimeout", "1000"); clientResource.setNext(new Client(context, Protocol.HTTP)); clientResource.setRetryOnError(false); return clientResource.wrap(QualityResource.class); } private static DifficultyResource getDifficultyResource() { ClientResource clientResource = new ClientResource(BASE_CLIENT_URL + DifficultyResource.RESOURCE_NAME); Context context = new Context(); context.getParameters().add("socketTimeout", "1000"); clientResource.setNext(new Client(context, Protocol.HTTP)); clientResource.setRetryOnError(false); return clientResource.wrap(DifficultyResource.class); } public boolean addTranslation(Translation translation) { try{ translationResource.add(translation); return true; }catch(Exception e){ e.printStackTrace(); return false; } } public boolean rateTranslation(Rate rating) { try{ rateResource.add(rating); return true; }catch(Exception e){ e.printStackTrace(); return false; } } public boolean addWordQualitiy(Quality quality) { try{ qualityResource.add(quality); return true; }catch(Exception e){ e.printStackTrace(); return false; } } public boolean addWordDifficulty(Difficulty difficulty) { try{ difficultyResource.add(difficulty); return true; }catch(Exception e){ e.printStackTrace(); return false; } } /** * Clients of this method should check whether null returned or not. * */ public List<Translation> listTranslations(Language language, Difficulty difficulty, int numberOfTranslations, List<Translation> translationsAlreadyUsed) { try{ return translationResource.list(new ListTranslationParameters(language, difficulty, numberOfTranslations, translationsAlreadyUsed)); }catch(Exception e){ e.printStackTrace(); return null; } } }
package com.jetbrains.ther.psi.references; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.impl.scopes.LibraryScope; import com.intellij.openapi.roots.ModifiableModelsProvider; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiFileFactoryImpl; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.IncorrectOperationException; import com.jetbrains.ther.TheRUtils; import com.jetbrains.ther.TheRLanguage; import com.jetbrains.ther.interpreter.TheRInterpreterConfigurable; import com.jetbrains.ther.interpreter.TheRInterpreterService; import com.jetbrains.ther.psi.api.*; import com.jetbrains.ther.psi.stubs.TheRAssignmentNameIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class TheRReferenceImpl implements PsiReference, PsiPolyVariantReference { private static final Logger LOG = Logger.getInstance(TheRReferenceImpl.class.getName()); protected final TheRReferenceExpression myElement; public TheRReferenceImpl(TheRReferenceExpression element) { myElement = element; } @NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { final List<ResolveResult> result = new ArrayList<ResolveResult>(); final String namespace = myElement.getNamespace(); final String name = myElement.getName(); if (name == null) return ResolveResult.EMPTY_ARRAY; if (namespace != null) { final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); final LibraryTable.ModifiableModel model = modelsProvider.getLibraryTableModifiableModel(myElement.getProject()); final Library library = model.getLibraryByName(TheRInterpreterConfigurable.THE_R_LIBRARY); if (library != null) { final VirtualFile[] files = library.getFiles(OrderRootType.CLASSES); for (VirtualFile child : files) { if (namespace.equals(child.getParent().getName())) { final VirtualFile file = child.findChild(name + ".R"); if (file != null) { final PsiFile psiFile = PsiManager.getInstance(myElement.getProject()).findFile(file); final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(psiFile, TheRAssignmentStatement.class); if (statements != null) { for (TheRAssignmentStatement statement : statements) { final PsiElement assignee = statement.getAssignee(); if (assignee != null && assignee.getText().equals(name)) { result.add(new PsiElementResolveResult(assignee)); } } } } } } } } TheRBlock rBlock = PsiTreeUtil.getParentOfType(myElement, TheRBlock.class); while (rBlock != null) { final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(rBlock, TheRAssignmentStatement.class); if (statements != null) { for (TheRAssignmentStatement statement : statements) { final PsiElement assignee = statement.getAssignee(); if (assignee != null && assignee.getText().equals(name)) { result.add(new PsiElementResolveResult(assignee)); } } } rBlock = PsiTreeUtil.getParentOfType(rBlock, TheRBlock.class); } final TheRFunction rFunction = PsiTreeUtil.getParentOfType(myElement, TheRFunction.class); if (rFunction != null) { final TheRParameterList list = rFunction.getParameterList(); for (TheRParameter parameter : list.getParameters()) { if (name.equals(parameter.getName())) { result.add(new PsiElementResolveResult(parameter)); } } } final PsiFile file = myElement.getContainingFile(); final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(file, TheRAssignmentStatement.class); if (statements != null) { for (TheRAssignmentStatement statement : statements) { final PsiElement assignee = statement.getAssignee(); if (assignee != null && assignee.getText().equals(name)) { result.add(new PsiElementResolveResult(assignee)); } } } if (!result.isEmpty()) return result.toArray(new ResolveResult[result.size()]); addFromLibrary(result, name, TheRInterpreterConfigurable.THE_R_LIBRARY); addFromLibrary(result, name, TheRInterpreterConfigurable.THE_R_SKELETONS); if (result.isEmpty()) { addRuntimeDefinition(result, name); } return result.toArray(new ResolveResult[result.size()]); } private void addRuntimeDefinition(@NotNull final List<ResolveResult> result, @NotNull final String name) { final String path = TheRInterpreterService.getInstance().getInterpreterPath(); if (path == null) return; final ProcessOutput output = TheRUtils.getProcessOutput(name); if (output.getExitCode() != 0) { LOG.info("Failed to obtain function definition from runtime: " + output.getStderr()); return; } if (output.isTimeout()) { LOG.info("Failed to obtain function definition from runtime because of timeout."); return; } String stdout = output.getStdout(); final int byteCodeIndex = stdout.indexOf("<bytecode"); if (byteCodeIndex > 0) stdout = stdout.substring(0, byteCodeIndex); final PsiFileFactory factory = PsiFileFactory.getInstance(myElement.getProject()); final String fileName = name + ".r"; final LightVirtualFile virtualFile = new LightVirtualFile(fileName, TheRLanguage.getInstance(), stdout); final PsiFile psiFile = ((PsiFileFactoryImpl)factory).trySetupPsiForFile(virtualFile, TheRLanguage.getInstance(), true, true); if (psiFile != null) result.add(new PsiElementResolveResult(psiFile)); } private void addFromLibrary(@NotNull final List<ResolveResult> result, @NotNull final String name, @NotNull final String libraryName) { final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); final LibraryTable.ModifiableModel model = modelsProvider.getLibraryTableModifiableModel(myElement.getProject()); if (model != null) { final Library library = model.getLibraryByName(libraryName); if (library != null) { final Collection<TheRAssignmentStatement> assignmentStatements = TheRAssignmentNameIndex.find(name, myElement.getProject(), new LibraryScope(myElement.getProject(), library)); for (TheRAssignmentStatement statement : assignmentStatements) { final PsiFile containingFile = statement.getContainingFile(); final PsiElement assignee = statement.getAssignee(); if(assignee == null) continue; if (FileUtil.getNameWithoutExtension(containingFile.getName()).equalsIgnoreCase(name)) { result.add(0, new PsiElementResolveResult(assignee)); } else result.add(new PsiElementResolveResult(assignee)); } } } } @Override public PsiElement getElement() { return myElement; } @Override public TextRange getRangeInElement() { final TextRange range = myElement.getNode().getTextRange(); return range.shiftRight(-myElement.getNode().getStartOffset()); } @Nullable @Override public PsiElement resolve() { final ResolveResult[] results = multiResolve(false); return results.length >= 1 ? results[0].getElement() : null; } @NotNull @Override public String getCanonicalText() { return getElement().getText(); } @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { return null; } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { return null; } @Override public boolean isReferenceTo(PsiElement element) { return false; } @NotNull @Override public Object[] getVariants() { List<LookupElement> result = new ArrayList<LookupElement>(); final String name = myElement.getName(); if (myElement.getParent() instanceof TheRReferenceExpression) return ResolveResult.EMPTY_ARRAY; if (name == null) return ResolveResult.EMPTY_ARRAY; TheRBlock rBlock = PsiTreeUtil.getParentOfType(myElement, TheRBlock.class); while (rBlock != null) { final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(rBlock, TheRAssignmentStatement.class); if (statements != null) { for (TheRAssignmentStatement statement : statements) { final PsiElement assignee = statement.getAssignee(); if (assignee != null) result.add(LookupElementBuilder.create(assignee.getText())); } } rBlock = PsiTreeUtil.getParentOfType(rBlock, TheRBlock.class); } final TheRFunction rFunction = PsiTreeUtil.getParentOfType(myElement, TheRFunction.class); if (rFunction != null) { final TheRParameterList list = rFunction.getParameterList(); for (TheRParameter parameter : list.getParameters()) { result.add(LookupElementBuilder.create(parameter)); } } final PsiFile file = myElement.getContainingFile(); final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(file, TheRAssignmentStatement.class); if (statements != null) { for (TheRAssignmentStatement statement : statements) { final PsiElement assignee = statement.getAssignee(); if (assignee != null) result.add(LookupElementBuilder.create(assignee.getText())); } } addVariantsFromSkeletons(result); return result.toArray(); } private void addVariantsFromSkeletons(@NotNull final List<LookupElement> result) { final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); final LibraryTable.ModifiableModel model = modelsProvider.getLibraryTableModifiableModel(myElement.getProject()); if (model != null) { final Library library = model.getLibraryByName(TheRInterpreterConfigurable.THE_R_SKELETONS); if (library != null) { final Collection<String> assignmentStatements = TheRAssignmentNameIndex.allKeys(myElement.getProject()); for (String statement : assignmentStatements) { final Collection<TheRAssignmentStatement> statements = TheRAssignmentNameIndex.find(statement, myElement.getProject(), new LibraryScope(myElement.getProject(), library)); for (TheRAssignmentStatement assignmentStatement : statements) { final PsiDirectory directory = assignmentStatement.getContainingFile().getParent(); assert directory != null; result.add(LookupElementBuilder.create(assignmentStatement, directory.getName() + "::" + assignmentStatement.getName())); } } } } } @Override public boolean isSoft() { return true; } }
package git4idea.actions; import com.intellij.dvcs.DvcsUtil; import com.intellij.history.Label; import com.intellij.history.LocalHistory; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction; import com.intellij.openapi.vcs.update.ActionInfo; import com.intellij.openapi.vcs.update.UpdateInfoTree; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.vcs.ViewUpdateInfoNotification; import git4idea.GitBranch; import git4idea.GitRevisionNumber; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.branch.GitBranchPair; import git4idea.commands.*; import git4idea.merge.GitConflictResolver; import git4idea.merge.GitMergeCommittingConflictResolver; import git4idea.merge.GitMerger; import git4idea.merge.MergeChangeCollector; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.update.GitUpdateInfoAsLog; import git4idea.update.GitUpdatedRanges; import git4idea.util.GitUIUtil; import git4idea.util.GitUntrackedFilesHelper; import git4idea.util.LocalChangesWouldBeOverwrittenHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static com.intellij.notification.NotificationType.INFORMATION; import static git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector.Operation.MERGE; import static git4idea.update.GitUpdateSessionKt.getBodyForUpdateNotification; import static git4idea.update.GitUpdateSessionKt.getTitleForUpdateNotification; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; abstract class GitMergeAction extends GitRepositoryAction { private static final Logger LOG = Logger.getInstance(GitMergeAction.class); protected static class DialogState { final VirtualFile selectedRoot; final String progressTitle; final Computable<GitLineHandler> handlerProvider; @NotNull private final List<String> selectedBranches; DialogState(@NotNull VirtualFile root, @NotNull String title, @NotNull Computable<GitLineHandler> provider, @NotNull List<String> selectedBranches) { selectedRoot = root; progressTitle = title; handlerProvider = provider; this.selectedBranches = selectedBranches; } } @Nullable protected abstract DialogState displayDialog(@NotNull Project project, @NotNull List<VirtualFile> gitRoots, @NotNull VirtualFile defaultRoot); @Override protected void perform(@NotNull Project project, @NotNull List<VirtualFile> gitRoots, @NotNull VirtualFile defaultRoot) { DialogState dialogState = displayDialog(project, gitRoots, defaultRoot); if (dialogState == null) { return; } VirtualFile selectedRoot = dialogState.selectedRoot; Computable<GitLineHandler> handlerProvider = dialogState.handlerProvider; Label beforeLabel = LocalHistory.getInstance().putSystemLabel(project, "Before update"); new Task.Backgroundable(project, dialogState.progressTitle, true) { @Override public void run(@NotNull ProgressIndicator indicator) { GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project); Git git = Git.getInstance(); GitLocalChangesWouldBeOverwrittenDetector localChangesDetector = new GitLocalChangesWouldBeOverwrittenDetector(selectedRoot, MERGE); GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector = new GitUntrackedFilesOverwrittenByOperationDetector(selectedRoot); GitSimpleEventDetector mergeConflict = new GitSimpleEventDetector(GitSimpleEventDetector.Event.MERGE_CONFLICT); GitRepository repository = repositoryManager.getRepositoryForRoot(selectedRoot); assert repository != null : "Repository can't be null for root " + selectedRoot; GitUpdatedRanges updatedRanges = null; if (repository.getCurrentBranch() != null && dialogState.selectedBranches.size() == 1) { String selectedBranch = StringUtil.trimStart(dialogState.selectedBranches.get(0), "remotes/"); GitBranch targetBranch = repository.getBranches().findBranchByName(selectedBranch); if (targetBranch != null) { GitBranchPair refPair = new GitBranchPair(repository.getCurrentBranch(), targetBranch); updatedRanges = GitUpdatedRanges.calcInitialPositions(project, singletonMap(repository, refPair)); } else { LOG.warn("Couldn't find the branch with name [" + selectedBranch + "]"); } } String beforeRevision = repository.getCurrentRevision(); try (AccessToken ignore = DvcsUtil.workingTreeChangeStarted(project, getActionName())) { GitCommandResult result = git.runCommand(() -> { GitLineHandler handler = handlerProvider.compute(); handler.addLineListener(localChangesDetector); handler.addLineListener(untrackedFilesDetector); handler.addLineListener(mergeConflict); return handler; }); if (beforeRevision != null) { GitRevisionNumber currentRev = new GitRevisionNumber(beforeRevision); handleResult(result, project, mergeConflict, localChangesDetector, untrackedFilesDetector, repository, currentRev, beforeLabel, updatedRanges); } } } }.queue(); } private void handleResult(@NotNull GitCommandResult result, @NotNull Project project, @NotNull GitSimpleEventDetector mergeConflictDetector, @NotNull GitLocalChangesWouldBeOverwrittenDetector localChangesDetector, @NotNull GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector, @NotNull GitRepository repository, @NotNull GitRevisionNumber currentRev, @NotNull Label beforeLabel, @Nullable GitUpdatedRanges updatedRanges) { VirtualFile root = repository.getRoot(); if (mergeConflictDetector.hasHappened()) { new GitMergeCommittingConflictResolver(project, Git.getInstance(), new GitMerger(project), singletonList(root), new GitConflictResolver.Params(project), true).merge(); } if (result.success() || mergeConflictDetector.hasHappened()) { VfsUtil.markDirtyAndRefresh(false, true, false, root); repository.update(); if (updatedRanges != null && AbstractCommonUpdateAction.showsCustomNotification(singletonList(GitVcs.getInstance(project)))) { new GitUpdateInfoAsLog(project, updatedRanges.calcCurrentPositions(), (filesCount, commitCount, filteredCommits, viewCommits) -> { String title = getTitleForUpdateNotification(filesCount, commitCount); String content = getBodyForUpdateNotification(filesCount, commitCount, filteredCommits); Notification notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(title, content, INFORMATION, null); notification.addAction(NotificationAction.createSimple("View Commits", viewCommits)); return notification; }).buildAndShowNotification(); } else { showUpdates(project, root, currentRev, beforeLabel, getActionName()); } } else if (localChangesDetector.wasMessageDetected()) { LocalChangesWouldBeOverwrittenHelper.showErrorNotification(project, repository.getRoot(), getActionName(), localChangesDetector.getRelativeFilePaths()); } else if (untrackedFilesDetector.wasMessageDetected()) { GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, root, untrackedFilesDetector.getRelativeFilePaths(), getActionName(), null); } else { GitUIUtil.notifyError(project, "Git " + getActionName() + " Failed", result.getErrorOutputAsJoinedString(), true, null); repository.update(); } } private static void showUpdates(@NotNull Project project, @NotNull VirtualFile root, @NotNull GitRevisionNumber currentRev, @NotNull Label beforeLabel, @NotNull String actionName) { try { UpdatedFiles files = UpdatedFiles.create(); MergeChangeCollector collector = new MergeChangeCollector(project, root, currentRev); collector.collect(files); GuiUtils.invokeLaterIfNeeded(() -> { ProjectLevelVcsManagerEx manager = (ProjectLevelVcsManagerEx)ProjectLevelVcsManager.getInstance(project); UpdateInfoTree tree = manager.showUpdateProjectInfo(files, actionName, ActionInfo.UPDATE, false); if (tree != null) { tree.setBefore(beforeLabel); tree.setAfter(LocalHistory.getInstance().putSystemLabel(project, "After update")); ViewUpdateInfoNotification.focusUpdateInfoTree(project, tree); } }, ModalityState.defaultModalityState()); } catch (VcsException e) { GitVcs.getInstance(project).showErrors(singletonList(e), actionName); } } }
package com.mebigfatguy.fbcontrib.detect; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ExceptionTable; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import com.mebigfatguy.fbcontrib.utils.RegisterUtils; import com.mebigfatguy.fbcontrib.utils.SignatureUtils; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** looks for methods that catch checked exceptions, and throw unchecked * exceptions in their place. There are several levels of concern. Least * important are methods constrained by interface or super class contracts * not to throw checked exceptions but appear owned by the same author. Next * are methods constrained by interface or super class contracts and throw other * types of checked exceptions. Lastly are method not constrained by any interface * or superclass contract. */ public class ExceptionSoftening extends BytecodeScanningDetector { private static JavaClass runtimeClass; static { try { runtimeClass = Repository.lookupClass("java/lang/RuntimeException"); } catch (ClassNotFoundException cnfe) { runtimeClass = null; } } private final BugReporter bugReporter; private OpcodeStack stack; private Map<Integer, CodeException> catchHandlerPCs; private List<CatchInfo> catchInfos; private LocalVariableTable lvt; private Map<String, Set<String>> constrainingInfo; /** constructs a EXS detector given the reporter to report bugs on. * @param bugReporter the sync of bug reports */ public ExceptionSoftening(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** overrides the visitor to reset the stack * * @param classContext the context object of the currently parsed class */ @Override public void visitClassContext(ClassContext classContext) { try { if (runtimeClass != null) { stack = new OpcodeStack(); super.visitClassContext(classContext); } } finally { stack = null; } } /** overrides the visitor to look for methods that catch checked exceptions * and rethrow runtime exceptions * * @param obj the context object of the currently parsed code block */ @Override public void visitCode(Code obj) { try { Method method = getMethod(); if (prescreen(method)) { catchHandlerPCs = collectExceptions(obj.getExceptionTable()); if (!catchHandlerPCs.isEmpty()) { stack.resetForMethodEntry(this); catchInfos = new ArrayList<CatchInfo>(); lvt = method.getLocalVariableTable(); constrainingInfo = null; super.visitCode(obj); } } } finally { catchInfos = null; catchHandlerPCs = null; lvt = null; constrainingInfo = null; } } /** overrides the visitor to find catch blocks that throw runtime exceptions * * @param seen the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { try { stack.precomputation(this); int pc = getPC(); CodeException ex = catchHandlerPCs.get(Integer.valueOf(pc)); if (ex != null) { int endPC; if ((seen == GOTO) || (seen == GOTO_W)) endPC = this.getBranchTarget(); else endPC = Integer.MAX_VALUE; ConstantPool pool = getConstantPool(); ConstantClass ccls = (ConstantClass)pool.getConstant(ex.getCatchType()); String catchSig = ccls.getBytes(pool); CatchInfo ci = new CatchInfo(ex.getHandlerPC(), endPC, catchSig); catchInfos.add(ci); } updateEndPCsOnCatchRegScope(catchInfos, pc, seen); removeFinishedCatchBlocks(catchInfos, pc); if (seen == ATHROW) { try { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); JavaClass exClass = itm.getJavaClass(); if ((exClass != null) && exClass.instanceOf(runtimeClass)) { if (catchInfos.size() > 0) { Set<String> possibleCatchSignatures = findPossibleCatchSignatures(catchInfos, pc); if (!possibleCatchSignatures.contains(exClass.getClassName())) { boolean anyRuntimes = false; for (String possibleCatches : possibleCatchSignatures) { exClass = Repository.lookupClass(possibleCatches); if (exClass.instanceOf(runtimeClass)) { anyRuntimes = true; break; } } if (!anyRuntimes) { if (constrainingInfo == null) constrainingInfo = getConstrainingInfo(getClassContext().getJavaClass(), getMethod()); String bug = null; int priority = NORMAL_PRIORITY; if (constrainingInfo == null) { bug = "EXS_EXCEPTION_SOFTENING_NO_CONSTRAINTS"; priority = HIGH_PRIORITY; } else if (!constrainingInfo.values().iterator().next().isEmpty()) { bug = "EXS_EXCEPTION_SOFTENING_HAS_CHECKED"; priority = NORMAL_PRIORITY; } else { String pack1 = constrainingInfo.keySet().iterator().next(); String pack2 = getClassContext().getJavaClass().getClassName(); int dotPos = pack1.lastIndexOf('.'); if (dotPos >= 0) pack1 = pack1.substring(0, dotPos); else pack1 = ""; dotPos = pack2.lastIndexOf('.'); if (dotPos >= 0) pack2 = pack2.substring(0, dotPos); else pack2 = ""; if (SignatureUtils.similarPackages(pack1, pack2, 2)) { bug = "EXS_EXCEPTION_SOFTENING_NO_CHECKED"; priority = NORMAL_PRIORITY; } } if (bug != null) { bugReporter.reportBug(new BugInstance(this, bug, priority) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } } } finally { stack.sawOpcode(this, seen); } } /** * collects all the valid exception objects (ones where start and finish are before the target) * and with a catch type * * @param exceptions the exceptions from the class file * @return the filtered exceptions keyed by catch end pc */ private static LinkedHashMap<Integer, CodeException> collectExceptions(CodeException[] exceptions) { List<CodeException> filteredEx = new ArrayList<CodeException>(); for (CodeException ce : exceptions) { if ((ce.getCatchType() != 0) && (ce.getStartPC() < ce.getEndPC()) && (ce.getEndPC() <= ce.getHandlerPC())) { filteredEx.add(ce); } } LinkedHashMap<Integer, CodeException> handlers = new LinkedHashMap<Integer, CodeException>(); for (CodeException ex : filteredEx) { handlers.put(Integer.valueOf(ex.getEndPC()), ex); } return handlers; } /** remove catchinfo blocks from the map where the handler end is before the current pc * * @param infos the exception handlers installed * @param pc the current pc */ private static void removeFinishedCatchBlocks(List<CatchInfo> infos, int pc) { Iterator<CatchInfo> it = infos.iterator(); while (it.hasNext()) { if (it.next().getFinish() < pc) it.remove(); } } /** reduces the end pc based on the optional LocalVariableTable's exception register scope * * @param infos the list of active catch blocks * @param pc the current pc */ private void updateEndPCsOnCatchRegScope(List<CatchInfo> infos, int pc, int seen) { if (lvt != null) { for (CatchInfo ci : infos) { if (ci.getStart() == pc) { if ((seen == ASTORE) || ((seen >= ASTORE_0) && (seen <= ASTORE_3))) { int exReg = RegisterUtils.getAStoreReg(this, seen); LocalVariable lv = lvt.getLocalVariable(exReg, pc + 1); if (lv != null) { ci.setFinish(lv.getStartPC() + lv.getLength()); } break; } } } } } /** returns an array of catch types that the current pc is in * * @param infos the list of catch infos for this method * @param pc the current pc * @return an set of catch exception types that the pc is currently in */ private static Set<String> findPossibleCatchSignatures(List<CatchInfo> infos, int pc) { Set<String> catchTypes = new HashSet<String>(6); ListIterator<CatchInfo> it = infos.listIterator(infos.size()); while (it.hasPrevious()) { CatchInfo ci = it.previous(); if ((pc >= ci.getStart()) && (pc < ci.getFinish())) { catchTypes.add(ci.getSignature()); } else { break; } } return catchTypes; } /** finds the super class or interface that constrains the types of exceptions that can be thrown from the given method * * @param m the method to check * @return a map containing the class name to a set of exceptions that constrain this method */ private Map<String, Set<String>> getConstrainingInfo(JavaClass cls, Method m) throws ClassNotFoundException { String methodName = m.getName(); String methodSig = m.getSignature(); { //First look for the method in interfaces of the class JavaClass[] infClasses = cls.getInterfaces(); for (JavaClass infCls : infClasses) { Method infMethod = findMethod(infCls, methodName, methodSig); if (infMethod != null) { return buildConstrainingInfo(infCls, infMethod); } Map<String, Set<String>> constrainingExs = getConstrainingInfo(infCls, m); if (constrainingExs != null) { return constrainingExs; } } } { //Next look at the superclass JavaClass superCls = cls.getSuperClass(); if (superCls != null) { Method superMethod = findMethod(superCls, methodName, methodSig); if (superMethod != null) { return buildConstrainingInfo(superCls, superMethod); } //Otherwise recursively call this on the super class return getConstrainingInfo(superCls, m); } return null; } } /** finds a method that matches the name and signature in the given class * @param cls the class to look in * @param methodName the name to look for * @param methodSig the signature to look for * * @return the method or null */ private static Method findMethod(JavaClass cls, String methodName, String methodSig) { Method[] methods = cls.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) && method.getSignature().equals(methodSig)) { return method; } } return null; } /** returns exception names describing what exceptions are allowed to be thrown * * @param cls the cls to find the exceptions in * @param m the method to add exceptions from * @return a map with one entry of a class name to a set of exceptions that constrain what can be thrown. */ private static Map<String, Set<String>> buildConstrainingInfo(JavaClass cls, Method m) throws ClassNotFoundException { Map<String, Set<String>> constraintInfo = new HashMap<String, Set<String>>(); Set<String> exs = new HashSet<String>(); ExceptionTable et = m.getExceptionTable(); if (et != null) { int[] indexTable = et.getExceptionIndexTable(); ConstantPool pool = cls.getConstantPool(); for (int index : indexTable) { if (index != 0) { ConstantClass ccls = (ConstantClass)pool.getConstant(index); String exName = ccls.getBytes(pool); JavaClass exClass = Repository.lookupClass(exName); if (!exClass.instanceOf(runtimeClass)) exs.add(ccls.getBytes(pool)); } } } constraintInfo.put(cls.getClassName(), exs); return constraintInfo; } /** returns whether a method explicitly throws an exception * * @param method the currently parsed method * @return if the method throws an exception */ private boolean prescreen(Method method) { BitSet bytecodeSet = getClassContext().getBytecodeSet(method); return (bytecodeSet != null) && (bytecodeSet.get(Constants.ATHROW)); } private static class CatchInfo { private final int catchStart; private int catchFinish; private final String catchSignature; public CatchInfo(int start, int finish, String signature) { catchStart = start; catchFinish = finish; catchSignature = signature; } public int getStart() { return catchStart; } public void setFinish(int finish) { catchFinish = finish; } public int getFinish() { return catchFinish; } public String getSignature() { return catchSignature; } @Override public String toString() { return "CatchInfo[catchStart=" + catchStart + ", catchFinish=" + catchFinish + ", catchSignature=" + catchSignature + "]"; } } }
package com.mebigfatguy.fbcontrib.detect; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.bcel.Constants; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantMethodref; import org.apache.bcel.classfile.ConstantNameAndType; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.ConstantValue; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.CodeByteUtils; import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.RegisterUtils; import com.mebigfatguy.fbcontrib.utils.TernaryPatcher; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.visitclass.LVTHelper; /** * looks for silly bugs that are simple but do not fit into one large pattern. */ @CustomUserValue public class SillynessPotPourri extends BytecodeScanningDetector { private static final Set<String> collectionInterfaces = new HashSet<String>(); static { collectionInterfaces.add("java/util/Collection"); collectionInterfaces.add("java/util/List"); collectionInterfaces.add("java/util/Set"); collectionInterfaces.add("java/util/SortedSet"); collectionInterfaces.add("java/util/Map"); collectionInterfaces.add("java/util/SortedMap"); } private static final Set<String> oddMissingEqualsClasses = new HashSet<String>(); static { oddMissingEqualsClasses.add("java.lang.StringBuffer"); oddMissingEqualsClasses.add("java.lang.StringBuilder"); } private static final String LITERAL = "literal"; private static final Pattern APPEND_PATTERN = Pattern.compile("append:([0-9]+):(.*)"); private static JavaClass calendarClass; static { try { calendarClass = Repository.lookupClass("java/util/Calendar"); } catch (ClassNotFoundException cnfe) { calendarClass = null; } } private static Map<String, Integer> methodsThatAreSillyOnStringLiterals = new HashMap<String, Integer>(); static { methodsThatAreSillyOnStringLiterals.put("toLowerCase()Ljava/lang/String;", Values.ZERO); methodsThatAreSillyOnStringLiterals.put("toUpperCase()Ljava/lang/String;", Values.ZERO); methodsThatAreSillyOnStringLiterals.put("toLowerCase(Ljava/util/Locale;)Ljava/lang/String;", Values.ONE); methodsThatAreSillyOnStringLiterals.put("toUpperCase(Ljava/util/Locale;)Ljava/lang/String;", Values.ONE); methodsThatAreSillyOnStringLiterals.put("trim()Ljava/lang/String;", Values.ZERO); methodsThatAreSillyOnStringLiterals.put("isEmpty()Z", Values.ZERO); } private final BugReporter bugReporter; private final Set<String> toStringClasses; private OpcodeStack stack; private int lastPCs[]; private int lastOpcode; private int lastReg; private boolean lastIfEqWasBoolean; private boolean lastLoadWasString; /** branch targets, to a set of branch instructions */ private Map<Integer, BitSet> branchTargets; private Set<String> staticConstants; /** * constructs a SPP detector given the reporter to report bugs on * @param bugReporter the sync of bug reports */ public SillynessPotPourri(BugReporter bugReporter) { this.bugReporter = bugReporter; toStringClasses = new HashSet<String>(); } @Override public void visitField(Field field) { if ("serialVersionUID".equals(field.getName()) && ((field.getAccessFlags() & ACC_STATIC) != 0) && ((field.getAccessFlags() & ACC_PRIVATE) == 0)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_SERIALVER_SHOULD_BE_PRIVATE.name(), LOW_PRIORITY) .addClass(this) .addField(this)); } } @Override public void visitClassContext(ClassContext classContext) { try { stack = new OpcodeStack(); lastPCs = new int[4]; branchTargets = new HashMap<Integer, BitSet>(); super.visitClassContext(classContext); } finally { stack = null; lastPCs = null; branchTargets = null; staticConstants = null; } } /** * implements the visitor to reset the opcode stack * * @param obj the context object for the currently parsed Code */ @Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); lastOpcode = -1; lastReg = -1; lastIfEqWasBoolean = false; lastLoadWasString = false; Arrays.fill(lastPCs, -1); branchTargets.clear(); super.visitCode(obj); } /** * implements the visitor to look for various silly bugs * * @param seen the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { int reg = -1; String userValue = null; try { stack.precomputation(this); if (isBranchByteCode(seen)) { Integer branchTarget = Integer.valueOf(getBranchTarget()); BitSet branchInsSet = branchTargets.get(branchTarget); if (branchInsSet == null) { branchInsSet = new BitSet(); branchTargets.put(branchTarget, branchInsSet); } branchInsSet.set(getPC()); } //not an else if, because some of the opcodes in the previous branch also matter here. if ((seen == IFEQ) || (seen == IFLE) || (seen == IFNE)) { checkForEmptyStringAndNullChecks(seen); } //see above, several opcodes hit multiple branches. if ((seen == IFEQ) || (seen == IFNE) || (seen == IFGT)) { checkSizeEquals0(); } if (seen == IFEQ) { checkNullAndInstanceOf(); } if (seen == IFNE) { checkNotEqualsStringBuilderLength(); } else if (seen == IFEQ) { checkEqualsStringBufferLength(); } else if ((seen == IRETURN) && lastIfEqWasBoolean) { checkForUselessTernaryReturn(); } else if (seen == LDC2_W) { checkApproximationsOfMathConstants(); } else if (seen == DCMPL) { checkCompareToNaNDouble(); } else if (seen == FCMPL) { checkCompareToNaNFloat(); } else if (OpcodeUtils.isAStore(seen)) { reg = RegisterUtils.getAStoreReg(this, seen); checkStutterdAssignment(seen, reg); checkImmutableUsageOfStringBuilder(reg); } else if (OpcodeUtils.isALoad(seen)) { sawLoad(seen); } else if ((seen >= ICONST_0) && (seen <= ICONST_3)) { userValue = sawIntConst(userValue); } else if (seen == CALOAD) { checkImproperToCharArrayUse(); } else if (seen == INVOKESTATIC) { userValue = sawInvokeStatic(userValue); } else if (seen == INVOKEVIRTUAL) { userValue = sawInvokeVirtual(userValue); } else if (seen == INVOKESPECIAL) { sawInvokeSpecial(); } else if (seen == INVOKEINTERFACE) { userValue = sawInvokeInterface(userValue); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { TernaryPatcher.pre(stack, seen); stack.sawOpcode(this, seen); TernaryPatcher.post(stack, seen); if ((stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); if (userValue != null) { item.setUserValue(userValue); } else if ("iterator".equals(item.getUserValue()) && (seen == GETFIELD) || (seen == ALOAD) || ((seen >= ALOAD_0) && (seen <= ALOAD_3))) { item.setUserValue(null); } } lastOpcode = seen; lastReg = reg; System.arraycopy(lastPCs, 1, lastPCs, 0, 3); lastPCs[3] = getPC(); } } private void checkImproperToCharArrayUse() { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); String ic = (String)item.getUserValue(); if ("iconst".equals(ic)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_CHARAT.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } private String sawIntConst(String userValue) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); String tca = (String)item.getUserValue(); if ("toCharArray".equals(tca)) { userValue = "iconst"; } } return userValue; } private void sawLoad(int seen) { lastLoadWasString = false; LocalVariableTable lvt = getMethod().getLocalVariableTable(); if (lvt != null) { LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, RegisterUtils.getALoadReg(this, seen), getPC()); if (lv != null) { lastLoadWasString = "Ljava/lang/String;".equals(lv.getSignature()); } } } private void checkStutterdAssignment(int seen, int reg) { if (seen == lastOpcode && reg == lastReg) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_STUTTERED_ASSIGNMENT.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } private void checkImmutableUsageOfStringBuilder(int reg) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); String mName = (String) item.getUserValue(); if (mName != null) { if ("trim".equals(mName)) { item.setUserValue(null); } else { Matcher m = APPEND_PATTERN.matcher(mName); if (m.matches()) { int appendReg = Integer.parseInt(m.group(1)); if (reg == appendReg) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_STRINGBUILDER_IS_MUTABLE.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } private void checkCompareToNaNFloat() { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(0); Float f1 = (Float)item.getConstant(); item = stack.getStackItem(1); Float f2 = (Float)item.getConstant(); if (((f1 != null) && f1.isNaN()) || ((f2 != null) && f2.isNaN())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_ISNAN.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this) .addString("float") .addString("Float")); } } } private void checkCompareToNaNDouble() { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(0); Double d1 = (Double)item.getConstant(); item = stack.getStackItem(1); Double d2 = (Double)item.getConstant(); if (((d1 != null) && d1.isNaN()) || ((d2 != null) && d2.isNaN())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_ISNAN.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this) .addString("double") .addString("Double")); } } } private void checkApproximationsOfMathConstants() { Object con = getConstantRefOperand(); if (con instanceof ConstantDouble) { double d = ((ConstantDouble) con).getBytes(); double piDelta = Math.abs(d - Math.PI); double eDelta = Math.abs(d - Math.E); if (((piDelta > 0.0) && (piDelta < 0.002)) || ((eDelta > 0.0) && (eDelta < 0.002))) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_MATH_CONSTANT.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } private void checkForUselessTernaryReturn() { byte[] bytes = getCode().getCode(); if ((lastPCs[0] != -1) && ((0x00FF & bytes[lastPCs[3]]) == ICONST_0) && ((0x00FF & bytes[lastPCs[2]]) == GOTO) && ((0x00FF & bytes[lastPCs[1]]) == ICONST_1) && ((0x00FF & bytes[lastPCs[0]]) == IFEQ)) { if (getMethod().getSignature().endsWith("Z")) { boolean bug = true; BitSet branchInsSet = branchTargets.get(Integer.valueOf(lastPCs[1])); if (branchInsSet != null) { bug = false; } branchInsSet = branchTargets.get(Integer.valueOf(lastPCs[3])); if ((branchInsSet != null) && (branchInsSet.cardinality() > 1)) { bug = false; } if (bug) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USELESS_TERNARY.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } private void checkEqualsStringBufferLength() { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); lastIfEqWasBoolean = "Z".equals(itm.getSignature()); } byte[] bytes = getCode().getCode(); if (lastPCs[1] != -1) { if (CodeByteUtils.getbyte(bytes, lastPCs[3]) == INVOKEVIRTUAL) { int loadIns = CodeByteUtils.getbyte(bytes, lastPCs[2]); if (((loadIns == LDC) || (loadIns == LDC_W)) && (CodeByteUtils.getbyte(bytes, lastPCs[1]) == INVOKEVIRTUAL)) { ConstantPool pool = getConstantPool(); int toStringIndex = CodeByteUtils.getshort(bytes, lastPCs[1]+1); Constant cmr = pool.getConstant(toStringIndex); if (cmr instanceof ConstantMethodref) { ConstantMethodref toStringMR = (ConstantMethodref)cmr; String toStringCls = toStringMR.getClass(pool); if (toStringCls.startsWith("java.lang.&&StringBu")) { int consIndex = CodeByteUtils.getbyte(bytes, lastPCs[2]+1); Constant c = pool.getConstant(consIndex); if (c instanceof ConstantString) { if ("".equals(((ConstantString) c).getBytes(pool))) { int nandtIndex = toStringMR.getNameAndTypeIndex(); ConstantNameAndType cnt = (ConstantNameAndType)pool.getConstant(nandtIndex); if ("toString".equals(cnt.getName(pool))) { int lengthIndex = CodeByteUtils.getshort(bytes, lastPCs[3]+1); ConstantMethodref lengthMR = (ConstantMethodref)pool.getConstant(lengthIndex); nandtIndex = lengthMR.getNameAndTypeIndex(); cnt = (ConstantNameAndType)pool.getConstant(nandtIndex); if ("equals".equals(cnt.getName(pool))) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_STRINGBUILDER_LENGTH.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } } } } } private void checkNotEqualsStringBuilderLength() { byte[] bytes = getCode().getCode(); if (lastPCs[2] != -1) { if ((CodeByteUtils.getbyte(bytes, lastPCs[3]) == INVOKEVIRTUAL) && (CodeByteUtils.getbyte(bytes, lastPCs[2]) == INVOKEVIRTUAL)) { ConstantPool pool = getConstantPool(); int toStringIndex = CodeByteUtils.getshort(bytes, lastPCs[2]+1); ConstantMethodref toStringMR = (ConstantMethodref)pool.getConstant(toStringIndex); String toStringCls = toStringMR.getClass(pool); if (toStringCls.startsWith("java.lang.StringBu")) { int nandtIndex = toStringMR.getNameAndTypeIndex(); ConstantNameAndType cnt = (ConstantNameAndType)pool.getConstant(nandtIndex); if ("toString".equals(cnt.getName(pool))) { int lengthIndex = CodeByteUtils.getshort(bytes, lastPCs[3]+1); ConstantMethodref lengthMR = (ConstantMethodref)pool.getConstant(lengthIndex); nandtIndex = lengthMR.getNameAndTypeIndex(); cnt = (ConstantNameAndType)pool.getConstant(nandtIndex); if ("length".equals(cnt.getName(pool))) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_STRINGBUILDER_LENGTH.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } private void checkNullAndInstanceOf() { byte[] bytes = getCode().getCode(); if ((lastPCs[0] != -1) && (CodeByteUtils.getbyte(bytes, lastPCs[1]) == IFNULL) && (CodeByteUtils.getbyte(bytes, lastPCs[3]) == INSTANCEOF)) { int ins0 = CodeByteUtils.getbyte(bytes, lastPCs[0]); if ((ins0 == ALOAD) || (ins0 == ALOAD_0) || (ins0 == ALOAD_1) || (ins0 == ALOAD_2) || (ins0 == ALOAD_3)) { int ins2 = CodeByteUtils.getbyte(bytes, lastPCs[0]); if (ins0 == ins2) { if ((ins0 != ALOAD) || (CodeByteUtils.getbyte(bytes, lastPCs[0] + 1) == CodeByteUtils.getbyte(bytes, lastPCs[2] + 1))) { int ifNullTarget = lastPCs[1] + CodeByteUtils.getshort(bytes, lastPCs[1]+1); if (ifNullTarget == getBranchTarget()) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NULL_BEFORE_INSTANCEOF.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } private void checkSizeEquals0() { if (stack.getStackDepth() == 1) { OpcodeStack.Item item = stack.getStackItem(0); if ("size".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_ISEMPTY.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } private void checkForEmptyStringAndNullChecks(int seen) { if (lastLoadWasString && (lastPCs[0] != -1)) { byte[] bytes = getCode().getCode(); int loadIns = CodeByteUtils.getbyte(bytes, lastPCs[2]); if ((((loadIns >= ALOAD_0) && (loadIns <= ALOAD_3)) || (loadIns == ALOAD)) && (CodeByteUtils.getbyte(bytes, lastPCs[3]) == INVOKEVIRTUAL) && (CodeByteUtils.getbyte(bytes, lastPCs[2]) == loadIns) && (CodeByteUtils.getbyte(bytes, lastPCs[1]) == IFNULL) && (CodeByteUtils.getbyte(bytes, lastPCs[0]) == loadIns) && ((loadIns != ALOAD) || (CodeByteUtils.getbyte(bytes, lastPCs[2]+1) == CodeByteUtils.getbyte(bytes, lastPCs[0]+1)))) { int brOffset = (loadIns == ALOAD) ? 11 : 10; if ((seen == IFNE) ? CodeByteUtils.getshort(bytes, lastPCs[1]+1) > brOffset : CodeByteUtils.getshort(bytes, lastPCs[1]+1) == brOffset) { int nextOp = CodeByteUtils.getbyte(bytes, getNextPC()); if ((nextOp != GOTO) && (nextOp != GOTO_W)) { ConstantPool pool = getConstantPool(); int mpoolIndex = CodeByteUtils.getshort(bytes, lastPCs[3]+1); ConstantMethodref cmr = (ConstantMethodref)pool.getConstant(mpoolIndex); int nandtIndex = cmr.getNameAndTypeIndex(); ConstantNameAndType cnt = (ConstantNameAndType)pool.getConstant(nandtIndex); if ("length".equals(cnt.getName(pool))) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_SUSPECT_STRING_TEST.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } } private static boolean isBranchByteCode(int seen) { return ((seen >= IFEQ) && (seen <= GOTO)) || (seen == IFNULL) || (seen == IFNONNULL) || (seen == GOTO_W); } private String sawInvokeStatic(String userValue) { String className = getClassConstantOperand(); String methodName = getNameConstantOperand(); if ("java/lang/System".equals(className)) { if ("getProperties".equals(methodName)) { userValue = "getProperties"; } else if ("arraycopy".equals(methodName)) { if (stack.getStackDepth() >= 5) { OpcodeStack.Item item = stack.getStackItem(2); String sig = item.getSignature(); if ((sig.charAt(0) != '[') && !"Ljava/lang/Object;".equals(sig)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NON_ARRAY_PARM.name(), HIGH_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } item = stack.getStackItem(4); sig = item.getSignature(); if ((sig.charAt(0) != '[') && !"Ljava/lang/Object;".equals(sig)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NON_ARRAY_PARM.name(), HIGH_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } else if ("java/lang/reflect/Array".equals(className)) { int offset = -1; if ("getLength".equals(methodName)) { offset = 0; } else if (methodName.startsWith("get")) { offset = 1; } else if (methodName.startsWith("set")) { offset = 2; } if (offset >= 0) { if (stack.getStackDepth() > offset) { OpcodeStack.Item item = stack.getStackItem(offset); String sig = item.getSignature(); if ((sig.charAt(0) != '[') && !"Ljava/lang/Object;".equals(sig)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NON_ARRAY_PARM.name(), HIGH_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } else if ("java/lang/String".equals(className)) { if ("format".equals(methodName)) { OpcodeStack.Item item = stack.getStackItem(1); String format = (String) item.getConstant(); if ((format != null) && !format.contains("%")) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_STATIC_FORMAT_STRING.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } return userValue; } private String sawInvokeVirtual(String userValue) throws ClassNotFoundException { String className = getClassConstantOperand(); String methodName = getNameConstantOperand(); if ("java/util/BitSet".equals(className)) { bitSetSilliness(methodName); } else if ("java/lang/StringBuilder".equals(className) || "java/lang/StringBuffer".equals(className)) { userValue = stringBufferSilliness(userValue, methodName); } else if ("java/lang/String".equals(className)) { userValue = stringSilliness(userValue, methodName, getSigConstantOperand()); } else if ("equals(Ljava/lang/Object;)Z".equals(methodName + getSigConstantOperand())) { equalsSilliness(className); } else if ("java/lang/Boolean".equals(className) && "booleanValue".equals(methodName)) { booleanSilliness(); } else if (("java/util/GregorianCalendar".equals(className) || "java/util/Calendar".equals(className)) && ("after".equals(methodName) || "before".equals(methodName))) { calendarBeforeAfterSilliness(); } else if ("java/util/Properties".equals(className)) { propertiesSilliness(methodName); } else if ("toString".equals(methodName) && "java/lang/Object".equals(className)) { defaultToStringSilliness(); } return userValue; } private void bitSetSilliness(String methodName) { if ("clear".equals(methodName) || "flip".equals(methodName) || "get".equals(methodName) || "set".equals(methodName)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object o =item.getConstant(); if (o instanceof Integer) { if (((Integer) o).intValue() < 0) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NEGATIVE_BITSET_ITEM.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } private String stringBufferSilliness(String userValue, String methodName) { if ("append".equals(methodName)) { if (stack.getStackDepth() > 1) { OpcodeStack.Item valItem = stack.getStackItem(0); OpcodeStack.Item sbItem = stack.getStackItem(1); Object constant = valItem.getConstant(); boolean argIsLiteralString = (constant instanceof String) && (((String) constant).length() > 0); argIsLiteralString = argIsLiteralString && !looksLikeStaticFieldValue((String) constant); if (argIsLiteralString) { String existingAppend = (String) sbItem.getUserValue(); if (existingAppend != null) { Matcher m = APPEND_PATTERN.matcher(existingAppend); if (m.matches() && LITERAL.equals(m.group(2))) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_DOUBLE_APPENDED_LITERALS.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); argIsLiteralString = false; } } } String literal = argIsLiteralString ? LITERAL : ""; if (sbItem.getRegisterNumber() > -1) { userValue = "append:" + sbItem.getRegisterNumber() + ':' + literal; } else { userValue = (String) sbItem.getUserValue(); if (userValue != null) { Matcher m = APPEND_PATTERN.matcher(userValue); if (m.matches()) { userValue = "append:" + m.group(1) + ':' + literal; } } } } } return userValue; } private String stringSilliness(String userValue, String methodName, String signature) { Integer stackOffset = methodsThatAreSillyOnStringLiterals.get(methodName + signature); if (stackOffset != null) { if (stack.getStackDepth() > stackOffset.intValue()) { OpcodeStack.Item itm = stack.getStackItem(stackOffset.intValue()); Object constant = itm.getConstant(); if ((constant != null) && constant.getClass().equals(String.class) && (itm.getXField() == null)) { int priority = NORMAL_PRIORITY; if (Type.getArgumentTypes(getSigConstantOperand()).length > 0) { //if an argument is passed in, it may be locale-specific priority = LOW_PRIORITY; } bugReporter.reportBug(new BugInstance(this, BugType.SPP_CONVERSION_OF_STRING_LITERAL.name(), priority) .addClass(this) .addMethod(this) .addSourceLine(this) .addCalledMethod(this)); } } } //not an elseif because the below cases might be in the set methodsThatAreSillyOnStringLiterals if ("intern".equals(methodName)) { String owningMethod = getMethod().getName(); if (!Values.STATIC_INITIALIZER.equals(owningMethod)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getConstant() != null) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_INTERN_ON_CONSTANT.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } else if ("toCharArray".equals(methodName)) { userValue = "toCharArray"; } else if ("toLowerCase".equals(methodName) || "toUpperCase".equals(methodName)) { userValue = "IgnoreCase"; } else if ("equalsIgnoreCase".equals(methodName) || "compareToIgnoreCase".equals(methodName)) { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(1); if ("IgnoreCase".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USELESS_CASING.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } item = stack.getStackItem(0); String parm = (String)item.getConstant(); if ("".equals(parm)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_EMPTY_CASING.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } else if ("trim".equals(methodName)) { userValue = "trim"; } else if ("length".equals(methodName)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); if ("trim".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_TEMPORARY_TRIM.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } else if ("equals".equals(methodName)) { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(1); if ("trim".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_TEMPORARY_TRIM.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } else if ("toString".equals(methodName)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_TOSTRING_ON_STRING.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } return userValue; } private void equalsSilliness(String className) { try { JavaClass cls = Repository.lookupClass(className); if (cls.isEnum()) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_EQUALS_ON_ENUM.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } else { if (stack.getStackDepth() >= 2) { OpcodeStack.Item item = stack.getStackItem(1); cls = item.getJavaClass(); if (cls != null) { String clsName = cls.getClassName(); if (oddMissingEqualsClasses.contains(clsName)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_EQUALS_ON_STRING_BUILDER.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } } private void booleanSilliness() { if (lastPCs[0] != -1) { int range1Size = lastPCs[2] - lastPCs[0]; if (range1Size == (getNextPC() - lastPCs[3])) { byte[] bytes = getCode().getCode(); int ifeq = 0x000000FF & bytes[lastPCs[2]]; if (ifeq == IFEQ) { int start1 = lastPCs[0]; int start2 = lastPCs[3]; boolean found = true; for (int i = 0; i < range1Size; i++) { if (bytes[start1+i] != bytes[start2+i]) { found = false; break; } } if (found) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_INVALID_BOOLEAN_NULL_CHECK.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } private void calendarBeforeAfterSilliness() { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(0); String itemSig = item.getSignature(); //Rule out java.lang.Object as mergeJumps can throw away type info (BUG) if (!"Ljava/lang/Object;".equals(itemSig) && !"Ljava/util/Calendar;".equals(itemSig) && !"Ljava/util/GregorianCalendar;".equals(itemSig)) { try { JavaClass cls = Repository.lookupClass(itemSig.substring(1, itemSig.length() - 1)); if (!cls.instanceOf(calendarClass)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_INVALID_CALENDAR_COMPARE.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } } } } private void defaultToStringSilliness() throws ClassNotFoundException { if (stack.getStackDepth() >= 1) { OpcodeStack.Item item = stack.getStackItem(0); JavaClass toStringClass = item.getJavaClass(); if (toStringClass != null) { String toStringClassName = toStringClass.getClassName(); if (!toStringClass.isInterface() && !toStringClass.isAbstract() && !"java.lang.Object".equals(toStringClassName) && !"java.lang.String".equals(toStringClassName) && toStringClasses.add(toStringClassName)) { try { JavaClass cls = Repository.lookupClass(toStringClassName); if (!hasToString(cls)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NON_USEFUL_TOSTRING.name(), toStringClass.isFinal() ? NORMAL_PRIORITY : LOW_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } } } } } private void propertiesSilliness(String methodName) { if (("get".equals(methodName) || "getProperty".equals(methodName))) { if (stack.getStackDepth() > 1) { OpcodeStack.Item item = stack.getStackItem(1); if ("getProperties".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_GETPROPERTY.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } private String sawInvokeInterface(String userValue) { String className = getClassConstantOperand(); if ("java/util/Map".equals(className)) { String method = getNameConstantOperand(); if ("keySet".equals(method)) { userValue = "keySet"; } } else if ("java/util/Set".equals(className)) { String method = getNameConstantOperand(); if ("contains".equals(method)) { if (stack.getStackDepth() >= 2) { OpcodeStack.Item item = stack.getStackItem(1); if ("keySet".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_CONTAINSKEY.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } else if ("java/util/List".equals(className)) { String method = getNameConstantOperand(); if ("iterator".equals(method)) { userValue = "iterator"; } } else if ("java/util/Iterator".equals(className)) { String method = getNameConstantOperand(); if ("next".equals(method)) { if (stack.getStackDepth() >= 1) { OpcodeStack.Item item = stack.getStackItem(0); if ("iterator".equals(item.getUserValue())) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_GET0.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } if (collectionInterfaces.contains(className)) { String method = getNameConstantOperand(); if ("size".equals(method)) { userValue = "size"; } } return userValue; } private void sawInvokeSpecial() { String className = getClassConstantOperand(); if ("java/lang/StringBuffer".equals(className) || "java/lang/StringBuilder".equals(className)) { String methodName = getNameConstantOperand(); if (Values.CONSTRUCTOR.equals(methodName)) { String signature = getSigConstantOperand(); if ("(I)V".equals(signature)) { if (lastOpcode == BIPUSH) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object o = item.getConstant(); if (o instanceof Integer) { int parm = ((Integer) o).intValue(); if ((parm > 32) && (parm < 127) && (parm != 64) && ((parm % 10) != 0) && ((parm % 5) != 0)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_NO_CHAR_SB_CTOR.name(), LOW_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } else if ("(Ljava/lang/String;)V".equals(signature)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); String con = (String)item.getConstant(); if ("".equals(con)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_STRINGBUFFER_WITH_EMPTY_STRING.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } else if ("java/math/BigDecimal".equals(className)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object constant = item.getConstant(); if (constant instanceof Double) { double v = ((Double) constant).doubleValue(); if ((v != 0.0) && (v != 1.0)) { bugReporter.reportBug(new BugInstance(this, BugType.SPP_USE_BIGDECIMAL_STRING_CTOR.name(), NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } } } } private boolean looksLikeStaticFieldValue(String constant) { if (staticConstants == null) { staticConstants = new HashSet<String>(); Field[] fields = getClassContext().getJavaClass().getFields(); for (Field f : fields) { if (((f.getAccessFlags() & (Constants.ACC_FINAL|Constants.ACC_STATIC)) == (Constants.ACC_FINAL|Constants.ACC_STATIC)) && "Ljava/lang/String;".equals(f.getSignature())) { ConstantValue cv = f.getConstantValue(); if (cv != null) { int cvIndex = cv.getConstantValueIndex(); staticConstants.add(getConstantPool().getConstantString(cvIndex, Constants.CONSTANT_String)); } } } } return staticConstants.contains(constant); } private boolean hasToString(JavaClass cls) throws ClassNotFoundException { do { for (Method m : cls.getMethods()) { if ("toString".equals(m.getName()) && "()Ljava/lang/String;".equals(m.getSignature())) { return true; } } cls = cls.getSuperClass(); } while (!"java.lang.Object".equals(cls.getClassName())); return false; } }
package com.swabunga.spell.swing; import com.swabunga.spell.engine.SpellDictionary; import com.swabunga.spell.engine.SpellDictionaryHashMap; import com.swabunga.spell.event.DocumentWordTokenizer; import com.swabunga.spell.event.SpellCheckEvent; import com.swabunga.spell.event.SpellCheckListener; import com.swabunga.spell.event.SpellChecker; import javax.swing.*; import javax.swing.text.JTextComponent; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.ResourceBundle; /** This class spellchecks a JTextComponent throwing up a Dialog everytime * it encounters a misspelled word. * * @author Robert Gustavsson (robert@lindesign.se) */ public class JTextComponentSpellChecker implements SpellCheckListener { // private static final String COMPLETED="COMPLETED"; private String dialogTitle = null; private SpellChecker spellCheck = null; private JSpellDialog dlg = null; private JTextComponent textComp = null; private ResourceBundle messages; // Constructor public JTextComponentSpellChecker(SpellDictionary dict) { this(dict, null); } // Convinient Constructors, for those lazy guys. public JTextComponentSpellChecker(String dictFile) throws IOException { this(dictFile, null); } public JTextComponentSpellChecker(String dictFile, String title) throws IOException { this(new SpellDictionaryHashMap(new File(dictFile)), title); } public JTextComponentSpellChecker(String dictFile, String phoneticFile, String title) throws IOException { this(new SpellDictionaryHashMap(new File(dictFile), new File(phoneticFile)), title); } public JTextComponentSpellChecker(SpellDictionary dict, String title) { spellCheck = new SpellChecker(dict); spellCheck.setCache(); spellCheck.addSpellCheckListener(this); dialogTitle = title; messages = ResourceBundle.getBundle("com.swabunga.spell.swing.messages", Locale.getDefault()); } // MEMBER METHODS /** * Set user dictionary (used when a word is added) */ public void setUserDictionary(SpellDictionary dictionary) { if (spellCheck != null) spellCheck.setUserDictionary(dictionary); } private void setupDialog(JTextComponent textComp) { Component comp = SwingUtilities.getRoot(textComp); // Probably the most common situation efter the first time. if (dlg != null && dlg.getOwner() == comp) return; if (comp != null && comp instanceof Window) { if (comp instanceof Frame) dlg = new JSpellDialog((Frame) comp, dialogTitle, true); if (comp instanceof Dialog) dlg = new JSpellDialog((Dialog) comp, dialogTitle, true); // Put the dialog in the middle of it's parent. if (dlg != null) { Window win = (Window) comp; int x = (int) (win.getLocation().getX() + win.getWidth() / 2 - dlg.getWidth() / 2); int y = (int) (win.getLocation().getY() + win.getHeight() / 2 - dlg.getHeight() / 2); dlg.setLocation(x, y); } } else { dlg = new JSpellDialog((Frame) null, dialogTitle, true); } } /** * This method is called to check the spelling of a JTextComponent. * * @param textComp The JTextComponent to spellcheck. * @return Either SpellChecker.SPELLCHECK_OK, SpellChecker.SPELLCHECK_CANCEL or the number of errors found. The number of errors are those that * are found BEFORE any corrections are made. */ public synchronized int spellCheck(JTextComponent textComp) { setupDialog(textComp); this.textComp = textComp; DocumentWordTokenizer tokenizer = new DocumentWordTokenizer(textComp.getDocument()); int exitStatus = spellCheck.checkSpelling(tokenizer); textComp.requestFocus(); textComp.setCaretPosition(0); this.textComp = null; return exitStatus; } public void spellingError(SpellCheckEvent event) { // java.util.List suggestions = event.getSuggestions(); event.getSuggestions(); int start = event.getWordContextPosition(); int end = start + event.getInvalidWord().length(); // Mark the invalid word in TextComponent textComp.requestFocus(); textComp.setCaretPosition(0); textComp.setCaretPosition(start); textComp.moveCaretPosition(end); dlg.show(event); } }
package com.syntacticsugar.vooga.util.webconnect; import java.util.HashMap; import java.util.Map; import org.json.*; import com.syntacticsugar.vooga.util.compress.Compressor; public class JSONHelper { public static String extractXML(JSONObject json) { try { String xml = json.getString("xml"); xml = Compressor.decompress16(xml); return xml; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } public static void printArray(JSONArray arr) { for (int i = 0; i < arr.length(); i++) { try { JSONObject entry = (JSONObject) arr.get(i); System.out.println(entry.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static JSONObject createXMLJSON(String author, String gamename, String description, String xml) { Map<String, String> map = new HashMap<String, String>(); xml = Compressor.compress16(xml); map.put("xml", xml); map.put("author", author); map.put("gamename", gamename); map.put("description", description); return new JSONObject(map); } public static JSONObject createCommentJSON(int id, String author, String comment) { Map<String, String> map = new HashMap<String, String>(); map.put("id", Integer.toString(id)); map.put("author", author); map.put("comment", comment); return new JSONObject(map); } }
package me.nallar.tickthreading.mappings; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Splitter; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.io.Files; import me.nallar.tickthreading.Log; public class MCPMappings extends Mappings { private static final Pattern extendsPattern = Pattern.compile("\\s+?extends\\s+?([\\S]+)[^\\{]+?\\{", Pattern.DOTALL | Pattern.MULTILINE); private static final Pattern packagePattern = Pattern.compile("package\\s+?([^\\s;]+)[^;]*?;", Pattern.DOTALL | Pattern.MULTILINE); private final Map<String, String> methodSeargeMappings = new HashMap<String, String>(); private final Map<String, String> fieldSeargeMappings = new HashMap<String, String>(); private final BiMap<ClassDescription, ClassDescription> classMappings = HashBiMap.create(); private final BiMap<MethodDescription, MethodDescription> methodMappings = HashBiMap.create(); private final Map<FieldDescription, FieldDescription> fieldMappings = new HashMap<FieldDescription, FieldDescription>(); private final Map<String, MethodDescription> parameterlessMethodMappings = new HashMap<String, MethodDescription>(); private final Map<String, String> classNameToSuperClassName = new HashMap<String, String>(); @Override public MethodDescription map(MethodDescription methodDescription) { MethodDescription obfuscated = methodMappings.get(methodDescription); if (obfuscated == null) { obfuscated = parameterlessMethodMappings.get(methodDescription.getShortName()); if (methodDescription.isExact() || obfuscated == null) { Log.info("Failed to" + (obfuscated == null ? "" : " directly") + " map " + methodDescription + (obfuscated == null ? "" : ", would map to " + obfuscated)); obfuscated = methodDescription; obfuscated.obfuscateClasses(); } } return obfuscated; } @Override public MethodDescription rmap(MethodDescription methodDescription) { return methodMappings.inverse().get(methodDescription); } @Override public ClassDescription map(ClassDescription classDescription) { return classMappings.get(classDescription); } @Override public FieldDescription map(FieldDescription fieldDescription) { FieldDescription obfuscated = fieldMappings.get(fieldDescription); if (obfuscated == null) { String className; do { className = classNameToSuperClassName.get(fieldDescription.className); if (className != null) { Log.info(fieldDescription + " -> " + className); fieldDescription = new FieldDescription(className, fieldDescription.name); obfuscated = fieldMappings.get(fieldDescription); } } while (obfuscated == null && className != null); } return obfuscated; } public MCPMappings(File mcpDir) throws IOException { parse(mcpDir); } void parse(File mcpDir) throws IOException { loadCsv(new File(mcpDir, "methods.csv"), methodSeargeMappings); loadCsv(new File(mcpDir, "fields.csv"), fieldSeargeMappings); loadSrg(new File(mcpDir, "packaged.srg")); methodSeargeMappings.clear(); fieldSeargeMappings.clear(); } private void loadSrg(File mappingsSrg) throws IOException { Scanner srgScanner = new Scanner(mappingsSrg); while (srgScanner.hasNextLine()) { if (srgScanner.hasNext("CL:")) { srgScanner.next(); String fromClass = srgScanner.next().replace('/', '.'); String toClass = srgScanner.next().replace('/', '.'); ClassDescription obfuscatedClass = new ClassDescription(fromClass); ClassDescription deobfuscatedClass = new ClassDescription(toClass); classMappings.put(deobfuscatedClass, obfuscatedClass); File sourceLocation = new File(mappingsSrg.getParentFile().getParentFile(), "src/minecraft/" + (toClass.replace('.', '/') + ".java")); try { String contents = Files.toString(sourceLocation, Charset.forName("UTF-8")); Matcher extendsMatcher = extendsPattern.matcher(contents); if (extendsMatcher.find()) { String shortExtendsClassName = extendsMatcher.group(1); String extendsClassName = null; for (String line : Splitter.on('\n').trimResults().split(contents)) { if (line.endsWith('.' + shortExtendsClassName + ';')) { extendsClassName = line.substring(7, line.length() - 1); } } if (extendsClassName == null) { Matcher packageMatcher = packagePattern.matcher(contents); if (packageMatcher.find()) { extendsClassName = packageMatcher.group(1) + '.' + shortExtendsClassName; } } if (extendsClassName != null) { classNameToSuperClassName.put(toClass, extendsClassName); } } } catch (FileNotFoundException ignored) { } } else if (srgScanner.hasNext("FD:")) { srgScanner.next(); String obfuscatedMCPName = srgScanner.next(); String seargeName = srgScanner.next(); seargeName = seargeName.substring(seargeName.lastIndexOf('/') + 1); String deobfuscatedName = fieldSeargeMappings.get(seargeName); if (deobfuscatedName == null) { deobfuscatedName = seargeName; } FieldDescription obfuscatedField = new FieldDescription(obfuscatedMCPName); FieldDescription deobfuscatedField = new FieldDescription(classMappings.inverse().get(new ClassDescription(obfuscatedField.className)).name, deobfuscatedName); fieldMappings.put(deobfuscatedField, obfuscatedField); } else if (srgScanner.hasNext("MD:")) { srgScanner.next(); String obfuscatedName = srgScanner.next(); String obfuscatedTypeInfo = srgScanner.next(); String seargeName = srgScanner.next(); String deobfuscatedTypeInfo = srgScanner.next(); String obfuscatedClassName = obfuscatedName.substring(0, obfuscatedName.lastIndexOf('/')).replace('/', '.'); obfuscatedName = obfuscatedName.substring(obfuscatedName.lastIndexOf('/') + 1); String deobfuscatedClassName = seargeName.substring(0, seargeName.lastIndexOf('/')).replace('/', '.'); seargeName = seargeName.substring(seargeName.lastIndexOf('/') + 1); String deobfuscatedName = methodSeargeMappings.get(seargeName); if (deobfuscatedName == null) { deobfuscatedName = seargeName; } MethodDescription deobfuscatedMethodDescription = new MethodDescription(deobfuscatedClassName, deobfuscatedName, deobfuscatedTypeInfo); MethodDescription obfuscatedMethodDescription = new MethodDescription(obfuscatedClassName, obfuscatedName, obfuscatedTypeInfo); methodMappings.put(deobfuscatedMethodDescription, obfuscatedMethodDescription); parameterlessMethodMappings.put(deobfuscatedMethodDescription.getShortName(), obfuscatedMethodDescription); } else { srgScanner.nextLine(); } } } private static void loadCsv(File mappingsCsv, Map<String, String> seargeMappings) throws IOException { Scanner in = new Scanner(mappingsCsv); try { in.useDelimiter(","); while (in.hasNextLine()) { String seargeName = in.next(); String name = in.next(); String side = in.next(); in.nextLine(); if ("2".equals(side)) { // 2 = joined 'side'. seargeMappings.put(seargeName, name); } } } finally { in.close(); } } public Map<String, String> getSimpleClassNameMappings() { Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<ClassDescription, ClassDescription> entry : classMappings.entrySet()) { map.put(entry.getValue().name, entry.getKey().name); } return map; } }
package org.voovan.http.server; import org.voovan.http.server.context.HttpFilterConfig; import org.voovan.http.server.context.WebContext; import org.voovan.http.server.context.WebServerConfig; import org.voovan.http.server.exception.ResourceNotFound; import org.voovan.http.server.exception.RouterNotFound; import org.voovan.http.server.router.MimeFileRouter; import org.voovan.tools.*; import org.voovan.tools.log.Logger; import java.io.File; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.URLDecoder; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; public class HttpDispatcher { private static Map<String, String> REGEXED_ROUTER_CACHE = new ConcurrentHashMap<String, String>(); private static Map<String, List<Object>> ROUTER_INFO_CACHE = new ConcurrentHashMap<String, List<Object>>(); /** * [MainKey] = HTTP method ,[Value] = { [Value Key] = Route path, [Value value] = RouteBuiz } */ private Map<String, Map<String, HttpRouter>> methodRouters; private WebServerConfig webConfig; private SessionManager sessionManager; private MimeFileRouter mimeFileRouter; private String[] indexFiles; /** * * * @param webConfig Web * @param sessionManager Session */ public HttpDispatcher(WebServerConfig webConfig, SessionManager sessionManager) { REGEXED_ROUTER_CACHE.clear(); ROUTER_INFO_CACHE.clear(); methodRouters = new LinkedHashMap<String, Map<String, HttpRouter>>(); this.webConfig = webConfig; this.sessionManager = sessionManager; indexFiles = webConfig.getIndexFiles(); // HTTP this.addRouteMethod("GET"); this.addRouteMethod("POST"); this.addRouteMethod("HEAD"); this.addRouteMethod("PUT"); this.addRouteMethod("DELETE"); this.addRouteMethod("TRACE"); this.addRouteMethod("CONNECT"); this.addRouteMethod("OPTIONS"); // Mime mimeFileRouter = new MimeFileRouter(webConfig.getContextPath()); } /** * Http * @return */ public Map<String, Map<String, HttpRouter>> getRoutes(){ return methodRouters; } /** * ,:HTTP GETPOST * * @param method HTTP */ protected void addRouteMethod(String method) { if (!methodRouters.containsKey(method)) { Map<String,HttpRouter> routers = new TreeMap<String, HttpRouter>(new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length() > o2.length() && !o1.equals(o2)){ return -1; } else if(o1.length() < o2.length() &&!o1.equals(o2)){ return 1; } else if(o1.equals(o2)){ return 0; } else{ return 1; } } }); methodRouters.put(method, routers); } } /** * * @param routePath * @return */ public static String fixRoutePath(String routePath){ if(routePath.endsWith("/")){ routePath = TString.removeSuffix(routePath); } if(!routePath.startsWith("/")){ routePath = TString.assembly("/", routePath); } return TString.fastReplaceAll(routePath, "\\/{2,9}", "/"); } /** * * * @param method Http * @param routeRegexPath * @param router */ public void addRouteHandler(String method, String routeRegexPath, HttpRouter router) { if (methodRouters.keySet().contains(method)) { methodRouters.get(method).put(fixRoutePath(routeRegexPath), router); } } /** * * @param request HTTP * @return true: , false: */ public boolean isFrameWorkRequest(HttpRequest request){ return (request.protocol().getMethod().equals("ADMIN") || request.protocol().getMethod().equals("MONITOR")) && request.header().contain("AUTH-TOKEN"); } /** * Http , * * @param request HTTP * @param response HTTP */ public void process(HttpRequest request, HttpResponse response){ Chain<HttpFilterConfig> filterConfigs = webConfig.getFilterConfigs().clone(); Object filterResult = null; request.setSessionManager(sessionManager); if(!isFrameWorkRequest(request)) { //, Redirect filterResult = disposeFilter(filterConfigs, request, response); } // response , if(response.body().size()==0) { disposeRoute(request, response); } if(!isFrameWorkRequest(request)) { filterResult = disposeInvertedFilter(filterConfigs, request, response); } // HttpResponse Session Cookie if(request.sessionExists()){ HttpSession session = request.getSession(); session.attach(request, response); } WebContext.writeAccessLog(webConfig, request, response); } /** * * @param request request * @return true: , false: */ public boolean isStaticFile(HttpRequest request) { File staticFile = mimeFileRouter.getStaticFile(request); if(staticFile.exists() && staticFile.isFile()){ return true; } else { return false; } } /** * * @param request * @return { , [ , HttpRouter ] } */ public List<Object> findRouter(HttpRequest request){ String requestPath = request.protocol().getPath(); String requestMethod = request.protocol().getMethod(); String routerMark = requestPath+requestMethod; List<Object> routerInfo = ROUTER_INFO_CACHE.get(routerMark); if(routerInfo==null) { if(isStaticFile(request)){ routerInfo = TObject.asList(request.protocol().getPath(), mimeFileRouter); ROUTER_INFO_CACHE.put(routerMark, routerInfo); return routerInfo; } else { Map<String, HttpRouter> routers = methodRouters.get(requestMethod); for (Map.Entry<String, HttpRouter> routeEntry : routers.entrySet()) { String routePath = routeEntry.getKey(); if (matchPath(requestPath, routePath, webConfig.isMatchRouteIgnoreCase())) { //[ , HttpRouter ] routerInfo = TObject.asList(routePath, routeEntry.getValue()); ROUTER_INFO_CACHE.put(routerMark, routerInfo); return routerInfo; } } } } return routerInfo; } /** * Http * @param request Http * @param response Http */ public void disposeRoute(HttpRequest request, HttpResponse response){ String requestPath = request.protocol().getPath(); //[ , HttpRouter ] List<Object> routerInfo = findRouter(request); if (routerInfo!=null) { try { String routePath = (String)routerInfo.get(0); HttpRouter router = (HttpRouter)routerInfo.get(1); Map<String, String> pathVariables = fetchPathVariables(requestPath, routePath); if(pathVariables!=null) { request.getParameters().putAll(pathVariables); } router.process(request, response); } catch (Exception e) { if(e instanceof Throwable){ e = new Exception((Throwable)e); } exceptionMessage(request, response, e); } } else { if(!tryIndex(request,response)) { exceptionMessage(request, response, new RouterNotFound("Not avaliable router!")); } } } /** * * @param request Http * @param response Http * @return true, false */ public boolean tryIndex(HttpRequest request,HttpResponse response){ for (String indexFile : indexFiles) { String requestPath = request.protocol().getPath(); String filePath = webConfig.getContextPath() + requestPath.replace("/",File.separator) + (requestPath.endsWith("/") ? "" : File.separator) + indexFile; if(TFile.fileExists(filePath)){ try { String newRequestPath = requestPath + (requestPath.endsWith("/") ? "" : "/") + indexFile; request.protocol().setPath(newRequestPath); mimeFileRouter.process(request,response); } catch (Exception e) { exceptionMessage(request, response, e); } return true; } } return false; } /** * * @param routePath * @return */ public static String routePath2RegexPath(String routePath){ if(!REGEXED_ROUTER_CACHE.containsKey(routePath)) { String routeRegexPath = TString.fastReplaceAll(routePath, "\\*", ".*?"); routeRegexPath = TString.fastReplaceAll(routeRegexPath, "/", "\\/"); routeRegexPath = TString.fastReplaceAll(routeRegexPath, ":[^:?/]*", "[^:?/]*"); routeRegexPath = TString.assembly("^\\/?", routeRegexPath, "\\/?$"); REGEXED_ROUTER_CACHE.put(routePath, routeRegexPath); return routeRegexPath; } else { return REGEXED_ROUTER_CACHE.get(routePath); } } /** * * @param requestPath * @param routePath * @param matchRouteIgnoreCase * @return */ public static boolean matchPath(String requestPath, String routePath,boolean matchRouteIgnoreCase){ ///home/:name^[/]?/home/[/]?+ String routeRegexPath = routePath2RegexPath(routePath); if(matchRouteIgnoreCase){ requestPath = requestPath.toLowerCase(); routeRegexPath = routeRegexPath.toLowerCase(); } if(TString.regexMatch(requestPath, routeRegexPath) > 0 ){ return true; }else { return false; } } /** * ,/:test/:name /test/var1{name:var1} * @param requestPath * @param routePath * @return Map */ public static Map<String, String> fetchPathVariables(String requestPath,String routePath) { String compareRoutePath = routePath.endsWith("*") ? TString.removeSuffix(routePath) : routePath; compareRoutePath = compareRoutePath.endsWith("/") ? TString.removeSuffix(compareRoutePath) : compareRoutePath; String compareRequestPath = requestPath.endsWith("/") ? TString.removeSuffix(requestPath) : requestPath; if(compareRequestPath.equals(compareRoutePath)){ return null; } else { Map<String, String> resultMap = new LinkedHashMap<String, String>(); String routePathMathchRegex = routePath; try { String[] names = TString.searchByRegex(routePath, ":[^:?/]*"); if (names.length > 0) { for (int i = 0; i < names.length; i++) { names[i] = TString.removePrefix(names[i]); String name = names[i]; routePathMathchRegex = routePathMathchRegex.replace(":" + name, "(?<" + name + ">.*)"); } Matcher matcher = TString.doRegex(requestPath, routePathMathchRegex); for (String name : names) { resultMap.put(name, URLDecoder.decode(matcher.group(name), "UTF-8")); } } } catch (UnsupportedEncodingException e) { Logger.error("RoutePath URLDecoder.decode failed by charset: UTF-8", e); } return resultMap; } } /** * // * @param filterConfigs HTTP * @param request * @param response * @return */ public Object disposeFilter(Chain<HttpFilterConfig> filterConfigs, HttpRequest request, HttpResponse response) { filterConfigs.rewind(); Object filterResult = null; while(filterConfigs.hasNext()){ HttpFilterConfig filterConfig = filterConfigs.next(); HttpFilter httpFilter = filterConfig.getHttpFilterInstance(); if(httpFilter!=null) { filterResult = httpFilter.onRequest(filterConfig, request, response, filterResult); if(filterResult==null){ break; } } } return filterResult; } /** * * @param filterConfigs HTTP * @param request * @param response * @return */ public Object disposeInvertedFilter(Chain<HttpFilterConfig> filterConfigs, HttpRequest request, HttpResponse response) { filterConfigs.rewind(); Object filterResult = null; while(filterConfigs.hasPrevious()){ HttpFilterConfig filterConfig = filterConfigs.previous(); HttpFilter httpFilter = filterConfig.getHttpFilterInstance(); if(httpFilter!=null) { filterResult = httpFilter.onResponse(filterConfig, request, response, filterResult); if(filterResult==null){ break; } } } return filterResult; } /** * * * @param request * @param response * @param e */ public void exceptionMessage(HttpRequest request, HttpResponse response, Exception e) { Map<String, Object> errorDefine = WebContext.getErrorDefine(); String requestMethod = request.protocol().getMethod(); String requestPath = request.protocol().getPath(); String className = e.getClass().getName(); String errorMessage = e.toString().replace(TFile.getLineSeparator(), "<br/>"); String stackInfo = ""; if(!errorDefine.containsKey(className)) { Throwable throwable = e; do { stackInfo = TString.assembly(stackInfo, "\n\n", throwable.toString(), "\n", TEnv.getStackElementsMessage(throwable.getStackTrace())); throwable = throwable.getCause(); if (throwable == null) { break; } if (throwable instanceof InvocationTargetException) { throwable = throwable.getCause(); } } while (true); } // HTML stackInfo = TString.indent(stackInfo.trim(),1).replace("\n", "<br>"); response.header().put("Content-Type", "text/html"); // error , Map<String, Object> error = new HashMap<String, Object>(); if( !(e instanceof ResourceNotFound || e instanceof RouterNotFound) ){ response.protocol().setStatus(500); error.put("StatusCode", 500); Logger.error(e); }else{ response.protocol().setStatus(404); error.put("StatusCode", 404); } error.put("Page", "Error.html"); error.put("Description", stackInfo); // error , if (errorDefine.containsKey(className)) { error.putAll((Map<String,Object>)errorDefine.get(className)); response.protocol().setStatus((int)error.get("StatusCode")); } else if (errorDefine.get("Other") != null) { error.putAll((Map<String,Object>)errorDefine.get("Other")); response.protocol().setStatus((int)error.get("StatusCode")); } String errorPageContent = WebContext.getDefaultErrorPage(); if(TFile.fileExists(TFile.getSystemPath("/conf/error-page/" + error.get("Page")))) { try { errorPageContent = new String(TFile.loadFileFromContextPath("/conf/error-page/" + error.get("Page")),"UTF-8"); } catch (UnsupportedEncodingException e1) { Logger.error("This charset is unsupported",e); } } if(errorPageContent!=null){ errorPageContent = TString.oneTokenReplace(errorPageContent, "StatusCode", error.get("StatusCode").toString()); errorPageContent = TString.oneTokenReplace(errorPageContent, "RequestMethod", requestMethod); errorPageContent = TString.oneTokenReplace(errorPageContent, "RequestPath", requestPath); errorPageContent = TString.oneTokenReplace(errorPageContent, "ErrorMessage", errorMessage); errorPageContent = TString.oneTokenReplace(errorPageContent, "Description", error.get("Description").toString()); errorPageContent = TString.oneTokenReplace(errorPageContent, "Version", WebContext.getVERSION()); errorPageContent = TString.oneTokenReplace(errorPageContent, "DateTime", TDateTime.now()); response.clear(); response.write(errorPageContent); } } }
package org.cf.smalivm.opcode; import gnu.trove.list.TIntList; import gnu.trove.list.linked.TIntLinkedList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.cf.smalivm.MethodReflector; import org.cf.smalivm.SideEffect; import org.cf.smalivm.SmaliClassManager; import org.cf.smalivm.VirtualMachine; import org.cf.smalivm.context.ExecutionContext; import org.cf.smalivm.context.ExecutionGraph; import org.cf.smalivm.context.MethodState; import org.cf.smalivm.emulate.MethodEmulator; import org.cf.smalivm.type.LocalType; import org.cf.smalivm.type.TypeUtil; import org.cf.smalivm.type.UninitializedInstance; import org.cf.smalivm.type.UnknownValue; import org.cf.util.ImmutableUtils; import org.cf.util.SmaliClassUtils; import org.cf.util.Utils; import org.jf.dexlib2.iface.instruction.Instruction; import org.jf.dexlib2.iface.instruction.ReferenceInstruction; import org.jf.dexlib2.iface.instruction.formats.Instruction35c; import org.jf.dexlib2.iface.instruction.formats.Instruction3rc; import org.jf.dexlib2.iface.reference.MethodReference; import org.jf.dexlib2.util.ReferenceUtil; import org.jf.dexlib2.writer.builder.BuilderClassDef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InvokeOp extends ExecutionContextOp { static InvokeOp create(Instruction instruction, int address, VirtualMachine vm) { int childAddress = address + instruction.getCodeUnits(); String opName = instruction.getOpcode().name; MethodReference methodReference = (MethodReference) ((ReferenceInstruction) instruction).getReference(); String methodDescriptor = ReferenceUtil.getMethodDescriptor(methodReference); int[] registers = null; if (opName.contains("/range")) { Instruction3rc instr = (Instruction3rc) instruction; int registerCount = instr.getRegisterCount(); int start = instr.getStartRegister(); int end = start + registerCount; registers = new int[registerCount]; for (int i = start; i < end; i++) { registers[i - start] = i; } } else { Instruction35c instr = (Instruction35c) instruction; int registerCount = instr.getRegisterCount(); registers = new int[registerCount]; switch (registerCount) { case 5: registers[4] = instr.getRegisterG(); case 4: registers[3] = instr.getRegisterF(); case 3: registers[2] = instr.getRegisterE(); case 2: registers[1] = instr.getRegisterD(); case 1: registers[0] = instr.getRegisterC(); break; } } String returnType = methodReference.getReturnType(); List<String> parameterTypes; boolean isStatic = opName.contains("-static"); SmaliClassManager classManager = vm.getClassManager(); if (classManager.isLocalMethod(methodDescriptor)) { parameterTypes = classManager.getParameterTypes(methodDescriptor); } else { parameterTypes = Utils.getParameterTypes(methodDescriptor); if (!isStatic) { parameterTypes.add(0, methodReference.getDefiningClass()); } } int i = 0; TIntList parameterRegisters = new TIntLinkedList(parameterTypes.size()); for (String parameterType : parameterTypes) { parameterRegisters.add(registers[i]); i++; if (parameterType.equals("J") || parameterType.equals("D")) { i++; } } return new InvokeOp(address, opName, childAddress, methodDescriptor, returnType, parameterRegisters.toArray(), parameterTypes, vm, isStatic); } private static final Logger log = LoggerFactory.getLogger(InvokeOp.class.getSimpleName()); private final boolean isStatic; private final String methodDescriptor; private final int[] parameterRegisters; private final List<String> parameterTypes; private final String returnType; private SideEffect.Level sideEffectLevel; private final VirtualMachine vm; private InvokeOp(int address, String opName, int childAddress, String methodDescriptor, String returnType, int[] parameterRegisters, List<String> parameterTypes, VirtualMachine vm, boolean isStatic) { super(address, opName, childAddress); this.methodDescriptor = methodDescriptor; this.returnType = returnType; this.parameterRegisters = parameterRegisters; this.parameterTypes = parameterTypes; this.vm = vm; this.isStatic = isStatic; sideEffectLevel = SideEffect.Level.STRONG; } @Override public int[] execute(ExecutionContext ectx) { String targetMethod = methodDescriptor; if (getName().contains("-virtual")) { // -virtual/range // Method call might be to interface or abstract class. // Try and resolve what the actual virtual target is. int targetRegister = parameterRegisters[0]; Object value = ectx.getMethodState().peekRegister(targetRegister); targetMethod = getLocalTargetForVirtualMethod(value); } MethodState callerContext = ectx.getMethodState(); if (MethodReflector.canReflect(targetMethod) || MethodEmulator.canEmulate(targetMethod)) { MethodState calleeContext = buildNonLocalCalleeContext(callerContext); boolean allArgumentsKnown = allArgumentsKnown(calleeContext); if (allArgumentsKnown) { executeNonLocalMethod(targetMethod, callerContext, calleeContext); return getPossibleChildren(); } else { if (log.isTraceEnabled()) { log.trace("Not emulating / reflecting " + targetMethod + " because all args not known."); } assumeMaximumUnknown(callerContext); } } else { // This assumes if reflection fails, not worth it to try possibly cached framework classes. SmaliClassManager classManager = vm.getClassManager(); if (classManager.isLocalMethod(targetMethod)) { ExecutionContext calleeContext = buildLocalCalleeContext(targetMethod, ectx); if (classManager.methodHasImplementation(targetMethod)) { executeLocalMethod(targetMethod, ectx, calleeContext); } else { if (log.isWarnEnabled()) { log.warn("Attempting to execute local method without implementation: " + targetMethod + ". Assuming maxiumum ambiguity."); } assumeMaximumUnknown(callerContext); } } else { markCallerRegistersRead(callerContext); if (log.isDebugEnabled()) { log.debug("Unknown method: " + targetMethod + ". Assuming maximum ambiguity."); } assumeMaximumUnknown(callerContext); } } return getPossibleChildren(); } public int[] getParameterRegisters() { return parameterRegisters; } public String getReturnType() { return returnType; } @Override public SideEffect.Level sideEffectLevel() { return sideEffectLevel; } @Override public String toString() { StringBuilder sb = new StringBuilder(getName()); sb.append(" {"); if (getName().contains("/range")) { sb.append("r").append(parameterRegisters[0]).append(" .. r") .append(parameterRegisters[parameterRegisters.length - 1]); } else { if (parameterRegisters.length > 0) { for (int register : parameterRegisters) { sb.append("r").append(register).append(", "); } sb.setLength(sb.length() - 2); } } sb.append("}, ").append(methodDescriptor); return sb.toString(); } private boolean allArgumentsKnown(MethodState mState) { for (int parameterRegister = mState.getParameterStart(); parameterRegister < mState.getRegisterCount();) { Object value = mState.peekParameter(parameterRegister); if (value instanceof UnknownValue) { return false; } String type = TypeUtil.getValueType(value); parameterRegister += "J".equals(type) || "D".equals(type) ? 2 : 1; } return true; } private void markCallerRegistersRead(MethodState callerState) { for (int callerRegister : parameterRegisters) { callerState.readRegister(callerRegister); } } private void assignCalleeMethodStateParameters(MethodState callerState, MethodState calleeState) { int parameterRegister = calleeState.getParameterStart(); for (int i = 0; i < parameterRegisters.length; i++) { int callerRegister = parameterRegisters[i]; Object value = callerState.readRegister(callerRegister); calleeState.assignParameter(parameterRegister, value); String type = parameterTypes.get(i); parameterRegister += "J".equals(type) || "D".equals(type) ? 2 : 1; } } private void assumeMaximumUnknown(MethodState mState) { // TODO: add option to mark all class states unknown instead of just method state for (int i = 0; i < parameterTypes.size(); i++) { String type = parameterTypes.get(i); int register = parameterRegisters[i]; Object value = mState.peekRegister(register); if (null == value) { // Nulls don't mutate. continue; } boolean isInitializing = methodDescriptor.contains(";-><init>(") && (value instanceof UninitializedInstance); if (!isInitializing) { // May be immutable type, but if this is the initializer, internal state would be changing. if (ImmutableUtils.isImmutableClass(type)) { if (log.isTraceEnabled()) { log.trace(type + " (parameter) is immutable"); } continue; } String actualType = TypeUtil.getValueType(value); if (ImmutableUtils.isImmutableClass(actualType)) { // Parameter type might be "Ljava/lang/Object;" but actual type is "Ljava/lang/String"; if (log.isTraceEnabled()) { log.trace(type + " (actual) is immutable"); } continue; } } value = new UnknownValue(type); if (log.isDebugEnabled()) { log.debug(type + " is mutable and passed into unresolvable method execution, making Unknown"); } mState.pokeRegister(register, value); } if (!"V".equals(returnType)) { Object value = new UnknownValue(returnType); mState.assignResultRegister(value); } } private ExecutionContext buildLocalCalleeContext(String methodDescriptor, ExecutionContext callerContext) { ExecutionContext calleeContext = vm.getRootExecutionContext(methodDescriptor); calleeContext.setCallDepth(callerContext.getCallDepth() + 1); MethodState callerMethodState = callerContext.getMethodState(); MethodState calleeMethodState = calleeContext.getMethodState(); assignCalleeMethodStateParameters(callerMethodState, calleeMethodState); // Class state merging is handled by the VM. return calleeContext; } private MethodState buildNonLocalCalleeContext(MethodState callerMethodState) { ExecutionContext ectx = new ExecutionContext(vm); int parameterSize = Utils.getRegisterSize(parameterTypes); int registerCount = parameterSize; MethodState calleeMethodState = new MethodState(ectx, registerCount, parameterTypes.size(), parameterSize); assignCalleeMethodStateParameters(callerMethodState, calleeMethodState); return calleeMethodState; } private void executeLocalMethod(String methodDescriptor, ExecutionContext callerContext, ExecutionContext calleeContext) { ExecutionGraph graph = vm.execute(methodDescriptor, calleeContext, callerContext, parameterRegisters); if (graph == null) { // Problem executing the method. Maybe node visits or call depth exceeded? log.info("Problem executing " + methodDescriptor + ", propagating ambiguity."); assumeMaximumUnknown(callerContext.getMethodState()); return; } if (!returnType.equals("V")) { Object consensus = graph.getTerminatingRegisterConsensus(MethodState.ReturnRegister); callerContext.getMethodState().assignResultRegister(consensus); } sideEffectLevel = graph.getHighestSideEffectLevel(); } private void executeNonLocalMethod(String methodDescriptor, MethodState callerContext, MethodState calleeContext) { assert allArgumentsKnown(calleeContext); if (MethodEmulator.canEmulate(methodDescriptor)) { sideEffectLevel = MethodEmulator.emulate(vm, calleeContext, methodDescriptor, getParameterRegisters()); } else if (MethodReflector.canReflect(methodDescriptor)) { MethodReflector reflector = new MethodReflector(methodDescriptor, returnType, parameterTypes, isStatic); reflector.reflect(calleeContext); // playa play // Only safe, non-side-effect methods are allowed to be reflected. sideEffectLevel = SideEffect.Level.NONE; } if (!isStatic) { // Handle updating the instance reference Object originalInstance = callerContext.peekRegister(parameterRegisters[0]); Object newInstance = calleeContext.peekParameter(0); if (originalInstance != newInstance) { // Instance went from UninitializedInstance class to something else. // TODO: add test for this! callerContext.assignRegisterAndUpdateIdentities(parameterRegisters[0], newInstance); } else { // The instance reference could have changed, so mark it as assigned here. callerContext.assignRegister(parameterRegisters[0], newInstance); } } if (!"V".equals(returnType)) { Object returnValue = calleeContext.readReturnRegister(); callerContext.assignResultRegister(returnValue); } } private String getLocalTargetForVirtualMethod(Object value) { String actualType; if (value instanceof LocalType) { actualType = ((LocalType) value).getName(); } else { actualType = SmaliClassUtils.javaClassToSmali(value.getClass().getName()); } if (SmaliClassUtils.isPrimitiveType(actualType)) { actualType = SmaliClassUtils.smaliPrimitiveToJavaWrapper(actualType); } String methodSignature = methodDescriptor.split("->")[1]; SmaliClassManager classManager = vm.getClassManager(); String targetMethod = getLocalTargetForVirtualMethod(actualType, methodSignature, classManager, new HashSet<String>()); return targetMethod != null ? targetMethod : methodDescriptor; } private static boolean doesNonLocalMethodExist(String className, String methodSignature) { Class<?> klazz = null; try { klazz = Class.forName(SmaliClassUtils.smaliClassToJava(className)); } catch (ClassNotFoundException e) { return false; } StringBuilder sb = new StringBuilder(className); sb.append("->").append(methodSignature); List<String> paramList = Utils.getParameterTypes(sb.toString()); Class<?>[] params = new Class<?>[paramList.size()]; for (int i = 0; i < paramList.size(); i++) { String paramName = paramList.get(i); try { if (SmaliClassUtils.isPrimitiveType(paramName)) { params[i] = SmaliClassUtils.getPrimitiveType(SmaliClassUtils.smaliClassToJava(paramName)); } else { params[i] = Class.forName(SmaliClassUtils.smaliClassToJava(paramName)); } } catch (ClassNotFoundException e) { return false; } } String methodName = methodSignature.split("\\(")[0]; try { klazz.getMethod(methodName, params); } catch (NoSuchMethodException e) { return false; } catch (SecurityException e) { return false; } return true; } private String getLocalTargetForVirtualMethod(String className, String methodSignature, SmaliClassManager classManager, Set<String> visited) { visited.add(className); StringBuilder sb = new StringBuilder(className); sb.append("->").append(methodSignature); String methodDescriptor = sb.toString(); boolean isLocalMethod = classManager.isLocalMethod(methodDescriptor); if ((isLocalMethod && classManager.methodHasImplementation(methodDescriptor))) { return methodDescriptor; } if (MethodReflector.isSafe(methodDescriptor) && doesNonLocalMethodExist(className, methodSignature)) { return methodDescriptor; } if (!classManager.isLocalClass(className)) { // Can't trace any further up. // Note, also checked if this is white-listed Java API return null; } BuilderClassDef classDef = classManager.getClass(className); Set<String> parents = new HashSet<String>(); parents.addAll(classDef.getInterfaces()); if (null != classDef.getSuperclass()) { parents.add(classDef.getSuperclass()); } for (String parent : parents) { if (visited.contains(parent)) { continue; } String target = getLocalTargetForVirtualMethod(parent, methodSignature, classManager, visited); if (null != target) { return target; } } return null; } }
package gov.nih.nci.gss.api; import gov.nih.nci.gss.domain.DataService; import gov.nih.nci.gss.domain.DataServiceGroup; import gov.nih.nci.gss.domain.DomainClass; import gov.nih.nci.gss.domain.DomainModel; import gov.nih.nci.gss.domain.GridService; import gov.nih.nci.gss.domain.HostingCenter; import gov.nih.nci.gss.domain.PointOfContact; import gov.nih.nci.gss.domain.StatusChange; import gov.nih.nci.gss.util.Cab2bTranslator; import gov.nih.nci.gss.util.NamingUtil; import gov.nih.nci.gss.util.StringUtil; import gov.nih.nci.system.applicationservice.ApplicationException; import gov.nih.nci.system.dao.orm.ORMDAOImpl; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.FileCopyUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Custom JSON API for returning service metadata in bulk and querying services * via caB2B. * * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class JSONDataService extends HttpServlet { private static Logger log = Logger.getLogger(JSONDataService.class); // TODO: externalize this private static final String HOST_KEY = "Hosting Institution"; private enum Verb { GET, POST }; private enum QueryStatus { RUNNING, EXPIRED, UNKNOWN, FOUND }; /** Date format for serializing dates into JSON. * Must match the data format used by the iPhone client */ private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); private static final String GET_SERVICE_HQL_SELECT = "select service from gov.nih.nci.gss.domain.GridService service "; private static final String GET_SERVICE_HQL_JOIN_STATUS = "left join fetch service.statusHistory status "; private static final String GET_SERVICE_HQL_WHERE_STATUS = "where ((status.changeDate is null) or (status.changeDate = (" + " select max(changeDate) " + " from gov.nih.nci.gss.domain.StatusChange s " + " where s.gridService = service " + "))) "; private static final String GET_HOST_HQL_SELECT = "select host from gov.nih.nci.gss.domain.HostingCenter host "; /** JSON string describing the usage of this service */ private String usage; /** Hibernate session factory */ private SessionFactory sessionFactory; /** Service that manages background queries and results */ private QueryService queryService; private NamingUtil namingUtil; @Override public void init() throws ServletException { try { WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); this.sessionFactory = ((ORMDAOImpl)ctx.getBean("ORMDAO")).getHibernateTemplate().getSessionFactory(); this.queryService = new QueryService(sessionFactory); this.usage = FileCopyUtils.copyToString(new InputStreamReader( JSONDataService.class.getResourceAsStream("/rest_api_usage.js"))); this.namingUtil = new NamingUtil(sessionFactory); } catch (Exception e) { throw new ServletException(e); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.GET, request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.POST, request, response); } @Override public void destroy() { queryService.close(); super.destroy(); } /** * * @param verb * @param request * @param response * @throws ServletException * @throws IOException */ private void doREST(Verb verb, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { response.setContentType("application/json"); String path = request.getPathInfo(); if (path == null) { pw.print(getJSONUsage()); } else { String[] pathList = path.split("/"); if (pathList.length < 2) { pw.print(getJSONUsage()); } else { String noun = pathList[1]; pw.print(getRESTResponse(verb, noun, pathList, request)); } } } catch (Exception e) { log.error("JSON service error",e); pw.print(getJSONError(e.getClass().getName(), e.getMessage())); } finally { pw.close(); } } /** * Process a REST request for a given noun. * @param noun * @param pathList * @param request * @return */ private String getRESTResponse(Verb verb, String noun, String[] pathList, HttpServletRequest request) throws Exception { if ("service".equals(noun)) { // Return details about services, or a single service String id = null; if (pathList.length > 2) { id = pathList[2]; } boolean includeMetadata = "1".equals(request.getParameter("metadata")); boolean includeModel = "1".equals(request.getParameter("model")); return getServiceJSON(id, includeMetadata, includeModel); } if ("host".equals(noun)) { // Return details about hosts, or a single hosts String id = null; if (pathList.length > 2) { id = pathList[2]; } return getHostJSON(id); } else if ("runQuery".equals(noun)) { // Query grid services using caB2B String clientId = request.getParameter("clientId"); String searchString = request.getParameter("searchString"); String serviceGroup = request.getParameter("serviceGroup"); String serviceIdConcat = request.getParameter("serviceIds"); String[] serviceIds = request.getParameterValues("serviceId"); String[] serviceUrls = request.getParameterValues("serviceUrl"); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(searchString)) { return getJSONError("UsageError", "Specify a searchString to search on."); } if (serviceIds.length == 0) { serviceIds = serviceIdConcat.split(","); } List<String> serviceUrlList = new ArrayList<String>(); for(String serviceUrl : serviceUrls) { serviceUrlList.add(serviceUrl); } if (serviceIds.length > 0) { Session s = sessionFactory.openSession(); for(String serviceId : serviceIds) { String hql = GET_SERVICE_HQL_SELECT+" where service.id = ?"; List<GridService> services = s.createQuery(hql).setString(0, serviceId).list(); if (services.isEmpty()) { return getJSONError("UsageError", "Unknown service id: "+serviceId); } if (services.size() > 1) { log.error("More than one matching service for service id: "+serviceId); } serviceUrlList.add(services.get(0).getUrl()); } s.close(); } QueryParams queryParams = null; if (!serviceUrlList.isEmpty()) { queryParams = new QueryParams(clientId, searchString, null, serviceUrlList); } else if (!StringUtil.isEmpty(serviceGroup)) { if (serviceGroup == null) { return getJSONError("UsageError", "Unrecognized serviceGroup '"+serviceGroup+"'"); } queryParams = new QueryParams(clientId, searchString, serviceGroup, null); } else { return getJSONError("UsageError", "Specify serviceGroup or serviceId or serviceUrl."); } Cab2bQuery query = queryService.executeQuery(queryParams); log.info("Executing "+queryParams+" as job " +query.getJobId()); JSONObject jsonObj = new JSONObject(); jsonObj.put("status", QueryStatus.RUNNING); jsonObj.put("job_id", query.getJobId()); return jsonObj.toString(); } else if ("query".equals(noun)) { String clientId = request.getParameter("clientId"); String jobId = request.getParameter("jobId"); boolean collapse = "1".equals(request.getParameter("collapse")); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(jobId)) { return getJSONError("UsageError", "Specify a jobId."); } Cab2bQuery query = queryService.retrieveQuery(jobId); if (query == null) { return getJSONStatus(QueryStatus.UNKNOWN); } if (!query.getQueryParams().getClientId().equals(clientId)) { return getJSONStatus(QueryStatus.UNKNOWN); } log.info("Got query "+jobId+": "+query.getQueryParams()); // What if the query isn't completed? if (!query.isDone()) { // Return nothing and let the client poll if ("1".equals(request.getParameter("async"))) { log.info("Returning asyncronously for query: "+jobId); return getJSONStatus(QueryStatus.RUNNING); } // Block until the query is completed synchronized (query) { try { log.info("Blocking until query is complete: "+jobId); query.wait(); } catch (InterruptedException e) { log.error("Interrupted wait",e); } } } return getQueryResultsJSON(query,collapse); } // If the noun was good we would've returned by now return getJSONError("UsageError", "Unrecognized noun '"+noun+"'"); } /** * Returns a JSON object representing the basic attributes of a service. * @param service * @return * @throws JSONException */ private JSONObject getJSONObjectForService(GridService service) throws JSONException { JSONObject jsonService = new JSONObject(); jsonService.put("id", service.getId().toString()); jsonService.put("name", service.getName()); jsonService.put("version", service.getVersion()); jsonService.put("class", service.getClass().getSimpleName()); // TODO: move this into the scheduled job jsonService.put("simple_name", namingUtil.getSimpleName(service.getName())); //jsonService.put("simple_name", service.getSimpleName()); jsonService.put("url", service.getUrl()); HostingCenter host = service.getHostingCenter(); if (host != null) { jsonService.put("host_id", host.getId().toString()); jsonService.put("host_short_name", host.getShortName()); } if (service instanceof DataService) { DataService dataService = (DataService)service; DataServiceGroup group = dataService.getGroup(); if (group != null) jsonService.put("group", group.getName()); if (dataService.getSearchDefault()) { jsonService.put("search_default", "true"); } } Collection<StatusChange> scs = service.getStatusHistory(); if (scs.size() > 1) { log.warn("More than 1 status change was returned for service with id="+service.getId()); } if (!scs.isEmpty()) { StatusChange statusChange = scs.iterator().next(); jsonService.put("status", statusChange.getNewStatus()); jsonService.put("last_update", df.format(statusChange.getChangeDate())); jsonService.put("publish_date", df.format(service.getPublishDate())); } return jsonService; } /** * Returns a JSON string with all the metadata about a particular service. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getServiceJSON(String serviceId, boolean includeMetadata, boolean includeModel) throws JSONException, ApplicationException { Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Create the HQL query StringBuffer hql = new StringBuffer(GET_SERVICE_HQL_SELECT); hql.append(GET_SERVICE_HQL_JOIN_STATUS); hql.append("left join fetch service.hostingCenter "); if (includeModel) hql.append("left join fetch service.domainModel "); hql.append(GET_SERVICE_HQL_WHERE_STATUS); if (serviceId != null) hql.append("and service.id = ?"); // Create the Hibernate Query Query q = s.createQuery(hql.toString()); if (serviceId != null) q.setString(0, serviceId); // Execute the query List<GridService> services = q.list(); JSONArray jsonArray = new JSONArray(); json.put("services", jsonArray); for (GridService service : services) { JSONObject jsonService = getJSONObjectForService(service); jsonArray.put(jsonService); // service host short name if (includeMetadata) { // service details jsonService.put("description", service.getDescription()); // service pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : service.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } jsonService.put("pocs", jsonPocs); // service host details HostingCenter host = service.getHostingCenter(); JSONObject hostObj = new JSONObject(); jsonService.put("hosting_center", hostObj); if (host != null) { hostObj.put("short_name", host.getShortName()); hostObj.put("long_name", host.getLongName()); hostObj.put("country_code", host.getCountryCode()); hostObj.put("state_province", host.getStateProvince()); hostObj.put("locality", host.getLocality()); hostObj.put("postal_code", host.getPostalCode()); hostObj.put("street", host.getStreet()); // service host pocs jsonPocs = new JSONArray(); for (PointOfContact poc : host.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } hostObj.put("pocs", jsonPocs); } } if (includeModel && (service instanceof DataService)) { DomainModel model = ((DataService)service).getDomainModel(); JSONObject modelObj = new JSONObject(); jsonService.put("domain_model", modelObj); if (model != null) { // domain model modelObj.put("long_name", model.getLongName()); modelObj.put("version", model.getVersion()); modelObj.put("description", model.getDescription()); // model classes JSONArray jsonClasses = new JSONArray(); for (DomainClass dc : model.getClasses()) { JSONObject jsonClass = new JSONObject(); jsonClass.put("name", dc.getClassName()); jsonClass.put("package", dc.getDomainPackage()); jsonClass.put("description", dc.getDescription()); jsonClasses.put(jsonClass); } modelObj.put("classes", jsonClasses); } } } } finally { s.close(); } return json.toString(); } /** * Returns a JSON string with all the metadata about a particular host. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getHostJSON(String hostId) throws JSONException, ApplicationException { Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Create the HQL query StringBuffer hql = new StringBuffer(GET_HOST_HQL_SELECT); if (hostId != null) hql.append("where host.id = ?"); // Create the Hibernate Query Query q = s.createQuery(hql.toString()); if (hostId != null) q.setString(0, hostId); // Execute the query List<HostingCenter> hosts = q.list(); JSONArray jsonArray = new JSONArray(); json.put("hosts", jsonArray); for (HostingCenter host : hosts) { JSONObject hostObj = new JSONObject(); jsonArray.put(hostObj); // service host details hostObj.put("id", host.getId().toString()); hostObj.put("short_name", host.getShortName()); hostObj.put("long_name", host.getLongName()); hostObj.put("country_code", host.getCountryCode()); hostObj.put("state_province", host.getStateProvince()); hostObj.put("locality", host.getLocality()); hostObj.put("postal_code", host.getPostalCode()); hostObj.put("street", host.getStreet()); // service host pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : host.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } hostObj.put("pocs", jsonPocs); } } finally { s.close(); } return json.toString(); } private String getQueryResultsJSON(Cab2bQuery query, boolean collapse) throws JSONException { if (!query.isDone()) { throw new IllegalStateException("Query has not completed: "+query); } Exception e = query.getException(); if (e != null) { return getJSONError(e.getClass().getName(), e.getMessage()); } JSONObject json = new JSONObject(query.getResultJson()); if (json.has("error")) { return query.getResultJson(); } Cab2bTranslator translator = queryService.getCab2b().getCab2bTranslator(); String modelGroupName = json.getString("modelGroupName"); String serviceGroup = translator.getServiceGroupForModelGroup(modelGroupName); if (modelGroupName != null) { json.remove("modelGroupName"); json.put("serviceGroup", serviceGroup); } if (collapse) { Map<String,Map<String,JSONObject>> servers = new LinkedHashMap<String,Map<String,JSONObject>>(); // the key to discriminate on for duplicates String primaryKey = translator.getPrimaryKeyForServiceGroup(serviceGroup); JSONObject queries = json.getJSONObject("results"); for(Iterator i = queries.keys(); i.hasNext(); ) { String queryName = (String)i.next(); JSONObject urls = queries.getJSONObject(queryName); for(Iterator j = urls.keys(); j.hasNext(); ) { String url = (String)j.next(); JSONArray objs = urls.getJSONArray(url); Map<String,JSONObject> serverUnique = servers.get(url); if (serverUnique == null) { serverUnique = new LinkedHashMap<String,JSONObject>(); servers.put(url, serverUnique); } for(int k=0; k<objs.length(); k++) { JSONObject obj = objs.getJSONObject(k); String key = null; try { key = obj.getString(primaryKey); } catch (JSONException x) { log.error("Error getting unique key",x); key = obj.toString(); } if (!serverUnique.containsKey(key)) { serverUnique.put(key, obj); } } } } JSONObject jsonUrls = new JSONObject(); for(String url : servers.keySet()) { JSONArray jsonObjs = new JSONArray(); jsonUrls.put(url, jsonObjs); for (JSONObject obj : servers.get(url).values()) { jsonObjs.put(obj); } } json.put("results", jsonUrls); } return json.toString(); } /** * Returns a JSON string with the given error message. * @return JSON-formatted String */ private String getJSONError(String exception, String message) { return "{\"error\":"+JSONObject.quote(exception)+ ",\"message\":"+JSONObject.quote(message)+"}"; } /** * Get a JSON string with a simple query status message. * @param status * @return * @throws JSONException */ private String getJSONStatus(Object status) throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put("status", status); return jsonObj.toString(); } /** * Returns a JSON string with usage instructions, or an error if a problem * occurs. * @return JSON-formatted String */ private String getJSONUsage() { return usage; } }
package gov.nih.nci.gss.api; import gov.nih.nci.gss.domain.DataService; import gov.nih.nci.gss.domain.DataServiceGroup; import gov.nih.nci.gss.domain.DomainClass; import gov.nih.nci.gss.domain.DomainModel; import gov.nih.nci.gss.domain.GridService; import gov.nih.nci.gss.domain.HostingCenter; import gov.nih.nci.gss.domain.PointOfContact; import gov.nih.nci.gss.domain.StatusChange; import gov.nih.nci.gss.util.Cab2bTranslator; import gov.nih.nci.gss.util.NamingUtil; import gov.nih.nci.gss.util.StringUtil; import gov.nih.nci.system.applicationservice.ApplicationException; import gov.nih.nci.system.dao.orm.ORMDAOImpl; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.FileCopyUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Custom JSON API for returning service metadata in bulk and querying services * via caB2B. * * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class JSONDataService extends HttpServlet { private static Logger log = Logger.getLogger(JSONDataService.class); // TODO: externalize this private static final String HOST_KEY = "Hosting Institution"; private enum Verb { GET, POST }; private enum QueryStatus { RUNNING, EXPIRED, UNKNOWN, FOUND }; /** Date format for serializing dates into JSON. * Must match the data format used by the iPhone client */ private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); private static final String GET_SERVICE_HQL_SELECT = "select service from gov.nih.nci.gss.domain.GridService service "; private static final String GET_SERVICE_HQL_JOIN_STATUS = "left join fetch service.statusHistory status "; private static final String GET_SERVICE_HQL_WHERE_STATUS = "where ((status.changeDate is null) or (status.changeDate = (" + " select max(changeDate) " + " from gov.nih.nci.gss.domain.StatusChange s " + " where s.gridService = service " + "))) "; private static final String GET_HOST_HQL_SELECT = "select host from gov.nih.nci.gss.domain.HostingCenter host "; /** JSON string describing the usage of this service */ private String usage; /** Hibernate session factory */ private SessionFactory sessionFactory; /** Service that manages background queries and results */ private QueryService queryService; private NamingUtil namingUtil; @Override public void init() throws ServletException { try { WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); this.sessionFactory = ((ORMDAOImpl)ctx.getBean("ORMDAO")).getHibernateTemplate().getSessionFactory(); this.queryService = new QueryService(sessionFactory); this.usage = FileCopyUtils.copyToString(new InputStreamReader( JSONDataService.class.getResourceAsStream("/rest_api_usage.js"))); this.namingUtil = new NamingUtil(sessionFactory); } catch (Exception e) { throw new ServletException(e); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.GET, request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doREST(Verb.POST, request, response); } @Override public void destroy() { queryService.close(); super.destroy(); } /** * * @param verb * @param request * @param response * @throws ServletException * @throws IOException */ private void doREST(Verb verb, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { response.setContentType("application/json"); String path = request.getPathInfo(); if (path == null) { pw.print(getJSONUsage()); } else { String[] pathList = path.split("/"); if (pathList.length < 2) { pw.print(getJSONUsage()); } else { String noun = pathList[1]; pw.print(getRESTResponse(verb, noun, pathList, request)); } } } catch (Exception e) { log.error("JSON service error",e); pw.print(getJSONError(e.getClass().getName(), e.getMessage())); } finally { pw.close(); } } /** * Process a REST request for a given noun. * @param noun * @param pathList * @param request * @return */ private String getRESTResponse(Verb verb, String noun, String[] pathList, HttpServletRequest request) throws Exception { if (verb != Verb.GET) { return getJSONError("MethodError", "Only the GET method is supported."); } if ("service".equals(noun)) { // Return details about services, or a single service String id = null; if (pathList.length > 2) { id = pathList[2]; } boolean includeMetadata = "1".equals(request.getParameter("metadata")); boolean includeModel = "1".equals(request.getParameter("model")); return getServiceJSON(id, includeMetadata, includeModel); } if ("host".equals(noun)) { // Return details about hosts, or a single hosts String id = null; if (pathList.length > 2) { id = pathList[2]; } return getHostJSON(id); } else if ("runQuery".equals(noun)) { // Query grid services using caB2B String clientId = request.getParameter("clientId"); String searchString = request.getParameter("searchString"); String serviceGroup = request.getParameter("serviceGroup"); String serviceId = request.getParameter("serviceId"); String serviceUrl = request.getParameter("serviceUrl"); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(searchString)) { return getJSONError("UsageError", "Specify a searchString to search on."); } QueryParams queryParams = null; if (!StringUtil.isEmpty(serviceUrl)) { queryParams = new QueryParams(clientId, searchString, null, serviceUrl); } else if (!StringUtil.isEmpty(serviceId)) { Session s = sessionFactory.openSession(); String hql = GET_SERVICE_HQL_SELECT+" where service.id = ?"; List<GridService> services = s.createQuery(hql).setString(0, serviceId).list(); if (services.isEmpty()) { return getJSONError("UsageError", "Unknown service id: "+serviceId); } if (services.size() > 1) { log.error("More than one matching service for service id: "+serviceId); } queryParams = new QueryParams(clientId, searchString, null, services.get(0).getUrl()); } else if (!StringUtil.isEmpty(serviceGroup)) { if (serviceGroup == null) { return getJSONError("UsageError", "Unrecognized serviceGroup '"+serviceGroup+"'"); } queryParams = new QueryParams(clientId, searchString, serviceGroup, null); } else { return getJSONError("UsageError", "Specify serviceGroup or serviceId or serviceUrl."); } Cab2bQuery query = queryService.executeQuery(queryParams); log.info("Executing "+queryParams+" as job " +query.getJobId()); JSONObject jsonObj = new JSONObject(); jsonObj.put("status", QueryStatus.RUNNING); jsonObj.put("job_id", query.getJobId()); return jsonObj.toString(); } else if ("query".equals(noun)) { String clientId = request.getParameter("clientId"); String jobId = request.getParameter("jobId"); boolean collapse = "1".equals(request.getParameter("collapse")); if (StringUtil.isEmpty(clientId)) { return getJSONError("UsageError", "Specify your clientId."); } if (StringUtil.isEmpty(jobId)) { return getJSONError("UsageError", "Specify a jobId."); } Cab2bQuery query = queryService.retrieveQuery(jobId); if (query == null) { return getJSONStatus(QueryStatus.UNKNOWN); } if (!query.getQueryParams().getClientId().equals(clientId)) { return getJSONStatus(QueryStatus.UNKNOWN); } log.info("Got query "+jobId+": "+query.getQueryParams()); // What if the query isn't completed? if (!query.isDone()) { // Return nothing and let the client poll if ("1".equals(request.getParameter("async"))) { log.info("Returning asyncronously for query: "+jobId); return getJSONStatus(QueryStatus.RUNNING); } // Block until the query is completed synchronized (query) { try { log.info("Blocking until query is complete: "+jobId); query.wait(); } catch (InterruptedException e) { log.error("Interrupted wait",e); } } } return getQueryResultsJSON(query,collapse); } // If the noun was good we would've returned by now return getJSONError("UsageError", "Unrecognized noun '"+noun+"'"); } /** * Returns a JSON object representing the basic attributes of a service. * @param service * @return * @throws JSONException */ private JSONObject getJSONObjectForService(GridService service) throws JSONException { JSONObject jsonService = new JSONObject(); jsonService.put("id", service.getId()); jsonService.put("name", service.getName()); jsonService.put("version", service.getVersion()); jsonService.put("class", service.getClass().getSimpleName()); // TODO: move this into the scheduled job jsonService.put("simple_name", namingUtil.getSimpleName(service.getName())); //jsonService.put("simple_name", service.getSimpleName()); jsonService.put("url", service.getUrl()); HostingCenter host = service.getHostingCenter(); if (host != null) { jsonService.put("host_id", host.getId()); jsonService.put("host_short_name", host.getShortName()); } if (service instanceof DataService) { DataService dataService = (DataService)service; DataServiceGroup group = dataService.getGroup(); if (group != null) jsonService.put("group", group.getName()); } Collection<StatusChange> scs = service.getStatusHistory(); if (scs.size() > 1) { log.warn("More than 1 status change was returned for service with id="+service.getId()); } if (!scs.isEmpty()) { StatusChange statusChange = scs.iterator().next(); jsonService.put("status", statusChange.getNewStatus()); jsonService.put("last_update", df.format(statusChange.getChangeDate())); jsonService.put("publish_date", df.format(service.getPublishDate())); } return jsonService; } /** * Returns a JSON string with all the metadata about a particular service. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getServiceJSON(String serviceId, boolean includeMetadata, boolean includeModel) throws JSONException, ApplicationException { Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Create the HQL query StringBuffer hql = new StringBuffer(GET_SERVICE_HQL_SELECT); hql.append(GET_SERVICE_HQL_JOIN_STATUS); hql.append("left join fetch service.hostingCenter "); if (includeModel) hql.append("left join fetch service.domainModel "); hql.append(GET_SERVICE_HQL_WHERE_STATUS); if (serviceId != null) hql.append("and service.id = ?"); // Create the Hibernate Query Query q = s.createQuery(hql.toString()); if (serviceId != null) q.setString(0, serviceId); // Execute the query List<GridService> services = q.list(); JSONArray jsonArray = new JSONArray(); json.put("services", jsonArray); for (GridService service : services) { JSONObject jsonService = getJSONObjectForService(service); jsonArray.put(jsonService); // service host short name if (includeMetadata) { // service details jsonService.put("description", service.getDescription()); // service pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : service.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } jsonService.put("pocs", jsonPocs); // service host details HostingCenter host = service.getHostingCenter(); JSONObject hostObj = new JSONObject(); jsonService.put("hosting_center", hostObj); if (host != null) { hostObj.put("long_name", host.getLongName()); hostObj.put("country_code", host.getCountryCode()); hostObj.put("state_province", host.getStateProvince()); hostObj.put("locality", host.getLocality()); hostObj.put("postal_code", host.getPostalCode()); hostObj.put("street", host.getStreet()); // service host pocs jsonPocs = new JSONArray(); for (PointOfContact poc : host.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } hostObj.put("pocs", jsonPocs); } } if (includeModel && (service instanceof DataService)) { DomainModel model = ((DataService)service).getDomainModel(); JSONObject modelObj = new JSONObject(); jsonService.put("domain_model", modelObj); if (model != null) { // domain model modelObj.put("long_name", model.getLongName()); modelObj.put("version", model.getVersion()); modelObj.put("description", model.getDescription()); // model classes JSONArray jsonClasses = new JSONArray(); for (DomainClass dc : model.getClasses()) { JSONObject jsonClass = new JSONObject(); jsonClass.put("name", dc.getClassName()); jsonClass.put("package", dc.getDomainPackage()); jsonClass.put("description", dc.getDescription()); jsonClasses.put(jsonClass); } modelObj.put("classes", jsonClasses); } } } } finally { s.close(); } return json.toString(); } /** * Returns a JSON string with all the metadata about a particular host. * @return JSON-formatted String * @throws JSONException * @throws ApplicationException */ private String getHostJSON(String hostId) throws JSONException, ApplicationException { Session s = sessionFactory.openSession(); JSONObject json = new JSONObject(); try { // Create the HQL query StringBuffer hql = new StringBuffer(GET_HOST_HQL_SELECT); if (hostId != null) hql.append("where host.id = ?"); // Create the Hibernate Query Query q = s.createQuery(hql.toString()); if (hostId != null) q.setString(0, hostId); // Execute the query List<HostingCenter> hosts = q.list(); JSONArray jsonArray = new JSONArray(); json.put("hosts", jsonArray); for (HostingCenter host : hosts) { JSONObject hostObj = new JSONObject(); jsonArray.put(hostObj); // service host details hostObj.put("id", host.getId()); hostObj.put("short_name", host.getShortName()); hostObj.put("long_name", host.getLongName()); hostObj.put("country_code", host.getCountryCode()); hostObj.put("state_province", host.getStateProvince()); hostObj.put("locality", host.getLocality()); hostObj.put("postal_code", host.getPostalCode()); hostObj.put("street", host.getStreet()); // service host pocs JSONArray jsonPocs = new JSONArray(); for (PointOfContact poc : host.getPointOfContacts()) { JSONObject jsonPoc = new JSONObject(); jsonPoc.put("name", poc.getName()); jsonPoc.put("role", poc.getRole()); jsonPoc.put("affiliation", poc.getAffiliation()); jsonPoc.put("email", poc.getEmail()); jsonPocs.put(jsonPoc); } hostObj.put("pocs", jsonPocs); } } finally { s.close(); } return json.toString(); } private String getQueryResultsJSON(Cab2bQuery query, boolean collapse) throws JSONException { if (!query.isDone()) { throw new IllegalStateException("Query has not completed: "+query); } Exception e = query.getException(); if (e != null) { return getJSONError(e.getClass().getName(), e.getMessage()); } JSONObject json = new JSONObject(query.getResultJson()); if (json.has("error")) { return query.getResultJson(); } Cab2bTranslator translator = queryService.getCab2b().getCab2bTranslator(); String modelGroupName = json.getString("modelGroupName"); String serviceGroup = translator.getServiceGroupForModelGroup(modelGroupName); json.remove("modelGroupName"); if (modelGroupName != null) { json.put("serviceGroup", serviceGroup); } if (collapse) { Map<String,JSONObject> unique = new LinkedHashMap<String,JSONObject>(); // the key to discriminate on for duplicates String primaryKey = translator.getPrimaryKeyForServiceGroup(serviceGroup); JSONObject queries = json.getJSONObject("results"); for(Iterator i = queries.keys(); i.hasNext(); ) { String queryName = (String)i.next(); JSONObject urls = queries.getJSONObject(queryName); for(Iterator j = urls.keys(); j.hasNext(); ) { String url = (String)j.next(); JSONArray objs = urls.getJSONArray(url); for(int k=0; k<objs.length(); k++) { JSONObject obj = objs.getJSONObject(k); String key = null; try { String host = obj.getString(HOST_KEY); String id = obj.getString(primaryKey); key = host+"~~"+id; } catch (JSONException x) { log.error("Error getting unique key",x); key = obj.toString(); } if (!unique.containsKey(key)) unique.put(key, obj); } } } JSONArray allResults = new JSONArray(); for(JSONObject obj : unique.values()) { allResults.put(obj); } json.put("results", allResults); } return json.toString(); } /** * Returns a JSON string with the given error message. * @return JSON-formatted String */ private String getJSONError(String exception, String message) { return "{\"error\":"+JSONObject.quote(exception)+ ",\"message\":"+JSONObject.quote(message)+"}"; } /** * Get a JSON string with a simple query status message. * @param status * @return * @throws JSONException */ private String getJSONStatus(Object status) throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put("status", status); return jsonObj.toString(); } /** * Returns a JSON string with usage instructions, or an error if a problem * occurs. * @return JSON-formatted String */ private String getJSONUsage() { return usage; } }
package com.growthbeat.link; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.growthbeat.CatchableThread; import com.growthbeat.GrowthbeatCore; import com.growthbeat.GrowthbeatException; import com.growthbeat.Logger; import com.growthbeat.Preference; import com.growthbeat.analytics.GrowthAnalytics; import com.growthbeat.http.GrowthbeatHttpClient; import com.growthbeat.link.FingerprintUtil.FingerprintGetter; import com.growthbeat.link.callback.DefaultSynchronizationCallback; import com.growthbeat.link.callback.SynchronizationCallback; import com.growthbeat.link.handler.DefaultInstallReferrerReceiveHandler; import com.growthbeat.link.handler.InstallReferrerReceiveHandler; import com.growthbeat.link.model.Click; import com.growthbeat.link.model.Synchronization; import com.growthbeat.utils.AppUtils; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.os.Looper; public class GrowthLink { private static final String LOGGER_DEFAULT_TAG = "GrowthLink"; private static final String HTTP_CLIENT_DEFAULT_BASE_URL = "https://api.link.growthbeat.com/"; private static final String DEFAULT_SYNCRONIZATION_URL = "http://gbt.io/l/synchronize"; private static final String DEFAULT_FINGERPRINT_URL = "http://gbt.io/l/fingerprints"; private static final int HTTP_CLIENT_DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; private static final int HTTP_CLIENT_DEFAULT_SOCKET_TIMEOUT = 60 * 1000; private static final String PREFERENCE_DEFAULT_FILE_NAME = "growthlink-preferences"; private static final String INSTALL_REFERRER_KEY = "installReferrer"; private static final GrowthLink instance = new GrowthLink(); private final Logger logger = new Logger(LOGGER_DEFAULT_TAG); private final GrowthbeatHttpClient httpClient = new GrowthbeatHttpClient(HTTP_CLIENT_DEFAULT_BASE_URL, HTTP_CLIENT_DEFAULT_CONNECTION_TIMEOUT, HTTP_CLIENT_DEFAULT_SOCKET_TIMEOUT); private final Preference preference = new Preference(PREFERENCE_DEFAULT_FILE_NAME); private Context context = null; private String applicationId = null; private String credentialId = null; private String syncronizationUrl = DEFAULT_SYNCRONIZATION_URL; private String fingerprintUrl = DEFAULT_FINGERPRINT_URL; private boolean initialized = false; private boolean firstSession = false; private CountDownLatch installReferrerLatch = new CountDownLatch(1); private SynchronizationCallback synchronizationCallback = new DefaultSynchronizationCallback(); private InstallReferrerReceiveHandler installReferrerReceiveHandler = new DefaultInstallReferrerReceiveHandler(); private GrowthLink() { super(); } public static GrowthLink getInstance() { return instance; } public void initialize(final Context context, final String applicationId, final String credentialId) { if (initialized) return; initialized = true; if (context == null) { logger.warning("The context parameter cannot be null."); return; } this.context = context.getApplicationContext(); this.applicationId = applicationId; this.credentialId = credentialId; GrowthbeatCore.getInstance().initialize(context, applicationId, credentialId); this.preference.setContext(GrowthbeatCore.getInstance().getContext()); if (GrowthbeatCore.getInstance().getClient() == null || (GrowthbeatCore.getInstance().getClient().getApplication() != null && !GrowthbeatCore.getInstance().getClient() .getApplication().getId().equals(applicationId))) { preference.removeAll(); } GrowthAnalytics.getInstance().initialize(context, applicationId, credentialId); synchronize(); } public void handleOpenUrl(Uri uri) { if (uri == null) return; final String clickId = uri.getQueryParameter("clickId"); if (clickId == null) { logger.info("Unabled to get clickId from url."); return; } final String uuid = uri.getQueryParameter("uuid"); if (uuid != null) { GrowthAnalytics.getInstance().setUUID(uuid); } new Thread(new Runnable() { @Override public void run() { logger.info("Deeplinking..."); try { final Click click = Click.deeplink(GrowthbeatCore.getInstance().waitClient().getId(), clickId, firstSession, credentialId); if (click == null || click.getPattern() == null || click.getPattern().getLink() == null) { logger.error("Failed to deeplink."); return; } logger.info(String.format("Deeplink success. (clickId: %s)", click.getId())); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Map<String, String> properties = new HashMap<String, String>(); properties.put("linkId", click.getPattern().getLink().getId()); properties.put("patternId", click.getPattern().getId()); if (click.getPattern().getIntent() != null) properties.put("intentId", click.getPattern().getIntent().getId()); if (firstSession) GrowthAnalytics.getInstance().track("GrowthLink", "Install", properties, null); GrowthAnalytics.getInstance().track("GrowthLink", "Open", properties, null); firstSession = false; if (click.getPattern().getIntent() != null) { GrowthbeatCore.getInstance().handleIntent(click.getPattern().getIntent()); } } }); } catch (GrowthbeatException e) { logger.info(String.format("Deeplink is not found.", e.getMessage())); } } }).start(); } private void synchronize() { logger.info("Check initialization..."); if (Synchronization.load() != null) { logger.info("Already initialized."); return; } firstSession = true; FingerprintUtil.asyncGetFingerprintParameters(context, fingerprintUrl, new FingerprintGetter() { @Override public void getFingerprintParameters(final String fingerprintParameters) { new Thread(new Runnable() { @Override public void run() { logger.info("Synchronizing..."); try { String version = AppUtils.getaAppVersion(context); final Synchronization synchronization = Synchronization.synchronize(applicationId, version, fingerprintParameters, credentialId); if (synchronization == null) { logger.error("Failed to Synchronize."); return; } logger.info(String.format("Synchronize success. (installReferrer: %s, cookieTracking: %s, deviceFingerprint: %s, clickId: %s)", synchronization.getInstallReferrer(), synchronization.getCookieTracking(), synchronization.getDeviceFingerprint(), synchronization.getClickId())); new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { if (GrowthLink.this.synchronizationCallback != null) { GrowthLink.this.synchronizationCallback.onComplete(synchronization); } } }); } catch (GrowthbeatException e) { logger.info(String.format("Synchronization is not found. %s", e.getMessage())); } } }).start(); } }); } public Context getContext() { return context; } public String getApplicationId() { return applicationId; } public String getCredentialId() { return credentialId; } public Logger getLogger() { return logger; } public GrowthbeatHttpClient getHttpClient() { return httpClient; } public Preference getPreference() { return preference; } public String getSyncronizationUrl() { return syncronizationUrl; } public void setSyncronizationUrl(String syncronizationUrl) { this.syncronizationUrl = syncronizationUrl; } public String getFingerprintUrl() { return fingerprintUrl; } public void setFingerprintUrl(String fingerprintUrl) { this.fingerprintUrl = fingerprintUrl; } public String getInstallReferrer() { return this.preference.getString(INSTALL_REFERRER_KEY); } public String waitInstallReferrer(long timeout) { try { installReferrerLatch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return null; } return getInstallReferrer(); } public void setInstallReferrer(String installReferrer) { this.preference.save(INSTALL_REFERRER_KEY, installReferrer); this.installReferrerLatch.countDown(); } public SynchronizationCallback getSynchronizationCallback() { return synchronizationCallback; } public void setSynchronizationCallback(SynchronizationCallback synchronizationCallback) { this.synchronizationCallback = synchronizationCallback; } public InstallReferrerReceiveHandler getInstallReferrerReceiveHandler() { return installReferrerReceiveHandler; } public void setInstallReferrerReceiveHandler(InstallReferrerReceiveHandler installReferrerReceiveHandler) { this.installReferrerReceiveHandler = installReferrerReceiveHandler; } private static class Thread extends CatchableThread { public Thread(Runnable runnable) { super(runnable); } @Override public void uncaughtException(java.lang.Thread thread, Throwable e) { String link = "Uncaught Exception: " + e.getClass().getName(); if (e.getMessage() != null) link += "; " + e.getMessage(); GrowthLink.getInstance().getLogger().warning(link); e.printStackTrace(); } } }
package org.opensim.view.motions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.Hashtable; import java.util.Observable; import java.util.Observer; import java.util.Vector; import javax.swing.JButton; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.awt.StatusDisplayer; import org.openide.nodes.Node; import org.opensim.modeling.Model; import org.opensim.modeling.ArrayStr; import org.opensim.view.experimentaldata.ModelForExperimentalData; import org.opensim.modeling.OpenSimObject; import org.opensim.modeling.Storage; import org.opensim.utils.FileUtils; import org.opensim.view.ExplorerTopComponent; import org.opensim.view.ModelEvent; import org.opensim.view.ObjectsRenamedEvent; import org.opensim.view.actions.ConfirmSaveDiscardJPanel; import org.opensim.view.experimentaldata.AnnotatedMotion; import org.opensim.view.nodes.OneModelNode; import org.opensim.view.pub.*; /** * * @author Ayman */ public class MotionsDB extends Observable // Observed by other entities in motionviewer implements Observer { public enum CloseMotionDefaultAction { SAVE, DISCARD, PROMPT } static private CloseMotionDefaultAction currentCloseMotionDefaultAction = CloseMotionDefaultAction.PROMPT; void addMotionDisplayer(Storage simmMotionData, MotionDisplayer displayer) { mapMotions2Displayers.put(simmMotionData, displayer); } MotionDisplayer getDisplayerForMotion(Storage mot){ return mapMotions2Displayers.get(mot); } void removeMotionDisplayer(Storage mot) { mapMotions2Displayers.remove(mot); } // Observer OpenSimDB to sync. up when models are deleted public static class ModelMotionPair { public Model model; public Storage motion; public ModelMotionPair(Model model, Storage motion) { this.model = model; this.motion = motion; } } static MotionsDB instance; // Map model to an ArrayList of Motions linked with it Hashtable<Model, ArrayList<Storage>> mapModels2Motions = new Hashtable<Model, ArrayList<Storage>>(4); Hashtable<Storage, MotionDisplayer> mapMotions2Displayers = new Hashtable<Storage, MotionDisplayer>(4); // Remember for each storage object, the file name it came from. Useful for saving/restoring application state // : If a file name is reused this info may not be current Hashtable<Storage, String> storageFilenames = new Hashtable<Storage, String>(4); // Map motion to a BitSet for storing dirty bit, etc. Hashtable<Storage, BitSet> mapMotion2BitSet = new Hashtable<Storage, BitSet>(1); private final static int numBits = 4; private final static int modifiedBit = 0; // More than one motion may be current if synchronizing motion Vector<ModelMotionPair> currentMotions = new Vector<ModelMotionPair>(); /** Creates a new instance of MotionsDB */ private MotionsDB() { OpenSimDB.getInstance().addObserver(this); addObserver(this); // Listen to our own events (used to update the explorer) } public static synchronized MotionsDB getInstance() { if (instance == null) { instance = new MotionsDB(); } return instance; } /** * Load a motion file, and associate it with a model. * We try to associate the motion with current model first if something doesn't look * right (e.g. no coordinates or markers match, warn and ask user either to select another model * or abort loading. * A side effect of changing the model associated with a loaded motion is that the new model becomes * current. */ public void loadMotionFile(String fileName, boolean primary) { Storage storage = null; try { storage = new Storage(fileName); } catch (IOException ex) { ex.printStackTrace(); DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Could not read motion file "+fileName)); return; } //saveStorageFileName(storage, fileName); loadMotionStorage(storage, primary, fileName); } public void loadMotionStorage(Storage newMotion, boolean primary, String filePath) { if (primary){ boolean associated = false; while(!associated){ Model modelForMotion = OpenSimDB.getInstance().selectModel(OpenSimDB.getInstance().getCurrentModel()); if (modelForMotion == null){ // user cancelled break; } // user selected a model, try to associate it if(MotionsDB.getInstance().motionAssociationPossible(modelForMotion, newMotion)){ addMotion(modelForMotion, newMotion, null); StatusDisplayer.getDefault().setStatusText("Associated motion: "+newMotion.getName()+" to model: "+modelForMotion.getName()); associated = true; } else { // Show error that motion couldn't be associated and repeat' DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message("Could not associate motion to current model.")); break; } } } else{ // There's already a model associated with current motion, use it Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (selected.length==1 && selected[0] instanceof OneMotionNode){ OneMotionNode parentMotionNode = (OneMotionNode) selected[0]; Model modelForMotion = parentMotionNode.getModelForNode(); if (newMotion instanceof AnnotatedMotion) addMotion(modelForMotion, newMotion, parentMotionNode.getMotion()); else { AnnotatedMotion aMot = new AnnotatedMotion(newMotion); addMotion(modelForMotion, aMot, parentMotionNode.getMotion()); MotionsDB.getInstance().saveStorageFileName(aMot, filePath); } } } } /** * Criteria for associating motionto a model: * At least one genccord or marker (_tx?) in motion file/Storage */ boolean motionAssociationPossible(Model modelForMotion, Storage newMotion) { ArrayStr coordinateNames = new ArrayStr(); modelForMotion.getCoordinateSet().getNames(coordinateNames); int numCoordinates = coordinateNames.getSize(); int numUsedColumns = 0; // Keep track of how many columns correspond to Coords or Markers for(int i=0; i<numCoordinates; i++){ if (newMotion.getStateIndex(coordinateNames.getitem(i))!=-1) numUsedColumns++; } ArrayStr markerNames = new ArrayStr(); modelForMotion.getMarkerSet().getNames(markerNames); for(int i=0; i<markerNames.getSize(); i++){ if ((newMotion.getStateIndex(markerNames.getitem(i)+"_tx")!=-1) || (newMotion.getStateIndex(markerNames.getitem(i)+"_Tx")!=-1) || (newMotion.getStateIndex(markerNames.getitem(i)+"_TX")!=-1)) numUsedColumns++; } return (numUsedColumns>=1); // At least one column makes sense } public void addMotion(Model model, Storage motion, Storage parentMotion) { if (! (model instanceof ModelForExperimentalData)){ boolean convertAngles = motion.isInDegrees(); if(convertAngles) model.getSimbodyEngine().convertDegreesToRadians(motion); } // Add to mapModels2Motion ArrayList<Storage> motions = mapModels2Motions.get(model); if(motions==null) { // First motion for model motions = new ArrayList<Storage>(4); mapModels2Motions.put(model, motions); } motions.add(motion); // Add to mapMotion2BitSet BitSet motionBits = new BitSet(numBits); mapMotion2BitSet.put(motion, motionBits); MotionEvent evt = new MotionEvent(this, model, motion, (parentMotion==null)?MotionEvent.Operation.Open:MotionEvent.Operation.Assoc); setChanged(); notifyObservers(evt); if (parentMotion==null) setCurrent(model, motion); // Also make it current (a separate event is sent out) } public void setMotionModified(Storage motion, boolean state) { BitSet motionBits = mapMotion2BitSet.get(motion); if (motionBits != null) motionBits.set(modifiedBit, state); } public boolean getMotionModified(Storage motion) { BitSet motionBits = mapMotion2BitSet.get(motion); if (motionBits != null) return motionBits.get(modifiedBit); return false; } public void clearCurrent() { clearCurrentMotions(); MotionEvent evt = new MotionEvent(this, MotionEvent.Operation.CurrentMotionsChanged); setChanged(); notifyObservers(evt); } public void setCurrent(Model model, Storage motion) { setCurrentMotion(new ModelMotionPair(model, motion)); MotionEvent evt = new MotionEvent(this, MotionEvent.Operation.CurrentMotionsChanged); evt.setModel(model); setChanged(); notifyObservers(evt); } public void setCurrent(Vector<ModelMotionPair> motions) { setCurrentMotions(motions); MotionEvent evt = new MotionEvent(this, MotionEvent.Operation.CurrentMotionsChanged); setChanged(); notifyObservers(evt); } public void closeMotion(Model model, Storage simmMotionData, boolean allowCancel) { closeMotion(model, simmMotionData, true, allowCancel); } public void closeMotion(Model model, Storage simmMotionData, boolean confirmCloseIfModified, boolean allowCancel) { // Prompt user to confirm the close and possibly save the motion if it has been modified. if (confirmCloseIfModified && getMotionModified(simmMotionData)) { if (!confirmCloseMotion(model, simmMotionData, allowCancel)) return; } ArrayList<Storage> motions = mapModels2Motions.get(model); if(motions!=null) { // Shouldn't be null, but just in case... motions.remove(simmMotionData); } // Remove from mapMotion2BitSet mapMotion2BitSet.remove(simmMotionData); boolean removed = removeFromCurrentMotions(new ModelMotionPair(model, simmMotionData)); Node motionNode = getMotionNode(model, simmMotionData); Node parentOrTopMotionsNode = null; if(motionNode!=null) { parentOrTopMotionsNode = motionNode.getParentNode(); // get displayer for parnet motion and remove evnt.getMotion() from associated motions if (motionNode instanceof OneAssociatedMotionNode){ Storage parentMotion = ((OneMotionNode) parentOrTopMotionsNode).getMotion(); MotionDisplayer currentDisplayer = getDisplayerForMotion(simmMotionData); currentDisplayer.cleanupDisplay(); getDisplayerForMotion(parentMotion).getAssociatedMotions().remove(currentDisplayer); } } MotionEvent evt = new MotionEvent(this, model, simmMotionData, MotionEvent.Operation.Close); setChanged(); notifyObservers(evt); removeMotionDisplayer(simmMotionData); if(removed) { evt = new MotionEvent(this, MotionEvent.Operation.CurrentMotionsChanged); setChanged(); notifyObservers(evt); } } private boolean confirmCloseMotion(Model model, Storage simmMotionData, boolean allowCancel) { int dialogType = NotifyDescriptor.YES_NO_OPTION; if (allowCancel) dialogType = NotifyDescriptor.YES_NO_CANCEL_OPTION; NotifyDescriptor dlg = new NotifyDescriptor.Confirmation("Do you want to save the changes to motion '" + simmMotionData.getName() + "'?", "Save Modified Motion?", dialogType); Object userSelection = DialogDisplayer.getDefault().notify(dlg); if (((Integer)userSelection).intValue() == ((Integer)NotifyDescriptor.OK_OPTION).intValue()) { String fileName = FileUtils.getInstance().browseForFilenameToSave(FileUtils.MotionFileFilter, true, ""); if (fileName != null) { MotionsSaveAsAction.saveMotion((model), simmMotionData, fileName); saveStorageFileName(simmMotionData, fileName); return true; } else { // The user cancelled out of saving the file, which we interpret as wanting to cancel // the closing of the motion. But if allowCancel == false then we have to return true // so the close is not cancelled. return !allowCancel; } } else if (((Integer)userSelection).intValue() == ((Integer)NotifyDescriptor.NO_OPTION).intValue()) { return true; } return false; } public void update(Observable o, Object arg) { if (o instanceof OpenSimDB && arg instanceof ModelEvent){ ModelEvent evnt = (ModelEvent) arg; if (evnt.getOperation()==ModelEvent.Operation.Close){ Model model = evnt.getModel(); closeMotionsForModel(model); } else if (evnt.getOperation()==ModelEvent.Operation.SetCurrent){ if (evnt.getModel() instanceof ModelForExperimentalData){ // Make corresponding motion current as well ArrayList<Storage> motions = getModelMotions(evnt.getModel()); assert(motions.size()==1); setCurrent(evnt.getModel(), motions.get(0)); } } } else if (o instanceof MotionsDB && arg instanceof MotionEvent) { final MotionEvent evnt = (MotionEvent) arg; // Update tree display on event thread switch(evnt.getOperation()) { case Open: { Node modelNode = ExplorerTopComponent.findInstance().getModelNode(evnt.getModel()); if (modelNode==null) return; Node newMotionNode; if (evnt.getModel() instanceof ModelForExperimentalData){ newMotionNode= new OneMotionDataNode(evnt.getMotion()); modelNode.getChildren().add(new Node[]{newMotionNode}); } else { newMotionNode= new OneMotionNode(evnt.getMotion()); MotionsNode motionsNode = (MotionsNode) modelNode.getChildren().findChild("Motions"); if(motionsNode==null) { motionsNode = new MotionsNode(); getInstance().addObserver(motionsNode); modelNode.getChildren().add(new Node[]{motionsNode}); } motionsNode.getChildren().add(new Node[]{newMotionNode}); Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); ExplorerTopComponent.findInstance().getExplorerManager().setExploredContext(newMotionNode, selected); } break; } case Close: { try { // destroy() may throw IOException Node motionNode = getMotionNode(evnt.getModel(), evnt.getMotion()); Node parentOrTopMotionsNode = null; if(motionNode!=null) { parentOrTopMotionsNode = motionNode.getParentNode(); // get displayer for parnet motion and remove evnt.getMotion() from associated motions if (motionNode instanceof OneAssociatedMotionNode){ Storage parentMotion = ((OneMotionNode) parentOrTopMotionsNode).getMotion(); MotionDisplayer currentDisplayer = getDisplayerForMotion(evnt.getMotion()); getDisplayerForMotion(parentMotion).getAssociatedMotions().remove(currentDisplayer); } motionNode.destroy(); } // Delete the "Motions" container node if no more motions left if(parentOrTopMotionsNode!=null && parentOrTopMotionsNode.getChildren().getNodesCount()==0 && parentOrTopMotionsNode.getName().equals("Motions")) parentOrTopMotionsNode.destroy(); } catch (IOException ex) { ex.printStackTrace(); } break; } case Assoc: { Node[] motionNode = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (motionNode.length!=1) return; Node newMotionNode = new OneAssociatedMotionNode((AnnotatedMotion)evnt.getMotion()); motionNode[0].getChildren().add(new Node[]{newMotionNode}); break; } } } } public void reportTimeChange(double newTime) { MotionTimeChangeEvent evt = new MotionTimeChangeEvent(instance,newTime); setChanged(); instance.notifyObservers(evt); } public void reportModifiedMotion(Storage simmMotionData, Model model) { MotionEvent evt = new MotionEvent(this, model, simmMotionData, MotionEvent.Operation.Modified); setChanged(); notifyObservers(evt); } public ArrayList<Storage> getModelMotions(Model aModel) { return mapModels2Motions.get(aModel); } // Get the motion node from the explorer public OneMotionNode getMotionNode(final Model model, final Storage motion) { OneModelNode modelNode = ExplorerTopComponent.findInstance().getModelNode(model); if(modelNode!=null) { Node motionsNode = modelNode.getChildren().findChild("Motions"); if(motionsNode!=null) { return getMotionNode(motionsNode, motion); } else { // Preview motion if (model instanceof ModelForExperimentalData) return getMotionNode(modelNode, motion); } } return null; } // Utilities for currentMotions // TODO: add an equals() method to ModelMotionPair so that we can use more standard Vector routines // in place of these... but then I think we'll have to implement hashCode() and other such base functions. private void clearCurrentMotions() { currentMotions.setSize(0); } private void addToCurrentMotions(ModelMotionPair pair) { currentMotions.add(pair); } private void setCurrentMotion(ModelMotionPair pair) { currentMotions.setSize(1); currentMotions.set(0, pair); } private void setCurrentMotions(Vector<ModelMotionPair> motions) { currentMotions = motions; // TODO: hopefully it's safe to just use = here } private boolean removeFromCurrentMotions(ModelMotionPair pair) { for(int i=0; i<currentMotions.size(); i++) { if(currentMotions.get(i).model == pair.model && currentMotions.get(i).motion == pair.motion) { currentMotions.remove(i); return true; } } return false; } public int getNumCurrentMotions() { return currentMotions.size(); } public ModelMotionPair getCurrentMotion(int i) { return currentMotions.get(i); } boolean isModelMotionPairCurrent(ModelMotionPair pair) { for(int i=0; i<currentMotions.size(); i++) { if(currentMotions.get(i).model == pair.model && currentMotions.get(i).motion == pair.motion) return true; } return false; } void renameMotion(OpenSimObject openSimObject, String newName) { // Object has been renamed already; fire an ObjectsRenamedEvent. Vector<OpenSimObject> objs = new Vector<OpenSimObject>(1); objs.add(openSimObject); ObjectsRenamedEvent evnt = new ObjectsRenamedEvent(this, null, objs); setMotionModified((Storage)openSimObject, true); setChanged(); getInstance().notifyObservers(evnt); } public void setCurrentTime(double d) { reportTimeChange(d); } public void refreshDisplay() { double currentTime = MotionControlJPanel.getInstance().getMasterMotion().getCurrentTime(); setCurrentTime(currentTime); } public void saveStorageFileName(Storage newMotion, String fileName) { storageFilenames.put(newMotion, fileName); } public String getStorageFileName(Storage aMotion){ return storageFilenames.get(aMotion); } public void rebuild(MotionsDBDescriptor motionsDBDescriptor) { clearCurrentMotions(); ArrayList<String> modelFiles = motionsDBDescriptor.getModelFileNames(); ArrayList<String> motionFiles = motionsDBDescriptor.getMotionFileNames(); Object[] models =OpenSimDB.getInstance().getAllModels(); for(int i=0; i< models.length; i++){ Model candidateModel = ((Model)models[i]); int index=0; if (candidateModel.getInputFileName().equalsIgnoreCase(modelFiles.get(index))){ // Create motion from corresponding motionFiles[index] MotionsDB.getInstance().loadMotionFile(motionFiles.get(index), true); } } } private OneMotionNode getMotionNode(Node motionsNode, Storage motion) { Node[] children = motionsNode.getChildren().getNodes(); for(Node child : motionsNode.getChildren().getNodes()){ if(child instanceof OneMotionNode){ OneMotionNode motionNode = (OneMotionNode) child; if (motionNode.getMotion() == motion) return motionNode; for(Node associatedMotionNode:motionNode.getChildren().getNodes()){ if ((associatedMotionNode instanceof OneAssociatedMotionNode) && ((OneAssociatedMotionNode)associatedMotionNode).getMotion() == motion) return (OneMotionNode)associatedMotionNode; } } } return null; } public void closeMotionsForModel(Model model) { // Send motion close events for all motions associated with this model ArrayList<Storage> motionsForModel = mapModels2Motions.get(model); if(motionsForModel != null) { int numMotions = motionsForModel.size(); if (numMotions>1){ currentCloseMotionDefaultAction = CloseMotionDefaultAction.SAVE; final ConfirmSaveDiscardJPanel confirmPanel = new ConfirmSaveDiscardJPanel(numMotions>1); confirmPanel.setConformationText("Do you want to save results for "+model.getName()); JButton saveButton = new JButton("Save"); DialogDescriptor confirmDialog = new DialogDescriptor(confirmPanel, "Confirm Save", true, new Object[]{saveButton, new JButton("Discard")}, saveButton, 0, null, new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); boolean remember = confirmPanel.rememberUserChoice(); if (remember) { if (cmd.equalsIgnoreCase("Save")) { currentCloseMotionDefaultAction = CloseMotionDefaultAction.SAVE; //FileSaveModelAction.saveOrSaveAsModel(model, false); } else if (cmd.equalsIgnoreCase("Discard")) { currentCloseMotionDefaultAction = CloseMotionDefaultAction.DISCARD; } } } }); confirmDialog.setClosingOptions(null); DialogDisplayer.getDefault().createDialog(confirmDialog).setVisible(true); Object dlgReturn = confirmDialog.getValue(); int x=0; for(int i=numMotions-1; i>=0; i closeMotion(model, motionsForModel.get(i), currentCloseMotionDefaultAction == CloseMotionDefaultAction.SAVE, false); } currentCloseMotionDefaultAction = CloseMotionDefaultAction.SAVE; } else if (numMotions==1) closeMotion(model, motionsForModel.get(0), false); } } }
package com.jediterm.terminal.model; import com.google.common.collect.Lists; import com.jediterm.terminal.StyledTextConsumer; import com.jediterm.terminal.TextStyle; import com.jediterm.terminal.model.TerminalLine.TextEntry; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * Holds styled characters lines */ public class LinesBuffer { private static final Logger LOG = Logger.getLogger(LinesBuffer.class); private static final int BUFFER_MAX_LINES = 1000; private ArrayList<TerminalLine> myLines = Lists.newArrayList(); public LinesBuffer() { } public synchronized String getLines() { final StringBuilder sb = new StringBuilder(); boolean first = true; for (TerminalLine line : myLines) { if (!first) { sb.append("\n"); } sb.append(line.getText()); first = false; } return sb.toString(); } public synchronized void addNewLine(@NotNull TextStyle style, @NotNull CharBuffer characters) { addNewLine(new TerminalLine.TextEntry(style, characters)); } private synchronized void addNewLine(@NotNull TerminalLine.TextEntry entry) { addLine(new TerminalLine(entry)); } private synchronized void addLine(@NotNull TerminalLine line) { if (myLines.size() >= BUFFER_MAX_LINES) { removeTopLines(1); } myLines.add(line); } public synchronized int getLineCount() { return myLines.size(); } public synchronized void removeTopLines(int count) { myLines = Lists.newArrayList(myLines.subList(count, myLines.size())); } public String getLineText(int row) { TerminalLine line = getLine(row); return line.getText(); } public synchronized void insertLines(int y, int count, int lastLine, @NotNull TextEntry filler) { LinesBuffer tail = new LinesBuffer(); if (lastLine < getLineCount() - 1) { moveBottomLinesTo(getLineCount() - lastLine - 1, tail); } LinesBuffer head = new LinesBuffer(); if (y > 0) { moveTopLinesTo(y, head); } for (int i = 0; i < count; i++) { head.addNewLine(filler); } head.moveBottomLinesTo(head.getLineCount(), this); removeBottomLines(count); tail.moveTopLinesTo(tail.getLineCount(), this); } public synchronized LinesBuffer deleteLines(int y, int count, int lastLine, @NotNull TextEntry filler) { LinesBuffer tail = new LinesBuffer(); if (lastLine < getLineCount() - 1) { moveBottomLinesTo(getLineCount() - lastLine - 1, tail); } LinesBuffer head = new LinesBuffer(); if (y > 0) { moveTopLinesTo(y, head); } int toRemove = Math.min(count, getLineCount()); LinesBuffer removed = new LinesBuffer(); moveTopLinesTo(toRemove, removed); head.moveBottomLinesTo(head.getLineCount(), this); for (int i = 0; i < toRemove; i++) { addNewLine(filler); } tail.moveTopLinesTo(tail.getLineCount(), this); return removed; } public synchronized void writeString(int x, int y, String str, @NotNull TextStyle style) { TerminalLine line = getLine(y); line.writeString(x, str, style); } public synchronized void clearLines(int startRow, int endRow, @NotNull TextEntry filler) { for (int i = startRow; i <= endRow; i++) { getLine(i).clear(filler); } } // used for reset, style not needed here (reseted as well) public synchronized void clearAll() { myLines.clear(); } public synchronized void deleteCharacters(int x, int y, int count, @NotNull TextStyle style) { TerminalLine line = getLine(y); line.deleteCharacters(x, count, style); } public synchronized void insertBlankCharacters(final int x, final int y, final int count, final int maxLen, @NotNull TextStyle style) { TerminalLine line = getLine(y); line.insertBlankCharacters(x, count, maxLen, style); } public synchronized void clearArea(int leftX, int topY, int rightX, int bottomY, @NotNull TextStyle style) { for (int y = topY; y < bottomY; y++) { TerminalLine line = getLine(y); line.clearArea(leftX, rightX, style); } } public synchronized void processLines(final int yStart, final int yCount, @NotNull final StyledTextConsumer consumer) { processLines(yStart, yCount, consumer, -getLineCount()); } public synchronized void processLines(final int firstLine, final int count, @NotNull final StyledTextConsumer consumer, final int startRow) { for (int y = firstLine; y < Math.min(firstLine + count, myLines.size()); y++) { myLines.get(y).process(y, consumer, startRow); } } public synchronized void moveTopLinesTo(int count, final @NotNull LinesBuffer buffer) { count = Math.min(count, getLineCount()); buffer.addLines(myLines.subList(0, count)); removeTopLines(count); } public synchronized void addLines(@NotNull List<TerminalLine> lines) { int count = myLines.size() + lines.size(); if (count >= BUFFER_MAX_LINES) { removeTopLines(count - BUFFER_MAX_LINES); } myLines.addAll(lines); } @NotNull public synchronized TerminalLine getLine(int row) { for (int i = getLineCount(); i <= row; i++) { addLine(TerminalLine.createEmpty()); } return myLines.get(row); } public synchronized void moveBottomLinesTo(int count, final @NotNull LinesBuffer buffer) { count = Math.min(count, getLineCount()); buffer.addLinesFirst(myLines.subList(getLineCount() - count, getLineCount())); removeBottomLines(count); } private synchronized void addLinesFirst(@NotNull List<TerminalLine> lines) { List<TerminalLine> list = Lists.newArrayList(lines); list.addAll(myLines); myLines = Lists.newArrayList(list); } private synchronized void removeBottomLines(int count) { myLines = Lists.newArrayList(myLines.subList(0, getLineCount() - count)); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by CDS Networks, Inc. // 4. The name of CDS Networks, Inc. may not be used to endorse or promote // products derived from this software without specific prior // THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL CDS NETWORKS, INC. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. package com.internetcds.jdbc.tds; /** * constants from the 4.2 TDS protocol * * @version $Id: TdsDefinitions.java,v 1.6 2002-08-05 13:56:30 alin_sinpalean Exp $ * @author Craig Spannring * @author The FreeTDS project. */ interface TdsDefinitions { public static final String cvsVersion = "$Id: TdsDefinitions.java,v 1.6 2002-08-05 13:56:30 alin_sinpalean Exp $"; // Define the type of database the driver is connection to. public static final int SQLSERVER = 1; public static final int SYBASE = 2; // Versions of the TDS protocol. Keep the values in order so code // can recognize versions at or after a specified version. public static final int TDS42 = 42; public static final int TDS50 = 50; public static final int TDS70 = 70; // Sub packet types static final byte TDS_LANG_TOKEN = (byte)33; // 0x21 TDS 5.0 only static final byte TDS_CLOSE_TOKEN = (byte)113; // 0x71 TDS 5.0 only? ct_close() static final byte TDS_RET_STAT_TOKEN = (byte)0x79; // 121 static final byte TDS_PROCID = (byte)0x7C; // 124 TDS_PROCID static final byte TDS7_RESULT_TOKEN = (byte)129; // 0x81 TDS 7.0 only static final byte TDS_COL_NAME_TOKEN = (byte)0xA0; // 160 TDS 4.2 only static final byte TDS_COL_INFO_TOKEN = (byte)161; // 0xA1 TDS 4.2 only static final byte TDS_TABNAME = (byte)164; // 0xA4 static final byte TDS_UNKNOWN_0xA5 = (byte)0xA5; // 0xA5 static final byte TDS_UNKNOWN_0xA7 = (byte)0xA7; static final byte TDS_UNKNOWN_0xA8 = (byte)0xA8; static final byte TDS_ORDER = (byte)169; // 0xA9 TDS_ORDER static final byte TDS_ERR_TOKEN = (byte)170; // 0xAA static final byte TDS_MSG_TOKEN = (byte)171; // 0xAB static final byte TDS_PARAM_TOKEN = (byte)172; // 0xAC static final byte TDS_LOGIN_ACK_TOKEN = (byte)173; // 0xAD static final byte TDS_CONTROL = (byte)174; // 0xAE TDS_CONTROL static final byte TDS_ROW_TOKEN = (byte)209; // 0xD1 static final byte TDS_CMP_ROW_TOKEN = (byte)0xD3; // Compute Result Row static final byte TDS_CAP_TOKEN = (byte)226; // 0xE2 static final byte TDS_ENV_CHG_TOKEN = (byte)227; // 0xE3 static final byte TDS_MSG50_TOKEN = (byte)229; // 0xE5 static final byte TDS_RESULT_TOKEN = (byte)238; // 0xEE static final byte TDS_END_TOKEN = (byte)253; // 0xFD TDS_DONE static final byte TDS_DONEPROC = (byte)254; // 0xFE TDS_DONEPROC static final byte TDS_DONEINPROC = (byte)255; // 0xFF TDS_DONEINPROC // end of sub packet types static final byte TDS_ENV_DATABASE = (byte)1; static final byte TDS_ENV_CHARSET = (byte)3; static final byte TDS_ENV_BLOCKSIZE = (byte)4; // Native Column types static final byte SYBVOID = 31; // 0x1F static final byte SYBIMAGE = 34; // 0x22 static final byte SYBTEXT = 35; // 0x23 static final byte SYBVARBINARY = 37; // 0x25 static final byte SYBINTN = 38; // 0x26 static final byte SYBVARCHAR = 39; // 0x27 static final byte SYBBINARY = 45; // 0x2D static final byte SYBCHAR = 47; // 0x2F static final byte SYBINT1 = 48; // 0x30 static final byte SYBBIT = 50; // 0x32 static final byte SYBINT2 = 52; // 0x34 static final byte SYBINT4 = 56; // 0x38 static final byte SYBDATETIME4 = 58; // 0x3A static final byte SYBREAL = 59; // 0x3B static final byte SYBMONEY = 60; // 0x3C (does not allow nulls?) static final byte SYBDATETIME = 61; // 0x3D static final byte SYBFLT8 = 62; // 0x3E static final byte SYBNTEXT = 99; // 0x63 static final byte SYBNVARCHAR = 103; // 0x67 static final byte SYBBITN = 104; // 0x68 static final byte SYBDECIMAL = 106; // 0x6A static final byte SYBNUMERIC = 108; // 0x6C static final byte SYBFLTN = 109; // 0x6D static final byte SYBMONEYN = 110; // 0x6E static final byte SYBDATETIMN = 111; // 0x6F static final byte SYBMONEY4 = 112; // 0x70 static final byte SYBNCHAR = -17; // 0xEF // according to srv.h here are some additional types static final byte SYBBIGVARBINARY = (byte)0xA5; static final byte SYBBIGVARCHAR = (byte)0xA7; static final byte SYBBIGBINARY = (byte)0xAD; static final byte SYBBIGCHAR = (byte)0xAF; // XXX should SYBMONEY4 be 122 instead of 112? static final byte SYBSMALLMONEY = 122; // 0x7A // end of column types }
package com.punchline.javalib.entities; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Disposable; public final class PhysicsWorld implements Disposable { //region Constants private static final float TIME_STEP = 1.0f / 60.0f; private static final int MAX_STEPS = 5; //endregion //region Fields private World world; private int velocityIterations; private int positionIterations; private float elapsedTime; private float elapsedRatio; //endregion //region Initialization /** * Creates a PhysicsWorld. * @param gravity The world's gravity vector. * @param velocityIterations The world's number of velocity iterations per * time step. * @param positionIterations The world's number of position iterations per * time step. */ public PhysicsWorld(Vector2 gravity, int velocityIterations, int positionIterations) { world = new World(gravity, true); world.setAutoClearForces(false); this.velocityIterations = velocityIterations; this.positionIterations = positionIterations; } /** * Creates a PhysicsWorld. * @param gravity The world's gravity vector. */ public PhysicsWorld(Vector2 gravity) { this(gravity, 6, 2); } /** * Creates a PhysicsWorld with normal gravity. */ public PhysicsWorld() { this(new Vector2(0, -9.8f)); } //endregion //region Disposal @Override public void dispose() { world.dispose(); } //endregion //region Accessors /** * @return The Box2D {@link World} wrapped in this instance. */ public World getWorld() { return world; } /** * @return The remainder of the previous delta time that has not yet * been processed by the physics simulation. */ public float getElapsedRatio() { return elapsedRatio; } //endregion //region Processing /** * Runs the {@link World}'s time step the appropriate number of times in order * to accommodate the current frame rate. * @param deltaSeconds The delta time, in seconds. */ public void process(float deltaSeconds) { elapsedTime += deltaSeconds; //Calculate how many steps are needed int steps = (int) (elapsedTime / TIME_STEP); //to simulate the last game loop if (steps > 0) { elapsedTime -= steps * TIME_STEP; //elapsedTime now equals the amount of time that hasn't been simulated } elapsedRatio = elapsedTime / TIME_STEP; //elapsedRatio now equals the fraction of a time step that hasn't been simulated steps = Math.min(steps, MAX_STEPS); //Clamp steps to avoid the spiral of doom for (int i = 0; i < steps; i++) { singleStep(); } //world.step(elapsedTime, velocityIterations, positionIterations); world.clearForces(); } //endregion //region Helpers private void singleStep() { world.step(TIME_STEP, velocityIterations, positionIterations); } //endregion }
/** * @author sliva */ package compiler.phases.abstr; import java.util.*; import compiler.common.report.*; import compiler.data.dertree.*; import compiler.data.dertree.DerNode.Nont; import compiler.data.dertree.visitor.*; import compiler.data.symbol.Symbol.Term; import compiler.data.abstree.*; import compiler.data.abstree.AbsBinExpr.Oper; /** * Transforms a derivation tree to an abstract syntax tree. * * @author sliva */ public class AbsTreeConstructor implements DerVisitor<AbsTree, AbsTree> { private final String PTR_NODE = "Expected PTR node"; private final String ARR_NODE = "Expected ARR node"; private final String GOT_STR = " got: "; private final String TOO_MANY_NODES = "There are zore or more than 3 nodes"; private final String DECL_NODE = "Declaration node doesn't start with TYP, FUN or VAR"; private final String WRONG_BINARY_NODE = "This binary operator doesn't exist."; private final Location kNULL_LOCATION = new Location(0, 0); @Override public AbsTree visit(DerLeaf leaf, AbsTree visArg) { throw new Report.InternalError(); } @Override public AbsTree visit(DerNode node, AbsTree visArg) { switch (node.label) { case Source: { AbsDecls decls = (AbsDecls) node.subtree(0).accept(this, null); return new AbsSource(decls, decls); } case Decls: case DeclsRest: { if (node.numSubtrees() == 0) return null; Vector<AbsDecl> allDecls = new Vector<AbsDecl>(); AbsDecl decl = (AbsDecl) node.subtree(0).accept(this, null); allDecls.add(decl); AbsDecls decls = (AbsDecls) node.subtree(1).accept(this, null); if (decls != null) allDecls.addAll(decls.decls()); return new AbsDecls(new Location(decl, decls == null ? decl : decls), allDecls); } case Decl: { DerLeaf typeOfDecleration = (DerLeaf) node.subtree(0); switch (typeOfDecleration.symb.token) { case VAR: { AbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null); Location loc = new Location(typeOfDecleration, parDecl); return new AbsVarDecl(loc, parDecl.name, parDecl.type); } case TYP: { AbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null); Location loc = new Location(typeOfDecleration, parDecl); return new AbsTypDecl(loc, parDecl.name, parDecl.type); } case FUN: { DerLeaf funName = (DerLeaf) node.subtree(1); AbsParDecls parDecls = (AbsParDecls) node.subtree(2).accept(this, null); AbsType type = (AbsType) node.subtree(3).accept(this, null); AbsExpr expr = (AbsExpr) node.subtree(4).accept(this, null); if (expr.location().equals(kNULL_LOCATION)) { Location loc = new Location(typeOfDecleration, type); System.out.println("null"); return new AbsFunDecl(loc, funName.symb.lexeme, parDecls, type); } else { System.out.println("not"); Location loc = new Location(typeOfDecleration, expr); return new AbsFunDef(loc, funName.symb.lexeme, parDecls, type, expr); } } default: throw new Report.Error(typeOfDecleration.location(), DECL_NODE + GOT_STR + typeOfDecleration.symb.token.toString()); } } case ParDecl: { return DeformParDecl(node); } case Type: { if (node.numSubtrees() == 1) { // This is only check for ( Type ) if (node.subtree(0) instanceof DerNode) { return node.subtree(0).accept(this, null); } else if (node.subtree(0) instanceof DerLeaf) { DerLeaf primitiveTypeNode = (DerLeaf) node.subtree(0); AbsAtomType.Type primitiveType; switch (primitiveTypeNode.symb.token) { case VOID: primitiveType = AbsAtomType.Type.VOID; break; case BOOL: primitiveType = AbsAtomType.Type.BOOL; break; case CHAR: primitiveType = AbsAtomType.Type.CHAR; break; case INT: primitiveType = AbsAtomType.Type.INT; break; default: // TODO: Error (Maybe) return new AbsTypName(primitiveTypeNode.location(), primitiveTypeNode.symb.lexeme); } return new AbsAtomType(primitiveTypeNode.location(), primitiveType); } } else if (node.numSubtrees() == 2) { DerLeaf ptr = (DerLeaf) node.subtree(0); if (ptr.symb.token == Term.PTR) { AbsType subType = (AbsType) node.subtree(1).accept(this, null); Location loc = new Location(ptr, subType); return new AbsPtrType(loc, subType); } else if (ptr.symb.token == Term.REC) { AbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null); Location loc = new Location(ptr, compDecls); return new AbsRecType(loc, compDecls); } else { throw new Report.Error(ptr.location(), PTR_NODE + GOT_STR + ptr.symb.token.toString()); } } else if (node.numSubtrees() == 3) { DerLeaf arr = (DerLeaf) node.subtree(0); if (arr.symb.token != Term.ARR) { throw new Report.Error(arr.location(), ARR_NODE + GOT_STR + arr.symb.token.toString()); } AbsExpr length = (AbsExpr) node.subtree(1).accept(this, null); AbsType elemType = (AbsType) node.subtree(2).accept(this, null); Location loc = new Location(arr, elemType); return new AbsArrType(loc, length, elemType); } else { throw new Report.Error(node.location(), TOO_MANY_NODES + GOT_STR + node.numSubtrees()); } } case ParDecls: { return DeformParDecls(node); } case ParDeclsRest: { return DeformParDecls(node); } case BodyEps: { if (node.numSubtrees() == 0) { // Hacky try to find other expr that is not abstrac and has less field return Epsilon(); } return node.subtree(1).accept(this, null); } case CompDecls: case CompDeclsRest: { if (node.numSubtrees() == 0) { return null; } Vector<AbsCompDecl> allCompDecls = new Vector<AbsCompDecl>(); AbsCompDecl compDecl = (AbsCompDecl) node.subtree(0).accept(this, null); allCompDecls.add(compDecl); AbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null); if (compDecls != null) { allCompDecls.addAll(compDecls.compDecls()); } Location loc = new Location(compDecl, compDecls == null ? compDecl : compDecls); return new AbsCompDecls(loc, allCompDecls); } case CompDecl: { return DeformCompDecl(node); } case Expr: case DisjExpr: case ConjExpr: case RelExpr: case AddExpr: case MulExpr: { return ExpressionTransform(node, visArg); } case DisjExprRest: case ConjExprRest: case AddExprRest: case MulExprRest: { System.out.println("Rest:" + node.label + " :" + node.numSubtrees()); if (node.numSubtrees() == 0) { System.out.println("Rest:" + "visarg" + visArg.location()); return visArg; } DerLeaf operatorNode = (DerLeaf) node.subtree(0); AbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token); if (oper == null) { throw new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees()); } AbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null); System.out.println("Rest: " + "l" + leftOperand.location()); Location loc = new Location(visArg, leftOperand); AbsBinExpr binExpr = new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand); AbsExpr rightOperand = (AbsExpr) node.subtree(2).accept(this, binExpr); System.out.println("Rest: " + leftOperand.location() + " r: " + rightOperand.location()); return rightOperand; } case RelExprRest: { System.out.println("Rest R:" + node.label + " :" + node.numSubtrees()); if (node.numSubtrees() == 0) { System.out.println("Rest R:" + "visarg" + visArg.location()); return visArg; } DerLeaf operatorNode = (DerLeaf) node.subtree(0); AbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token); if (oper == null) { throw new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees()); } AbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null); Location loc = new Location(operatorNode, visArg); return new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand); } case PrefExpr: { if (node.subtree(0) instanceof DerLeaf) { DerLeaf operatorNode = (DerLeaf) node.subtree(0); AbsUnExpr.Oper oper = kTermToUnarOper.get(operatorNode.symb.token); if (oper != null) { AbsExpr subExpr = (AbsExpr) node.subtree(1).accept(this, null); Location loc = new Location(operatorNode, subExpr); return new AbsUnExpr(loc, oper, subExpr); } if (operatorNode.symb.token == Term.NEW) { AbsType type = (AbsType) node.subtree(1).accept(this, null); Location loc = new Location(operatorNode, type); return new AbsNewExpr(loc, type); } if (operatorNode.symb.token == Term.DEL) { AbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null); Location loc = new Location(operatorNode, expr); return new AbsDelExpr(loc, expr); } } else { DerNode exprNode = (DerNode) node.subtree(0); AbsExpr expr = (AbsExpr) exprNode.accept(this, null); if (exprNode.label == Nont.Expr) { return node.subtree(1).accept(this, expr); } else if (exprNode.label == Nont.PstfExpr) { return node.subtree(1).accept(this, expr); } } } case PstfExpr: { return node.subtree(0).accept(this, null); } case AtomExpr: { if (node.numSubtrees() == 1) { return node.subtree(0).accept(this, null); } if (node.numSubtrees() == 2) { boolean isNull = node.subtree(1).accept(this, null) instanceof AbsAtomExpr && node.subtree(1).accept(this, null).location().equals(kNULL_LOCATION); if (isNull) { DerLeaf varName = (DerLeaf) node.subtree(0); Location loc = new Location(varName, varName); return new AbsVarName(loc, varName.symb.lexeme); } else { AbsArgs funArgs = (AbsArgs) node.subtree(1).accept(this, null); DerLeaf funName = (DerLeaf) node.subtree(0); Location loc = new Location(funName, funArgs); return new AbsFunName(loc, funName.symb.lexeme, funArgs); } } if (node.numSubtrees() == 3) { AbsStmts statements = (AbsStmts) node.subtree(0).accept(this, null); AbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null); AbsDecls decls = (AbsDecls) node.subtree(2).accept(this, null); Location loc = new Location(statements, decls); return new AbsBlockExpr(loc, decls, statements, expr); } } case Literal: { DerLeaf literal = (DerLeaf) node.subtree(0); return new AbsAtomExpr(literal, kTermToLitType.get(literal.symb.token), literal.symb.lexeme); } case CastEps: { if (node.numSubtrees() == 0) { return visArg; } AbsType type = (AbsType) node.subtree(0).accept(this, null); // Double check this for location Location loc = new Location(visArg, type); return new AbsCastExpr(loc, (AbsExpr) visArg, type); } case CallEps: case Args: { if (node.numSubtrees() == 0) { return Epsilon(); } return node.subtree(0).accept(this, null); } case ArgsEps: case ArgsRest: { if (node.numSubtrees() == 0) { return null; } Vector<AbsExpr> allExpr = new Vector<AbsExpr>(); AbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null); allExpr.add(expr); AbsArgs args = (AbsArgs) node.subtree(1).accept(this, null); if (args != null) { allExpr.addAll(args.args()); } Location loc = new Location(expr, args == null ? expr : args); return new AbsArgs(loc, allExpr); } case Stmts: case StmtsRest: { if (node.numSubtrees() == 0) { return null; } Vector<AbsStmt> allStmts = new Vector<AbsStmt>(); AbsStmt stmt = (AbsStmt) node.subtree(0).accept(this, null); allStmts.add(stmt); AbsStmts stmts = (AbsStmts) node.subtree(1).accept(this, null); if (stmts != null) { allStmts.addAll(stmts.stmts()); } Location loc = new Location(stmt, stmts == null ? stmt : stmts); return new AbsStmts(loc, allStmts); } case Stmt: { if (node.numSubtrees() == 2) { AbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null); return node.subtree(1).accept(this, expr); } if (node.numSubtrees() == 3) { AbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null); AbsStmts doStatements = (AbsStmts) node.subtree(2).accept(this, null); Location loc = new Location(node.subtree(0), doStatements); return new AbsWhileStmt(loc, condition, doStatements); } if (node.numSubtrees() == 4) { AbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null); AbsStmts thenStatements = (AbsStmts) node.subtree(2).accept(this, null); AbsStmts elseStatements = (AbsStmts) node.subtree(3).accept(this, null); Location loc = new Location(node.subtree(0), elseStatements); return new AbsIfStmt(loc, condition, thenStatements, elseStatements); } } case AssignEps: { if (node.numSubtrees() == 0) { return visArg; } AbsExpr rightSide = (AbsExpr) node.subtree(0).accept(this, null); Location loc = new Location(visArg, rightSide); return new AbsAssignStmt(loc, (AbsExpr) visArg, rightSide); } case ElseEps: case WhereEps: { if (node.numSubtrees() == 0) { return null; } return node.subtree(0).accept(this, null); } } // End Swithv return visArg; } // Helper function private AbsTree DeformParDecls(DerNode node) { if (node.numSubtrees() == 0) { return new AbsParDecls(kNULL_LOCATION, new Vector<AbsParDecl>()); } Vector<AbsParDecl> allParDecls = new Vector<AbsParDecl>(); AbsParDecl parDecl = (AbsParDecl) node.subtree(0).accept(this, null); allParDecls.add(parDecl); AbsParDecls parDecls = (AbsParDecls) node.subtree(1).accept(this, null); if (parDecls != null) { allParDecls.addAll(parDecls.parDecls()); } Location loc = new Location(parDecl, parDecls == null ? parDecl : parDecls); return new AbsParDecls(loc, allParDecls); } private AbsTree DeformParDecl(DerNode node) { DerLeaf identifier = (DerLeaf) node.subtree(0); AbsType type = (AbsType) node.subtree(1).accept(this, null); Location loc = new Location(identifier, type); return new AbsParDecl(loc, identifier.symb.lexeme, type); } // Same function just other class private AbsTree DeformCompDecl(DerNode node) { DerLeaf identifier = (DerLeaf) node.subtree(0); AbsType type = (AbsType) node.subtree(1).accept(this, null); Location loc = new Location(identifier, type); return new AbsCompDecl(loc, identifier.symb.lexeme, type); } private AbsTree ExpressionTransform(DerNode node, AbsTree visArg) { System.out.println(node.label + " :" + node.numSubtrees()); if (node.numSubtrees() == 0) { System.out.println("zero"); return visArg; } if (node.numSubtrees() == 1) { System.out.println("one"); return node.subtree(0).accept(this, null); } System.out.println("two"); AbsExpr leftOperand = (AbsExpr) node.subtree(0).accept(this, null); AbsExpr rightOperand = (AbsExpr) node.subtree(1).accept(this, leftOperand); System.out.println("exprTran: " + node.label + " :" + node.numSubtrees() + " l " + leftOperand.location() + " r " + rightOperand.location()); return rightOperand; } private AbsTree Epsilon() { // Hacky try to find other expr that is not abstrac and has less field return new AbsAtomExpr(kNULL_LOCATION, AbsAtomExpr.Type.VOID, ""); } private Map<Term, AbsBinExpr.Oper> kTermToBinOper = new HashMap<Term, AbsBinExpr.Oper>() { { put(Term.IOR, AbsBinExpr.Oper.IOR); put(Term.XOR, AbsBinExpr.Oper.XOR); put(Term.AND, AbsBinExpr.Oper.AND); put(Term.EQU, AbsBinExpr.Oper.EQU); put(Term.NEQ, AbsBinExpr.Oper.NEQ); put(Term.LTH, AbsBinExpr.Oper.LTH); put(Term.GTH, AbsBinExpr.Oper.GTH); put(Term.LEQ, AbsBinExpr.Oper.LEQ); put(Term.GEQ, AbsBinExpr.Oper.GEQ); put(Term.ADD, AbsBinExpr.Oper.ADD); put(Term.SUB, AbsBinExpr.Oper.SUB); put(Term.MUL, AbsBinExpr.Oper.MUL); put(Term.DIV, AbsBinExpr.Oper.DIV); put(Term.MOD, AbsBinExpr.Oper.MOD); } }; private Map<Term, AbsUnExpr.Oper> kTermToUnarOper = new HashMap<Term, AbsUnExpr.Oper>() { { put(Term.NOT, AbsUnExpr.Oper.NOT); put(Term.ADDR, AbsUnExpr.Oper.ADDR); put(Term.DATA, AbsUnExpr.Oper.DATA); put(Term.ADD, AbsUnExpr.Oper.ADD); put(Term.SUB, AbsUnExpr.Oper.SUB); } }; private Map<Term, AbsAtomExpr.Type> kTermToLitType = new HashMap<Term, AbsAtomExpr.Type>() { { put(Term.VOIDCONST, AbsAtomExpr.Type.VOID); put(Term.BOOLCONST, AbsAtomExpr.Type.BOOL); put(Term.PTRCONST, AbsAtomExpr.Type.PTR); put(Term.INTCONST, AbsAtomExpr.Type.INT); put(Term.CHARCONST, AbsAtomExpr.Type.CHAR); put(Term.STRCONST, AbsAtomExpr.Type.STR); } }; }
package hex.deeplearning; import hex.*; import hex.quantile.Quantile; import hex.quantile.QuantileModel; import hex.schemas.DeepLearningModelV3; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import water.*; import water.api.ModelSchema; import water.codegen.CodeGenerator; import water.codegen.CodeGeneratorPipeline; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.JCodeSB; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static hex.ModelMetrics.calcVarImp; import static hex.deeplearning.DeepLearning.makeDataInfo; import static water.H2O.technote; /** * The Deep Learning model * It contains a DeepLearningModelInfo with the most up-to-date model, * a scoring history, as well as some helpers to indicate the progress */ public class DeepLearningModel extends Model<DeepLearningModel,DeepLearningParameters,DeepLearningModel.DeepLearningModelOutput> implements Model.DeepFeatures { /** * The Deep Learning model output contains a few extra fields in addition to the metrics in Model.Output * 1) Scoring history (raw data) * 2) weights/biases (raw data) * 3) variable importances (TwoDimTable) */ public static class DeepLearningModelOutput extends Model.Output { public DeepLearningModelOutput() { super(); autoencoder = false;} public DeepLearningModelOutput(DeepLearning b) { super(b); autoencoder = b._parms._autoencoder; assert b.isSupervised() == !autoencoder; } final boolean autoencoder; DeepLearningScoring errors; Key[] weights; Key[] biases; double[] normmul; double[] normsub; double[] normrespmul; double[] normrespsub; int[] catoffsets; public TwoDimTable _variable_importances; @Override public ModelCategory getModelCategory() { return autoencoder ? ModelCategory.AutoEncoder : super.getModelCategory(); } @Override public boolean isSupervised() { return !autoencoder; } } /** * Deviance of given distribution function at predicted value f * @param w observation weight * @param y (actual) response * @param f (predicted) response in original response space * @return value of gradient */ @Override public double deviance(double w, double y, double f) { // Note: Must use sanitized parameters via get_params() as this._params can still have defaults AUTO, etc.) assert(get_params()._distribution != Distribution.Family.AUTO); return new Distribution(get_params()._distribution, get_params()._tweedie_power).deviance(w,y,f); } // Default publicly visible Schema is V2 public ModelSchema schema() { return new DeepLearningModelV3(); } void set_model_info(DeepLearningModelInfo mi) { assert(mi != null); model_info = mi; } final public DeepLearningModelInfo model_info() { return model_info; } final public VarImp varImp() { return _output.errors.variable_importances; } private volatile DeepLearningModelInfo model_info; // timing public long total_checkpointed_run_time_ms; //time spent in previous models public long total_training_time_ms; //total time spent running (training+scoring, including all previous models) public long total_scoring_time_ms; //total time spent scoring (including all previous models) public long total_setup_time_ms; //total time spent setting up (including all previous models) private long time_of_start_ms; //start time for this model (this cp restart) // auto-tuning public long actual_train_samples_per_iteration; public long tspiGuess; public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model // helpers for diagnostics public double epoch_counter; public int iterations; public boolean stopped_early; public long training_rows; public long validation_rows; private DeepLearningScoring[] scoringInfo; public DeepLearningScoring[] scoring_history() { return scoringInfo; } public ScoreKeeper[] scoreKeepers() { ScoreKeeper[] sk = new ScoreKeeper[scoring_history().length]; for (int i=0;i<sk.length;++i) { sk[i] = scoringInfo[i].validation ? scoringInfo[i].scored_valid : scoringInfo[i].scored_train; } return sk; } // Keep the best model so far, based on a single criterion (overall class. error or MSE) private float _bestLoss = Float.POSITIVE_INFINITY; public Key actual_best_model_key; public Key model_info_key; // return the most up-to-date model metrics DeepLearningScoring last_scored() { return scoringInfo == null ? null : scoringInfo[scoringInfo.length-1]; } /** * Get the parameters actually used for model building, not the user-given ones (_parms) * They might differ since some defaults are filled in, and some invalid combinations are auto-disabled in modifyParams * @return actually used parameters */ public final DeepLearningParameters get_params() { return model_info.get_params(); } // Lower is better public float loss() { switch (_parms._stopping_metric) { case MSE: return (float) mse(); case logloss: return (float) logloss(); case deviance: return (float) deviance(); case misclassification: return (float) classification_error(); case AUC: return (float)(1-auc()); case AUTO: default: return (float) (_output.isClassifier() ? logloss() : _output.autoencoder ? mse() : deviance()); } } @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(); case AutoEncoder: return new ModelMetricsAutoEncoder.MetricBuilderAutoEncoder(_output.nfeatures()); default: throw H2O.unimpl("Invalid ModelCategory " + _output.getModelCategory()); } } public int compareTo(DeepLearningModel o) { if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor."); if (o._output.isClassifier()) { if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes."); } return (loss() < o.loss() ? -1 : loss() > o.loss() ? 1 : 0); } public static class DeepLearningScoring extends Iced { public int iterations; public double epoch_counter; public double training_samples; public long time_stamp_ms; //absolute time the model metrics were computed public long total_training_time_ms; //total training time until this scoring event (including checkpoints) public long total_scoring_time_ms; //total scoring time until this scoring event (including checkpoints) public long total_setup_time_ms; //total setup time until this scoring event (including checkpoints) public long this_scoring_time_ms; //scoring time for this scoring event (only) boolean validation; public long score_training_samples; public long score_validation_samples; public boolean classification; VarImp variable_importances; ScoreKeeper scored_train = new ScoreKeeper(); ScoreKeeper scored_valid = new ScoreKeeper(); public AUC2 training_AUC; public AUC2 validation_AUC; DeepLearningScoring deep_clone() { AutoBuffer ab = new AutoBuffer(); this.write(ab); ab.flipForReading(); return (DeepLearningScoring) new DeepLearningScoring().read(ab); } } public double classification_error() { if (scoringInfo == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._classError : last_scored().scored_train._classError; } public double mse() { if (scoringInfo == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mse : last_scored().scored_train._mse; } public double auc() { if (scoringInfo == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._AUC : last_scored().scored_train._AUC; } public double deviance() { if (scoringInfo == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mean_residual_deviance : last_scored().scored_train._mean_residual_deviance; } public double logloss() { if (scoringInfo == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._logloss : last_scored().scored_train._logloss; } private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] scoringInfo) { List<String> colHeaders = new ArrayList<>(); List<String> colTypes = new ArrayList<>(); List<String> colFormat = new ArrayList<>(); colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Duration"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Training Speed"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Epochs"); colTypes.add("double"); colFormat.add("%.5f"); colHeaders.add("Iterations"); colTypes.add("int"); colFormat.add("%d"); colHeaders.add("Samples"); colTypes.add("double"); colFormat.add("%f"); colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Training Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Training R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Training LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Training AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Training Lift"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial || _output.getModelCategory() == ModelCategory.Multinomial) { colHeaders.add("Training Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } if (get_params()._valid != null) { colHeaders.add("Validation MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Validation Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Validation AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Validation Lift"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } } final int rows = scoringInfo.length; String[] s = new String[0]; TwoDimTable table = new TwoDimTable( "Scoring History", null, new String[rows], colHeaders.toArray(s), colTypes.toArray(s), colFormat.toArray(s), ""); int row = 0; for (DeepLearningScoring si : scoringInfo) { int col = 0; assert (row < table.getRowDim()); assert (col < table.getColDim()); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); table.set(row, col++, fmt.print(si.time_stamp_ms)); table.set(row, col++, PrettyPrint.msecs(si.total_training_time_ms, true)); // Log.info("1st speed: (samples: " + si.training_samples + ", total_run_time: " + si.total_training_time_ms + ", total_scoring_time: " + si.total_scoring_time_ms + ", total_setup_time: " + si.total_setup_time_ms + ")"); int speed = (int)(si.training_samples / ((si.total_training_time_ms - si.total_scoring_time_ms - si.total_setup_time_ms)/ 1e3)); assert(speed >= 0) : "Speed should not be negative! " + speed + " = (int)(" + si.training_samples + "/((" + si.total_training_time_ms + "-" + si.total_scoring_time_ms + "-" + si.total_setup_time_ms+")/1e3)"; table.set(row, col++, si.total_training_time_ms == 0 ? null : (String.format("%d", speed) + " rows/sec")); table.set(row, col++, si.epoch_counter); table.set(row, col++, si.iterations); table.set(row, col++, si.training_samples); table.set(row, col++, si.scored_train != null ? si.scored_train._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, si.scored_train != null ? si.scored_train._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, si.scored_train != null ? si.scored_train._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, si.scored_train != null ? si.scored_train._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, si.training_AUC != null ? si.training_AUC._auc : Double.NaN); table.set(row, col++, si.scored_train != null ? si.scored_train._lift : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, si.scored_train != null ? si.scored_train._classError : Double.NaN); } if (get_params()._valid != null) { table.set(row, col++, si.scored_valid != null ? si.scored_valid._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, si.scored_valid != null ? si.scored_valid._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, si.scored_valid != null ? si.scored_valid._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, si.scored_valid != null ? si.scored_valid._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, si.validation_AUC != null ? si.validation_AUC._auc : Double.NaN); table.set(row, col++, si.scored_valid != null ? si.scored_valid._lift : Double.NaN); } if (_output.isClassifier()) { table.set(row, col, si.scored_valid != null ? si.scored_valid._classError : Double.NaN); } } row++; } return table; } /** * Helper to allocate keys for output frames for weights and biases * @param destKey Base destination key for output frames */ private void makeWeightsBiases(Key destKey) { if (!model_info.get_params()._export_weights_and_biases) { _output.weights = null; _output.biases = null; _output.normmul = null; _output.normsub = null; _output.normrespmul = null; _output.normrespsub = null; _output.catoffsets = null; } else { _output.weights = new Key[get_params()._hidden.length + 1]; for (int i = 0; i < _output.weights.length; ++i) { _output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i)); } _output.biases = new Key[get_params()._hidden.length + 1]; for (int i = 0; i < _output.biases.length; ++i) { _output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i)); } _output.normmul = model_info.data_info._normMul; _output.normsub = model_info.data_info._normSub; _output.normrespmul = model_info.data_info._normRespMul; _output.normrespsub = model_info.data_info._normRespSub; _output.catoffsets = model_info.data_info._catOffsets; } } /** Constructor to restart from a checkpointed model * @param destKey New destination key for the model * @param parms User-given parameters for checkpoint restart * @param cp Checkpoint to restart from * @param store_best_model Store only the best model instead of the latest one */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModel cp, final boolean store_best_model, final DataInfo dataInfo) { super(destKey, parms == null ? (DeepLearningParameters)cp._parms.clone() : parms, (DeepLearningModelOutput)cp._output.clone()); assert(_parms != cp._parms); //make sure we have a clone model_info = cp.model_info.deep_clone(); //don't want to interfere with model being built, just make a deep copy and store that if (store_best_model) { model_info.data_info = dataInfo.deep_clone(); //replace previous data_info with updated version that's passed in (contains enum for classification) } else { model_info.data_info = dataInfo; //shallow clone is ok if (parms != null) { assert (_parms == parms); assert (_parms._checkpoint == parms._checkpoint); assert (_parms._checkpoint == cp._key); } // _parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy } DKV.put(dataInfo); assert(get_params() != cp.model_info().get_params()); //make sure we have a clone actual_best_model_key = cp.actual_best_model_key; time_of_start_ms = cp.time_of_start_ms; total_training_time_ms = cp.total_training_time_ms; total_checkpointed_run_time_ms = cp.total_training_time_ms; total_scoring_time_ms = cp.total_scoring_time_ms; total_setup_time_ms = cp.total_setup_time_ms; training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started validation_rows = cp.validation_rows; //copy the value to display the right number on the model page before training has started _bestLoss = cp._bestLoss; epoch_counter = cp.epoch_counter; iterations = cp.iterations; // deep clone scoring history scoringInfo = cp.scoringInfo.clone(); for (int i=0; i< scoringInfo.length;++i) scoringInfo[i] = cp.scoringInfo[i].deep_clone(); _output.errors = last_scored(); makeWeightsBiases(destKey); _output._scoring_history = createScoringHistoryTable(scoringInfo); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._names = dataInfo._adaptedFrame.names(); _output._domains = dataInfo._adaptedFrame.domains(); assert(Arrays.equals(_key._kb, destKey._kb)); } /** * Regular constructor (from scratch) * @param destKey destination key * @param parms DL parameters * @param output DL model output * @param train Training frame * @param valid Validation frame * @param nClasses Number of classes (1 for regression or autoencoder) */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid, int nClasses) { super(destKey, parms, output); final DataInfo dinfo = makeDataInfo(train, valid, _parms); _output._names = train._names ; // Since changed by DataInfo, need to be reflected in the Model output as well _output._domains= train.domains(); _output._names = dinfo._adaptedFrame.names(); _output._domains = dinfo._adaptedFrame.domains(); DKV.put(dinfo); model_info = new DeepLearningModelInfo(parms, dinfo, nClasses, train, valid); model_info_key = Key.makeUserHidden(Key.make(H2O.SELF)); actual_best_model_key = Key.makeUserHidden(Key.make(H2O.SELF)); if (parms._nfolds != 0) actual_best_model_key = null; if (!parms._autoencoder) { scoringInfo = new DeepLearningScoring[1]; scoringInfo[0] = new DeepLearningScoring(); scoringInfo[0].validation = (parms._valid != null); scoringInfo[0].time_stamp_ms = System.currentTimeMillis(); _output.errors = last_scored(); _output._scoring_history = createScoringHistoryTable(scoringInfo); _output._variable_importances = calcVarImp(last_scored().variable_importances); } time_of_start_ms = System.currentTimeMillis(); makeWeightsBiases(destKey); assert _key.equals(destKey); boolean fail = false; long byte_size = 0; try { byte_size = new AutoBuffer().put(this).buf().length; } catch(Throwable t) { fail = true; } if (byte_size > Value.MAX || fail) throw new IllegalArgumentException(technote(5, "Model is too large")); } public long _timeLastIterationEnter; public long _timeLastScoreStart; //start actual scoring private long _timeLastScoreEnd; //finished actual scoring private long _timeLastPrintStart; private void checkTimingConsistency() { assert(total_scoring_time_ms <= total_training_time_ms); assert(total_setup_time_ms <= total_training_time_ms); assert(total_setup_time_ms+total_scoring_time_ms <= total_training_time_ms); assert(total_training_time_ms >= total_checkpointed_run_time_ms); assert(total_checkpointed_run_time_ms >= 0); assert(total_training_time_ms >= 0); assert(total_scoring_time_ms >= 0); assert(_output._start_time <= System.currentTimeMillis()); assert(_output._end_time == 0); } void updateTiming(Key job_key) { final long now = System.currentTimeMillis(); long start_time_current_model = ((Job) DKV.getGet(job_key))._start_time; total_training_time_ms = total_checkpointed_run_time_ms + (now - start_time_current_model); checkTimingConsistency(); } /** * Score this DeepLearning model * @param fTrain potentially downsampled training data for scoring * @param fTest potentially downsampled validation data for scoring * @param jobKey key of the owning job * @param progressKey key of the progress * @param iteration Map/Reduce iteration count * @return true if model building is ongoing */ boolean doScoring(Frame fTrain, Frame fTest, Key jobKey, Key progressKey, int iteration, boolean finalScoring) { final long now = System.currentTimeMillis(); final double time_since_last_iter = now - _timeLastIterationEnter; updateTiming(jobKey); _timeLastIterationEnter = now; epoch_counter = (double)model_info().get_processed_total()/training_rows; boolean keep_running; // Auto-tuning // if multi-node and auto-tuning and at least 10 ms for communication (to avoid doing thins on multi-JVM on same node), // then adjust the auto-tuning parameter 'actual_train_samples_per_iteration' such that the targeted ratio of comm to comp is achieved // Note: actual communication time is estimated by the NetworkTest's collective test. if (H2O.CLOUD.size() > 1 && get_params()._train_samples_per_iteration == -2 && iteration > 1) { Log.info("Auto-tuning train_samples_per_iteration."); if (time_for_communication_us > 1e4) { Log.debug(" Time taken for communication: " + PrettyPrint.usecs((long) time_for_communication_us)); Log.debug(" Time taken for Map/Reduce iteration: " + PrettyPrint.msecs((long) time_since_last_iter, true)); final double comm_to_work_ratio = (time_for_communication_us * 1e-3) / time_since_last_iter; Log.debug(" Ratio of network communication to computation: " + String.format("%.5f", comm_to_work_ratio)); Log.debug(" target_comm_to_work: " + get_params()._target_ratio_comm_to_comp); Log.debug("Old value of train_samples_per_iteration: " + actual_train_samples_per_iteration); double correction = get_params()._target_ratio_comm_to_comp / comm_to_work_ratio; correction = Math.max(0.5,Math.min(2, correction)); //it's ok to train up to 2x more training rows per iteration, but not fewer than half. if (Math.abs(correction) < 0.8 || Math.abs(correction) > 1.2) { //don't correct unless it's significant (avoid slow drift) actual_train_samples_per_iteration /= correction; actual_train_samples_per_iteration = Math.max(1, actual_train_samples_per_iteration); Log.debug("New value of train_samples_per_iteration: " + actual_train_samples_per_iteration); } else { Log.debug("Keeping value of train_samples_per_iteration the same (would deviate too little from previous value): " + actual_train_samples_per_iteration); } } else { Log.debug("Communication is faster than 10 ms. Not modifying train_samples_per_iteration: " + actual_train_samples_per_iteration); } } keep_running = (epoch_counter < get_params()._epochs) && !stopped_early; final long sinceLastScore = now -_timeLastScoreStart; // this is potentially slow - only do every so often if( !keep_running || (sinceLastScore > get_params()._score_interval *1000 //don't score too often &&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params()._score_duty_cycle) ) { //duty cycle if (progressKey != null) { new Job.ProgressUpdate("Scoring on " + fTrain.numRows() + " training samples" + (fTest != null ? (", " + fTest.numRows() + " validation samples") : "") ).fork(progressKey); } final boolean printme = !get_params()._quiet_mode; _timeLastScoreStart = System.currentTimeMillis(); model_info().computeStats(); //might not be necessary, but is done to be certain that numbers are good DeepLearningScoring scoringInfo = new DeepLearningScoring(); scoringInfo.time_stamp_ms = _timeLastScoreStart; updateTiming(jobKey); scoringInfo.total_training_time_ms = total_training_time_ms; scoringInfo.total_scoring_time_ms = total_scoring_time_ms; scoringInfo.total_setup_time_ms = total_setup_time_ms; scoringInfo.epoch_counter = epoch_counter; scoringInfo.iterations = iterations; scoringInfo.training_samples = (double)model_info().get_processed_total(); scoringInfo.validation = fTest != null; scoringInfo.score_training_samples = fTrain.numRows(); scoringInfo.classification = _output.isClassifier(); if (get_params()._autoencoder) { if (printme) Log.info("Scoring the auto-encoder."); // training { final Frame mse_frame = scoreAutoEncoder(fTrain, Key.make(), false); mse_frame.delete(); ModelMetrics mtrain = ModelMetrics.getFromDKV(this, fTrain); //updated by model.score _output._training_metrics = mtrain; scoringInfo.scored_train = new ScoreKeeper(mtrain); } if (fTest != null) { final Frame mse_frame = scoreAutoEncoder(fTest, Key.make(), false); mse_frame.delete(); ModelMetrics mtest = ModelMetrics.getFromDKV(this, fTest); //updated by model.score _output._validation_metrics = mtest; scoringInfo.scored_valid = new ScoreKeeper(mtest); } } else { if (printme) Log.info("Scoring the model."); // compute errors final String m = model_info().toString(); if (m.length() > 0) Log.info(m); final Frame trainPredict = score(fTrain); trainPredict.delete(); hex.ModelMetrics mtrain = ModelMetrics.getFromDKV(this, fTrain); _output._training_metrics = mtrain; scoringInfo.scored_train = new ScoreKeeper(mtrain); hex.ModelMetrics mtest; hex.ModelMetricsSupervised mm1 = (ModelMetricsSupervised)mtrain; if (mm1 instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)(mm1); scoringInfo.training_AUC = mm._auc; } if (fTrain.numRows() != training_rows) { _output._training_metrics._description = "Metrics reported on temporary training frame with " + fTrain.numRows() + " samples"; } else if (fTrain._key != null && fTrain._key.toString().contains("chunks")){ _output._training_metrics._description = "Metrics reported on temporary (load-balanced) training frame"; } else { _output._training_metrics._description = "Metrics reported on full training frame"; } if (fTest != null) { Frame validPred = score(fTest); validPred.delete(); mtest = ModelMetrics.getFromDKV(this, fTest); _output._validation_metrics = mtest; scoringInfo.scored_valid = new ScoreKeeper(mtest); if (mtest != null) { if (mtest instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)mtest; scoringInfo.validation_AUC = mm._auc; } if (fTest.numRows() != validation_rows) { _output._validation_metrics._description = "Metrics reported on temporary validation frame with " + fTest.numRows() + " samples"; if (get_params()._score_validation_sampling == DeepLearningParameters.ClassSamplingMethod.Stratified) { _output._validation_metrics._description += " (stratified sampling)"; } } else if (fTest._key != null && fTest._key.toString().contains("chunks")){ _output._validation_metrics._description = "Metrics reported on temporary (load-balanced) validation frame"; } else { _output._validation_metrics._description = "Metrics reported on full validation frame"; } } } } if (get_params()._variable_importances) { if (!get_params()._quiet_mode) Log.info("Computing variable importances."); final float[] vi = model_info().computeVariableImportances(); scoringInfo.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info().data_info().coefNames(), 0, vi.length)); } _timeLastScoreEnd = System.currentTimeMillis(); long scoringTime = _timeLastScoreEnd - _timeLastScoreStart; total_scoring_time_ms += scoringTime; updateTiming(jobKey); // update the scoringInfo object to report proper speed scoringInfo.total_training_time_ms = total_training_time_ms; scoringInfo.total_scoring_time_ms = total_scoring_time_ms; scoringInfo.this_scoring_time_ms = scoringTime; // enlarge the error array by one, push latest score back if (this.scoringInfo == null) { this.scoringInfo = new DeepLearningScoring[]{scoringInfo}; } else { DeepLearningScoring[] err2 = new DeepLearningScoring[this.scoringInfo.length + 1]; System.arraycopy(this.scoringInfo, 0, err2, 0, this.scoringInfo.length); err2[err2.length - 1] = scoringInfo; this.scoringInfo = err2; } _output.errors = last_scored(); makeWeightsBiases(_key); water.util.Timer t = new Timer(); // store weights and matrices to Frames if (_output.weights != null && _output.biases != null) { for (int i = 0; i < _output.weights.length; ++i) { Frame f = model_info.get_weights(i).toFrame(_output.weights[i]); if (i==0) { f._names = model_info.data_info.coefNames(); DKV.put(f); } } for (int i = 0; i < _output.biases.length; ++i) { model_info.get_biases(i).toFrame(_output.biases[i]); } if (!_parms._quiet_mode) Log.info("Writing weights and biases to Frames took " + t.time()/1000. + " seconds."); } _output._scoring_history = createScoringHistoryTable(this.scoringInfo); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._model_summary = model_info.createSummaryTable(); // always keep a copy of the best model so far (based on the following criterion) if (!finalScoring) { if (actual_best_model_key != null && get_params()._overwrite_with_best_model && ( // if we have a best_model in DKV, then compare against its error() (unless it's a different model as judged by the network size) (DKV.get(actual_best_model_key) != null && (loss() < DKV.get(actual_best_model_key).<DeepLearningModel>get().loss() || !Arrays.equals(model_info().units, DKV.get(actual_best_model_key).<DeepLearningModel>get().model_info().units))) || // otherwise, compare against our own _bestError (DKV.get(actual_best_model_key) == null && loss() < _bestLoss) ) ) { _bestLoss = loss(); putMeAsBestModel(actual_best_model_key); } // print the freshly scored model to ASCII if (keep_running && printme) Log.info(toString()); if ((_output.isClassifier() && last_scored().scored_train._classError <= get_params()._classification_stop) || (!_output.isClassifier() && last_scored().scored_train._mse <= get_params()._regression_stop)) { Log.info("Achieved requested predictive accuracy on the training data. Model building completed."); stopped_early = true; } if (ScoreKeeper.earlyStopping(scoreKeepers(), get_params()._stopping_rounds, _output.isClassifier(), get_params()._stopping_metric, get_params()._stopping_tolerance )) { Log.info("Convergence detected based on simple moving average of the loss function for the past " + get_params()._stopping_rounds + " scoring events. Model building completed."); stopped_early = true; } if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(scoringInfo.this_scoring_time_ms, true)); } } if (stopped_early) { // pretend as if we finished all epochs to get the progress bar pretty (especially for N-fold and grid-search) ((Job) DKV.getGet(jobKey)).update((long) (_parms._epochs * training_rows)); update(jobKey); return false; } progressUpdate(progressKey, jobKey, keep_running); update(jobKey); return keep_running; } private void progressUpdate(Key progressKey, Key job_key, boolean keep_running) { updateTiming(job_key); Job.Progress prog = DKV.getGet(progressKey); double progress = prog == null ? 0 : prog.progress(); // Log.info("2nd speed: (samples: " + model_info().get_processed_total() + ", total_run_time: " + total_training_time_ms + ", total_scoring_time: " + total_scoring_time_ms + ", total_setup_time: " + total_setup_time_ms + ")"); int speed = (int)(model_info().get_processed_total() * 1000. / (total_training_time_ms -total_scoring_time_ms-total_setup_time_ms)); assert(speed >= 0) : "negative speed computed! (total_run_time: " + total_training_time_ms + ", total_scoring_time: " + total_scoring_time_ms + ", total_setup_time: " + total_setup_time_ms + ")"; String msg = "Iterations: " + String.format("%,d", iterations) + ". Epochs: " + String.format("%g", epoch_counter) + ". Speed: " + String.format("%,d", speed) + " samples/sec." + (progress == 0 ? "" : " Estimated time left: " + PrettyPrint.msecs((long) (total_training_time_ms * (1. - progress) / progress), true)); ((Job) DKV.getGet(job_key)).update(actual_train_samples_per_iteration); //mark the amount of work done for the progress bar if (progressKey != null) new Job.ProgressUpdate(msg).fork(progressKey); //update the message for the progress bar long now = System.currentTimeMillis(); long sinceLastPrint = now -_timeLastPrintStart; if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle _timeLastPrintStart = now; if (!get_params()._quiet_mode) { Log.info( "Training time: " + PrettyPrint.msecs(total_training_time_ms, true) + " (scoring: " + PrettyPrint.msecs(total_scoring_time_ms, true) + "). " + "Processed " + String.format("%,d", model_info().get_processed_total()) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs).\n"); Log.info(msg); } } } /** Make either a prediction or a reconstruction. * @param orig Test dataset * @param adaptedFr Test dataset, adapted to the model * @return A frame containing the prediction or reconstruction */ @Override protected Frame predictScoreImpl(Frame orig, Frame adaptedFr, String destination_key) { if (!get_params()._autoencoder) { return super.predictScoreImpl(orig, adaptedFr, destination_key); } else { // Reconstruction final int len = model_info().data_info().fullN(); assert(model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert(len == coefnames.length); String[] names = new String[len]; for(int i = 0; i < names.length; ++i) { names[i] = "reconstr_" + coefnames[i]; } Frame f = new MRTask() { @Override public void map( Chunk chks[], NewChunk recon[] ) { double tmp [] = new double[_output._names.length]; double preds[] = new double [len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { double p[] = score_autoencoder(chks, row, tmp, preds, neurons, true /*reconstruction*/, false /*reconstruction_error_per_feature*/); for( int c=0; c<len; c++ ) recon[c].addNum(p[c]); } } }.doAll(len, Vec.T_NUM, adaptedFr).outputFrame(); Frame of = new Frame((null == destination_key ? Key.make() : Key.make(destination_key)), names, f.vecs()); DKV.put(of); makeMetricBuilder(null).makeModelMetrics(this, orig, null, null); return of; } } @Override protected double[] score0(double[] data, double[] preds) { return score0(data, preds, 1, 0); } /** * Compute the loss function * @param myRows Mini-Batch Array of denseRow's containing numerical/categorical predictor and response data (standardized) * @return loss */ public double loss(DataInfo.Row[] myRows) { double loss = 0; Neurons[] neurons = DeepLearningTask.makeNeuronsForTraining(model_info()); for (DataInfo.Row myRow : myRows) { if (myRow == null) continue; long seed = -1; //ignored // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } ((Neurons.Input)neurons[0]).setInput(seed, myRow.numIds, myRow.numVals, myRow.nBins, myRow.binIds); DeepLearningTask.step(seed, neurons, model_info(), null, false, null, myRow.offset); // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } if (get_params()._loss == DeepLearningParameters.Loss.CrossEntropy) { if (_parms._balance_classes) throw H2O.unimpl(); int actual = (int) myRow.response[0]; double pred = neurons[neurons.length - 1]._a.get(actual); loss += -Math.log(Math.max(1e-15, pred)); //cross-entropy (same as log loss) } else { if (model_info.get_params()._autoencoder) throw H2O.unimpl(); //prediction and actual response in standardized response space double pred = neurons[neurons.length - 1]._a.get(0); double actual = myRow.response[0]; // FIXME: re-enable this such that the loss is computed from the de-standardized prediction/response //bring standardized prediction and actual response to real space // DataInfo di = model_info().data_info(); // if (di._normRespMul != null) { //either both are null or none // pred = (pred / di._normRespMul[0] + di._normRespSub[0]); // actual = (actual / di._normRespMul[0] + di._normRespSub[0]); Distribution dist = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power); pred = dist.linkInv(pred); loss += 0.5 * dist.deviance(1 /*weight*/, actual, pred); } // add L1/L2 penalty of model coefficients (weights & biases) for (int i = 0; i < _parms._hidden.length + 1; ++i) { if (neurons[i]._w == null) continue; for (int row = 0; row < neurons[i]._w.rows(); ++row) { for (int col = 0; col < neurons[i]._w.cols(); ++col) { loss += _parms._l1 * Math.abs(neurons[i]._w.get(row, col)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._w.get(row, col), 2); } } for (int row = 0; row < neurons[i]._b.size(); ++row) { loss += _parms._l1 * Math.abs(neurons[i]._b.get(row)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._b.get(row), 2); } } } return loss; } /** * Predict from raw double values representing the data * @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs * @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs * @return preds, can contain NaNs */ @Override public double[] score0(double[] data, double[] preds, double weight, double offset) { if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); ((Neurons.Input)neurons[0]).setInput(-1, data); DeepLearningTask.step(-1, neurons, model_info, null, false, null, offset); double[] out = neurons[neurons.length - 1]._a.raw(); if (_output.isClassifier()) { assert (preds.length == out.length + 1); for (int i = 0; i < preds.length - 1; ++i) { preds[i + 1] = out[i]; if (Double.isNaN(preds[i + 1])) throw new RuntimeException("Predicted class probability NaN!"); } // label assignment happens later - explicitly mark it as invalid here preds[0] = -1; } else { if (model_info().data_info()._normRespMul != null) //either both are null or none preds[0] = (out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]); else preds[0] = out[0]; // transform prediction to response space preds[0] = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInv(preds[0]); if (Double.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!"); } return preds; } /** * Score auto-encoded reconstruction (on-the-fly, without allocating the reconstruction as done in Frame score(Frame fr)) * @param frame Original data (can contain response, will be ignored) * @param destination_key Frame Id for output * @param reconstruction_error_per_feature whether to return the squared error per feature * @return Frame containing one Vec with reconstruction error (MSE) of each reconstructed row, caller is responsible for deletion */ public Frame scoreAutoEncoder(Frame frame, Key destination_key, final boolean reconstruction_error_per_feature) { if (!get_params()._autoencoder) throw new H2OIllegalArgumentException("Only for AutoEncoder Deep Learning model.", ""); final int len = _output._names.length; Frame adaptFrm = new Frame(frame); adaptTestForTrain(adaptFrm, true, false); final int outputcols = reconstruction_error_per_feature ? model_info.data_info.fullN() : 1; Frame mse = new MRTask() { @Override public void map( Chunk chks[], NewChunk[] mse ) { double tmp [] = new double[len]; double out[] = new double[outputcols]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); score_autoencoder(tmp, out, neurons, false /*reconstruction*/, reconstruction_error_per_feature); for (int i=0; i<outputcols; ++i) mse[i].addNum(out[i]); } } }.doAll(outputcols, Vec.T_NUM, adaptFrm).outputFrame(); String[] names; if (reconstruction_error_per_feature) { String[] coefnames = model_info().data_info().coefNames(); assert (outputcols == coefnames.length); names = new String[outputcols]; for (int i = 0; i < names.length; ++i) { names[i] = "reconstr_" + coefnames[i] + ".SE"; } } else { names = new String[]{"Reconstruction.MSE"}; } Frame res = new Frame(destination_key, names, mse.vecs()); DKV.put(res); _output.addModelMetrics(new ModelMetricsAutoEncoder(this, frame, res.vecs()[0].mean() /*mean MSE*/)); return res; } /** * Score auto-encoded reconstruction (on-the-fly, and materialize the deep features of given layer * @param frame Original data (can contain response, will be ignored) * @param layer index of the hidden layer for which to extract the features * @return Frame containing the deep features (#cols = hidden[layer]) */ public Frame scoreDeepFeatures(Frame frame, final int layer) { if (layer < 0 || layer >= model_info().get_params()._hidden.length) throw new H2OIllegalArgumentException("hidden layer (index) to extract must be between " + 0 + " and " + (model_info().get_params()._hidden.length-1),""); final int len = _output.nfeatures(); Vec resp = null; if (isSupervised()) { int ridx = frame.find(_output.responseName()); if (ridx != -1) { // drop the response for scoring! frame = new Frame(frame); resp = frame.vecs()[ridx]; frame.remove(ridx); } } Frame adaptFrm = new Frame(frame); //create new features, will be dense final int features = model_info().get_params()._hidden[layer]; Vec v = adaptFrm.anyVec(); Vec[] vecs = v!=null ? v.makeZeros(features) : null; if (vecs == null) throw new IllegalArgumentException("Cannot create deep features from a frame with no columns."); Scope.enter(); adaptTestForTrain(_output._names, _output.weightsName(), _output.offsetName(), _output.foldName(), null /*don't skip response*/, _output._domains, adaptFrm, _parms.missingColumnsType(), true, true); for (int j=0; j<features; ++j) { adaptFrm.add("DF.L"+(layer+1)+".C" + (j+1), vecs[j]); } new MRTask() { @Override public void map( Chunk chks[] ) { double tmp [] = new double[len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); ((Neurons.Input)neurons[0]).setInput(-1, tmp); //FIXME: No weights yet DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); double[] out = neurons[layer+1]._a.raw(); //extract the layer-th hidden feature for( int c=0; c<features; c++ ) chks[_output._names.length+c].set(row,out[c]); } } }.doAll(adaptFrm); // Return just the output columns int x=_output._names.length, y=adaptFrm.numCols(); Frame ret = adaptFrm.extractFrame(x, y); if (resp != null) ret.prepend(_output.responseName(), resp); Scope.exit(); return ret; } // Make (potentially expanded) reconstruction private double[] score_autoencoder(Chunk[] chks, int row_in_chunk, double[] tmp, double[] preds, Neurons[] neurons, boolean reconstruction, boolean reconstruction_error_per_feature) { assert(get_params()._autoencoder); assert(tmp.length == _output._names.length); for (int i=0; i<tmp.length; i++ ) tmp[i] = chks[i].atd(row_in_chunk); score_autoencoder(tmp, preds, neurons, reconstruction, reconstruction_error_per_feature); // this fills preds, returns MSE error (ignored here) return preds; } /** * Helper to reconstruct original data into preds array and compute the reconstruction error (MSE) * @param data Original data (unexpanded) * @param preds Reconstruction (potentially expanded) * @param neurons Array of neurons to work with (will call fprop on them) */ private void score_autoencoder(double[] data, double[] preds, Neurons[] neurons, boolean reconstruction, boolean reconstruction_error_per_feature) { assert(model_info().get_params()._autoencoder); if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } ((Neurons.Input)neurons[0]).setInput(-1, data); DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); // reconstructs data in expanded space double[] in = neurons[0]._a.raw(); //input (expanded) double[] out = neurons[neurons.length - 1]._a.raw(); //output (expanded) assert(in.length == out.length); if (reconstruction) { // Now scale back numerical columns to original data space (scale + shift) model_info().data_info().unScaleNumericals(out, out); //only modifies the numericals System.arraycopy(out, 0, preds, 0, out.length); //copy reconstruction into preds } else if (reconstruction_error_per_feature){ // Compute SE of reconstruction in expanded space for each feature for (int i = 0; i < in.length; ++i) preds[i] = Math.pow((out[i] - in[i]), 2); } else { // Compute MSE of reconstruction in expanded space assert(preds.length == 1); double l2 = 0; for (int i = 0; i < in.length; ++i) l2 += Math.pow((out[i] - in[i]), 2); l2 /= in.length; preds[0] = l2; } } /** * Compute quantile-based threshold (in reconstruction error) to find outliers * @param mse Vector containing reconstruction errors * @param quantile Quantile for cut-off * @return Threshold in MSE value for a point to be above the quantile */ public double calcOutlierThreshold(Vec mse, double quantile) { Frame mse_frame = new Frame(Key.make(), new String[]{"Reconstruction.MSE"}, new Vec[]{mse}); DKV.put(mse_frame._key, mse_frame); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = mse_frame._key; parms._probs = new double[]{quantile}; Job<QuantileModel> job = new Quantile(parms).trainModel(); QuantileModel kmm = job.get(); job.remove(); double q = kmm._output._quantiles[0][0]; kmm.delete(); DKV.remove(mse_frame._key); return q; } // helper to push this model to another key (for keeping good models) private void putMeAsBestModel(Key bestModelKey) { DeepLearningModel bestModel = new DeepLearningModel(bestModelKey, null, this, true, model_info().data_info()); DKV.put(bestModel._key, bestModel); if (model_info().get_params()._elastic_averaging) { DeepLearningModelInfo eamodel = DKV.getGet(model_info.elasticAverageModelInfoKey()); if (eamodel != null) DKV.put(bestModel.model_info().elasticAverageModelInfoKey(), eamodel); } assert (DKV.get(bestModelKey) != null); assert (bestModel.compareTo(this) <= 0); } @Override public void delete() { if (_output.weights != null && _output.biases != null) { for (Key k : _output.weights) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } for (Key k : _output.biases) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } } DKV.remove(model_info().data_info()._key); deleteElasticAverageModels(); super.delete(); } void deleteElasticAverageModels() { if (model_info().get_params()._elastic_averaging) { DKV.remove(model_info().elasticAverageModelInfoKey()); for (H2ONode node : H2O.CLOUD._memary) { DKV.remove(model_info().localModelInfoKey(node)); } } } private String getHeader() { assert get_params()._autoencoder; StringBuilder sb = new StringBuilder(); final int len = model_info().data_info().fullN(); String prefix = "reconstr_"; assert (model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert (len == coefnames.length); for (int c = 0; c < len; c++) { if (c>0) sb.append(","); sb.append(prefix).append(coefnames[c]); } return sb.toString(); } @Override protected SBPrintStream toJavaInit(SBPrintStream sb, CodeGeneratorPipeline fileCtx) { sb = super.toJavaInit(sb, fileCtx); final String mname = JCodeGen.toJavaId(_key.toString()); final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info()); final DeepLearningParameters p = model_info.get_params(); sb.ip("public boolean isSupervised() { return " + isSupervised() + "; }").nl(); sb.ip("public int nfeatures() { return "+_output.nfeatures()+"; }").nl(); sb.ip("public int nclasses() { return "+ (p._autoencoder ? neurons[neurons.length-1].units : _output.nclasses()) + "; }").nl(); if (model_info().data_info()._nums > 0) { JCodeGen.toStaticVarZeros(sb, "NUMS", new double[model_info().data_info()._nums], "Workspace for storing numerical input variables."); JCodeGen.toClassWithArray(sb, "static", "NORMMUL", model_info().data_info()._normMul);//, "Standardization/Normalization scaling factor for numerical variables."); JCodeGen.toClassWithArray(sb, "static", "NORMSUB", model_info().data_info()._normSub);//, "Standardization/Normalization offset for numerical variables."); } if (model_info().data_info()._cats > 0) { JCodeGen.toStaticVar(sb, "CATS", new int[model_info().data_info()._cats], "Workspace for storing categorical input variables."); } JCodeGen.toStaticVar(sb, "CATOFFSETS", model_info().data_info()._catOffsets, "Workspace for categorical offsets."); if (model_info().data_info()._normRespMul != null) { JCodeGen.toStaticVar(sb, "NORMRESPMUL", model_info().data_info()._normRespMul, "Standardization/Normalization scaling factor for response."); JCodeGen.toStaticVar(sb, "NORMRESPSUB", model_info().data_info()._normRespSub, "Standardization/Normalization offset for response."); } if (p._hidden_dropout_ratios != null) { JCodeGen.toStaticVar(sb, "HIDDEN_DROPOUT_RATIOS", p._hidden_dropout_ratios, "Hidden layer dropout ratios."); } final int[] layers = new int[neurons.length]; for (int i=0;i<neurons.length;++i) layers[i] = neurons[i].units; JCodeGen.toStaticVar(sb, "NEURONS", layers, "Number of neurons for each layer."); if (get_params()._autoencoder) { sb.i(1).p("public int getPredsSize() { return " + model_info.units[model_info.units.length-1] + "; }").nl(); sb.i(1).p("public boolean isAutoEncoder() { return true; }").nl(); sb.i(1).p("public String getHeader() { return \"" + getHeader() + "\"; }").nl(); } // Generate activation storage sb.i(1).p("// Storage for neuron activation values.").nl(); sb.i(1).p("public static final double[][] ACTIVATION = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Activation_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); } sb.i(1).p("};").nl(); fileCtx.add(new CodeGenerator() { @Override public void generate(JCodeSB out) { for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Activation_"+i; out.i().p("// Neuron activation values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); JCodeGen.toClassWithArray(out, null, colInfoClazz, new double[layers[i]]); } } }); // biases sb.i(1).p("// Neuron bias values.").nl(); sb.i(1).p("public static final double[][] BIAS = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Bias_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); } sb.i(1).p("};").nl(); // Generate additonal classes fileCtx.add(new CodeGenerator() { @Override public void generate(JCodeSB out) { for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Bias_"+i; out.i().p("// Neuron bias values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); double[] bias = i == 0 ? null : new double[model_info().get_biases(i-1).size()]; if (i>0) { for (int j=0; j<bias.length; ++j) bias[j] = model_info().get_biases(i-1).get(j); } JCodeGen.toClassWithArray(out, null, colInfoClazz, bias); } } }); // Weights sb.i(1).p("// Connecting weights between neurons.").nl(); sb.i(1).p("public static final float[][] WEIGHT = new float[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Weight_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); } sb.i(1).p("};").nl(); // Generate weight classes fileCtx.add(new CodeGenerator() { @Override public void generate(JCodeSB out) { for (int i = 0; i < neurons.length; i++) { String colInfoClazz = mname + "_Weight_" + i; if (i > 0) { out.i().p("// Neuron weights connecting "). p(neurons[i - 1].getClass().getSimpleName()).p(" and "). p(neurons[i].getClass().getSimpleName()). p(" layer").nl(); } float[] weights = i == 0 ? null : new float[model_info().get_weights(i - 1).rows() * model_info() .get_weights(i - 1).cols()]; if (i > 0) { final int rows = model_info().get_weights(i - 1).rows(); final int cols = model_info().get_weights(i - 1).cols(); for (int j = 0; j < rows; ++j) for (int k = 0; k < cols; ++k) weights[j * cols + k] = model_info().get_weights(i - 1).get(j, k); } JCodeGen.toClassWithArray(out, null, colInfoClazz, weights); } } }); return sb; } @Override protected boolean toJavaCheckTooBig() { return (model_info.size() > 1e6); } private SBPrintStream pureMatVec(final SBPrintStream bodySb) { bodySb.i(1).p("int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(1).p("int rows = ACTIVATION[i].length;").nl(); bodySb.i(1).p("int extra=cols-cols%8;").nl(); bodySb.i(1).p("int multiple = (cols/8)*8-1;").nl(); bodySb.i(1).p("int idx = 0;").nl(); bodySb.i(1).p("float[] a = WEIGHT[i];").nl(); bodySb.i(1).p("double[] x = ACTIVATION[i-1];").nl(); bodySb.i(1).p("double[] y = BIAS[i];").nl(); bodySb.i(1).p("double[] res = ACTIVATION[i];").nl(); bodySb.i(1).p("for (int row=0; row<rows; ++row) {").nl(); bodySb.i(2).p("double psum0 = 0, psum1 = 0, psum2 = 0, psum3 = 0, psum4 = 0, psum5 = 0, psum6 = 0, psum7 = 0;").nl(); bodySb.i(2).p("for (int col = 0; col < multiple; col += 8) {").nl(); bodySb.i(3).p("int off = idx + col;").nl(); bodySb.i(3).p("psum0 += a[off ] * x[col ];").nl(); bodySb.i(3).p("psum1 += a[off + 1] * x[col + 1];").nl(); bodySb.i(3).p("psum2 += a[off + 2] * x[col + 2];").nl(); bodySb.i(3).p("psum3 += a[off + 3] * x[col + 3];").nl(); bodySb.i(3).p("psum4 += a[off + 4] * x[col + 4];").nl(); bodySb.i(3).p("psum5 += a[off + 5] * x[col + 5];").nl(); bodySb.i(3).p("psum6 += a[off + 6] * x[col + 6];").nl(); bodySb.i(3).p("psum7 += a[off + 7] * x[col + 7];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("res[row] += psum0 + psum1 + psum2 + psum3;").nl(); bodySb.i(2).p("res[row] += psum4 + psum5 + psum6 + psum7;").nl(); bodySb.i(2).p("for (int col = extra; col < cols; col++)").nl(); bodySb.i(3).p("res[row] += a[idx + col] * x[col];").nl(); bodySb.i(2).p("res[row] += y[row];").nl(); bodySb.i(2).p("idx += cols;").nl(); bodySb.i(1).p("}").nl(); return bodySb; } @Override protected void toJavaPredictBody(SBPrintStream bodySb, CodeGeneratorPipeline classCtx, CodeGeneratorPipeline fileCtx, final boolean verboseCode) { final DeepLearningParameters p = model_info.get_params(); bodySb.i().p("java.util.Arrays.fill(preds,0);").nl(); final int cats = model_info().data_info()._cats; final int nums = model_info().data_info()._nums; // initialize input layer if (nums > 0) bodySb.i().p("java.util.Arrays.fill(NUMS,0);").nl(); if (cats > 0) bodySb.i().p("java.util.Arrays.fill(CATS,0);").nl(); bodySb.i().p("int i = 0, ncats = 0;").nl(); if (cats > 0) { bodySb.i().p("for(; i<"+cats+"; ++i) {").nl(); bodySb.i(1).p("if (!Double.isNaN(data[i])) {").nl(); bodySb.i(2).p("int c = (int) data[i];").nl(); if (model_info().data_info()._useAllFactorLevels) bodySb.i(2).p("CATS[ncats++] = c + CATOFFSETS[i];").nl(); else bodySb.i(2).p("if (c != 0) CATS[ncats++] = c + CATOFFSETS[i] - 1;").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } if (nums > 0) { bodySb.i().p("final int n = data.length;").nl(); bodySb.i().p("for(; i<n; ++i) {").nl(); bodySb.i(1).p("NUMS[i" + (cats > 0 ? "-" + cats : "") + "] = Double.isNaN(data[i]) ? 0 : "); if (model_info().data_info()._normMul != null) { bodySb.p("(data[i] - NORMSUB.VALUES[i" + (cats > 0 ? "-" + cats : "") + "])*NORMMUL.VALUES[i" + (cats > 0 ? "-" + cats : "") + "];").nl(); } else { bodySb.p("data[i];").nl(); } bodySb.i(0).p("}").nl(); } bodySb.i().p("java.util.Arrays.fill(ACTIVATION[0],0);").nl(); if (cats > 0) { bodySb.i().p("for (i=0; i<ncats; ++i) ACTIVATION[0][CATS[i]] = 1;").nl(); } if (nums > 0) { bodySb.i().p("for (i=0; i<NUMS.length; ++i) {").nl(); bodySb.i(1).p("ACTIVATION[0][CATOFFSETS[CATOFFSETS.length-1] + i] = Double.isNaN(NUMS[i]) ? 0 : NUMS[i];").nl(); bodySb.i().p("}").nl(); } boolean tanh=(p._activation == DeepLearningParameters.Activation.Tanh || p._activation == DeepLearningParameters.Activation.TanhWithDropout); boolean relu=(p._activation == DeepLearningParameters.Activation.Rectifier || p._activation == DeepLearningParameters.Activation.RectifierWithDropout); boolean maxout=(p._activation == DeepLearningParameters.Activation.Maxout || p._activation == DeepLearningParameters.Activation.MaxoutWithDropout); final String stopping = p._autoencoder ? "(i<=ACTIVATION.length-1)" : "(i<ACTIVATION.length-1)"; // make prediction: forward propagation bodySb.i().p("for (i=1; i<ACTIVATION.length; ++i) {").nl(); bodySb.i(1).p("java.util.Arrays.fill(ACTIVATION[i],0);").nl(); if (maxout) { bodySb.i(1).p("int _k = 2; // channels").nl(); bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("double[] channel = new double[_k];").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); bodySb.i(3).p("final int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(3).p("short maxK = 0;").nl(); bodySb.i(3).p("for (short k = 0; k < _k; ++k) {").nl(); bodySb.i(4).p("channel[k] = 0;").nl(); bodySb.i(4).p("for (int c=0; c<cols; ++c) {").nl(); bodySb.i(5).p("channel[k] += WEIGHT[i][_k*(r * cols + c) + k] * ACTIVATION[i-1][c];").nl(); bodySb.i(4).p("}").nl(); bodySb.i(4).p("channel[k] += BIAS[i][_k*r+k];").nl(); bodySb.i(4).p("if (channel[k] > channel[maxK]) maxK=k;").nl(); bodySb.i(3).p("}").nl(); bodySb.i(3).p("ACTIVATION[i][r] = channel[maxK];").nl(); } else { // optimized pureMatVec(bodySb); // Activation function bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); if (tanh) { bodySb.i(3).p("ACTIVATION[i][r] = 1 - 2 / (1 + Math.exp(2*ACTIVATION[i][r]));").nl(); } else if (relu) { bodySb.i(3).p("ACTIVATION[i][r] = Math.max(0, ACTIVATION[i][r]);").nl(); } } if (p._hidden_dropout_ratios != null) { bodySb.i(3).p("if (i<ACTIVATION.length-1) {").nl(); bodySb.i(4).p("ACTIVATION[i][r] *= HIDDEN_DROPOUT_RATIOS[i-1];").nl(); bodySb.i(3).p("}").nl(); } bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); if (maxout) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); pureMatVec(bodySb); bodySb.i(1).p("}").nl(); } if (_output.isClassifier()) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // softmax bodySb.i(2).p("double max = ACTIVATION[i][0];").nl(); bodySb.i(2).p("for (int r=1; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (ACTIVATION[i][r]>max) max = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("double scale = 0;").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("ACTIVATION[i][r] = Math.exp(ACTIVATION[i][r] - max);").nl(); bodySb.i(3).p("scale += ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, predicted NaN.\");").nl(); bodySb.i(3).p("ACTIVATION[i][r] /= scale;").nl(); bodySb.i(3).p("preds[r+1] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else if (!p._autoencoder) { //Regression bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // regression: set preds[1], FillPreds0 will put it into preds[0] if (model_info().data_info()._normRespMul != null) { bodySb.i(2).p("preds[1] = (ACTIVATION[i][0] / NORMRESPMUL[0] + NORMRESPSUB[0]);").nl(); } else { bodySb.i(2).p("preds[1] = ACTIVATION[i][0];").nl(); } bodySb.i(2).p("preds[1] = " + new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInvString("preds[1]")+";").nl(); bodySb.i(2).p("if (Double.isNaN(preds[1])) throw new RuntimeException(\"Predicted regression target NaN!\");").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else { //AutoEncoder bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, reconstructed NaN.\");").nl(); bodySb.i(3).p("preds[r] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); if (model_info().data_info()._nums > 0) { int ns = model_info().data_info().numStart(); bodySb.i(2).p("for (int k=" + ns + "; k<" + model_info().data_info().fullN() + "; ++k) {").nl(); bodySb.i(3).p("preds[k] = preds[k] / NORMMUL.VALUES[k-" + ns + "] + NORMSUB.VALUES[k-" + ns + "];").nl(); bodySb.i(2).p("}").nl(); } bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); // DEBUGGING // bodySb.i().p("System.out.println(java.util.Arrays.toString(data));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[0]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[ACTIVATION.length-1]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(preds));").nl(); // bodySb.i().p("System.out.println(\"\");").nl(); } if (_output.autoencoder) return; if (_output.isClassifier()) { if (_parms._balance_classes) bodySb.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl(); bodySb.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, PRIOR_CLASS_DISTRIB, data, " + defaultThreshold()+");").nl(); } else { bodySb.ip("preds[0] = preds[1];").nl(); } } private final String unstable_msg = technote(4, "\n\nTrying to predict with an unstable model." + "\nJob was aborted due to observed numerical instability (exponential growth)." + "\nEither the weights or the bias values are unreasonably large or lead to large activation values." + "\nTry a different initial distribution, a bounded activation function (Tanh), adding regularization" + "\n(via max_w2, l1, l2, dropout) or learning rate (either enable adaptive_rate or use a smaller learning rate or faster annealing)."); @Override protected long checksum_impl() { return super.checksum_impl() * model_info.checksum_impl(); } }
package app.hongs.serv.matrix; import app.hongs.Cnst; import app.hongs.Core; import app.hongs.HongsException; import app.hongs.action.ActionHelper; import app.hongs.action.FormSet; import app.hongs.action.NaviMap; import app.hongs.db.DB; import app.hongs.db.Model; import app.hongs.db.Table; import app.hongs.db.util.FetchCase; import app.hongs.util.Data; import app.hongs.util.Dict; import app.hongs.util.Synt; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author Hongs */ public class Form extends Model { protected String prefix = "centra/data"; public Form() throws HongsException { this(DB.getInstance("matrix").getTable("form")); } public Form(Table table) throws HongsException { super(table); } @Override public int put(String id, Map rd) throws HongsException { List<Map> fds = parseConf(rd); String name = (String) rd.get( "name" ); if (!rd.containsKey("state") && !fetchCase() .field("id") .where("id = ? AND state = ?", id, 2 ) .one ( ) .isEmpty( )) { throw new HongsException(0x1100, ", "); } int an = superPut (id, rd ); if (fds != null) { updateFormConf(id, fds); } if (name != null) { updateFormMenu(id, name); } return an; } @Override public int add(String id, Map rd) throws HongsException { List<Map> fds = parseConf(rd); String name = (String) rd.get( "name" ); String unitId = (String) rd.get( "unit_id" ); String unitNm = (String) db.getTable("unit") .filter ("id = ?", unitId) .select ("name") .one () .get ("name"); int an = superAdd (id, rd ); if (fds != null) { updateFormConf(id, fds); } if (name != null) { updateFormMenu(id, name); } updateUnitMenu(unitId, unitNm); insertAuthRole(id); return an; } @Override public int del(String id, FetchCase fc) throws HongsException { String unitId = (String) db.getTable("form") .filter ("id = ?", id) .select ("unit_id") .one () .get ("unit_id"); String unitNm = (String) db.getTable("unit") .filter ("id = ?", unitId) .select ("name") .one () .get ("name"); int n = super.del(id,fc); deleteFormConf(id); deleteFormMenu(id); updateUnitMenu(unitId, unitNm); deleteAuthRole(id); return n; } protected final int superAdd(String id, Map rd) throws HongsException { return super.add(id, rd); } protected final int superPut(String id, Map rd) throws HongsException { return super.put(id, rd); } protected final int superDel(String id, FetchCase fc) throws HongsException { return super.del(id, fc); } protected List<Map> parseConf(Map rd) { List<Map> flds = null; String conf = (String) rd.get("conf"); String name = (String) rd.get("name"); if (conf != null && !"".equals(conf)) { flds = Synt.asList(Data.toObject(conf)); Set set = Synt.setOf("name", "find", "cuid", "muid", "ctime", "mtime"); Map tdf = null; Map idf = null; Map fld ; Iterator<Map> itr = flds.iterator(); while (itr.hasNext()) { fld = itr.next(); if ( "".equals(fld.get("__name__"))) { fld.put("__name__", Core.newIdentity()); } else if ( "@".equals(fld.get("__name__"))) { tdf = fld; itr. remove ( ); } else if ( "id".equals(fld.get("__name__"))) { idf = fld; itr. remove ( ); } else if (set.contains(fld.get("__name__"))) { set. remove (fld.get("__name__")); } } if (tdf != null) { flds.add(0, tdf); tdf.remove("__text__"); tdf.remove("__type__"); tdf.remove("__rule__"); tdf.remove("__required__"); tdf.remove("__repeated__"); } if (idf != null) { flds.add(1, idf); idf.remove("__required__"); idf.remove("__repeated__"); } conf = Data.toString(flds); rd.put("conf", conf); fld = Synt.mapOf( "__text__", name, "__name__", "@", "listable", "?", "sortable", "?", "siftable", "?", "nameable", "?" ); if (tdf != null) { fld .putAll(tdf); tdf .putAll(fld); } else { flds.add(0, fld); } fld = Synt.mapOf( "__text__", "ID", "__name__", "id", "__type__", "hidden" ); if (idf != null) { fld .putAll(idf); idf .putAll(fld); } else { flds.add(1, fld); } if (set.contains("name")) { flds.add(Synt.mapOf( "__name__", "name", "__type__", "stored", "editable", "false" )); } if (set.contains("find")) { flds.add(Synt.mapOf( "__name__", "find", "__type__", "search", "editable", "false" , "unstored", "true" )); } if (set.contains("cuid")) { flds.add(Synt.mapOf( "__name__", "cuid", "__type__", "hidden", "editable", "false" , "default" , "=$uid" , "default-always", "true", "default-create", "true" )); } if (set.contains("muid")) { flds.add(Synt.mapOf( "__name__", "muid", "__type__", "hidden", "editable", "false" , "default" , "=$uid" , "default-always", "true", "default-create", "false" )); } if (set.contains("ctime")) { flds.add(Synt.mapOf( "__name__", "ctime" , "__type__", "number", "type" , "long" , "editable", "false" , "default" , "=%now" , "default-always", "true", "default-create", "true" )); } if (set.contains("mtime")) { flds.add(Synt.mapOf( "__name__", "mtime" , "__type__", "number", "type" , "long" , "editable", "false" , "default" , "=%now" , "default-always", "true", "default-create", "false" )); } } else { rd.remove("conf"); } return flds; } @Override protected void filter(FetchCase caze, Map rd) throws HongsException { super.filter(caze, rd); ActionHelper helper = Core.getInstance (ActionHelper.class); String uid = ( String ) helper.getSessibute( Cnst.UID_SES ); if (Cnst.ADM_UID.equals(uid)) { return; } String pm = prefix + "/"; String mm = caze.getOption("MODEL_START", ""); if ("getList".equals(mm) || "getInfo".equals(mm)) { mm = "/search"; } else if ("update" .equals(mm) || "delete" .equals(mm)) { mm = "/" + mm ; } else { return; } NaviMap nm = NaviMap.getInstance(prefix); Set<String> ra = nm.getRoleSet( ); Set<String> rs = new HashSet( ); for (String rn : ra) { if (rn.startsWith(pm) && rn. endsWith(mm)) { rs.add(rn.substring(pm.length(), rn.length() - mm.length())); } } caze.where("`"+table.name+"`.`id` IN (?)", rs); } protected void insertAuthRole(String id) throws HongsException { ActionHelper helper = Core.getInstance(ActionHelper.class); String uid = (String) helper.getSessibute ( Cnst.UID_SES ); Table tab = db.getTable ("role"); Table usr = db.getTable ("user"); tab.insert(Synt.mapOf("user_id", uid, "role", prefix + "/" + id + "/search")); tab.insert(Synt.mapOf("user_id", uid, "role", prefix + "/" + id + "/create")); tab.insert(Synt.mapOf("user_id", uid, "role", prefix + "/" + id + "/update")); tab.insert(Synt.mapOf("user_id", uid, "role", prefix + "/" + id + "/delete")); tab.insert(Synt.mapOf("user_id", uid, "role", prefix + "/" + id + "/revert")); usr.filter("`id` = ?", uid) .update(Synt.mapOf("rtime", System.currentTimeMillis() / 1000)); } protected void deleteAuthRole(String id) throws HongsException { Table tab = db.getTable ("role"); Set rns = Synt. setOf ( prefix + "/" + id + "/search", prefix + "/" + id + "/create", prefix + "/" + id + "/update", prefix + "/" + id + "/delete", prefix + "/" + id + "/revert" ); tab.remove("`role` IN (?)", rns ); } protected void deleteFormMenu(String id) { File fo = new File(Core.CONF_PATH +"/"+ prefix +"/"+ id + Cnst.FORM_EXT +".xml"); if (fo.exists()) { fo.delete(); } } protected void deleteFormConf(String id) { File fo = new File(Core.CONF_PATH +"/"+ prefix +"/"+ id + Cnst.NAVI_EXT +".xml"); if (fo.exists()) { fo.delete(); } } protected void updateUnitMenu(String id, String name) throws HongsException { Unit un = new Unit(); un.updateUnitMenu(id, name); un.updateRootMenu( ); } protected void updateFormMenu(String id, String name) throws HongsException { Document docm = makeDocument(); Element root = docm.createElement("root"); docm.appendChild ( root ); Element menu = docm.createElement("menu"); root.appendChild ( menu ); menu.setAttribute("text", name); menu.setAttribute("href", prefix+"/"+id+"/"); menu.setAttribute("hrel", prefix+"/"+id+"/main.html"); Element role, actn, depn; role = docm.createElement("rsname"); root.appendChild ( role ); role.appendChild ( docm.createTextNode( "@centra" ) ); role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", prefix+"/"+id+"/search"); role.setAttribute("text", ""+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/stream" + Cnst.ACT_EXT) ); role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", prefix+"/"+id+"/update"); role.setAttribute("text", ""+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(prefix+"/"+id+"/search") ); role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", prefix+"/"+id+"/create"); role.setAttribute("text", ""+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/create" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(prefix+"/"+id+"/search") ); role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", prefix+"/"+id+"/delete"); role.setAttribute("text", ""+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/delete" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(prefix+"/"+id+"/search") ); role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", prefix+"/"+id+"/revert"); role.setAttribute("text", ""+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/revert/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(prefix+"/"+id+"/revert/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(prefix+"/"+id+"/search") ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(prefix+"/"+id+"/update") ); saveDocument(Core.CONF_PATH+"/"+prefix+"/"+id+Cnst.NAVI_EXT+".xml", docm); } protected void updateFormConf(String id, List<Map> conf) throws HongsException { Document docm = makeDocument(); Element root = docm.createElement("root"); docm.appendChild ( root ); Element form = docm.createElement("form"); root.appendChild ( form ); form.setAttribute("name" , id); Map types = FormSet.getInstance().getEnum("__types__"); for (Map fiel: conf) { Element item = docm.createElement( "field" ); form.appendChild ( item ); String s, n, t; s = (String) fiel.get("__text__"); item.setAttribute("text", s); n = (String) fiel.get("__name__"); item.setAttribute("name", n); t = (String) fiel.get("__type__"); item.setAttribute("type", t); s = (String) fiel.get("__rule__"); item.setAttribute("rule", s); s = Synt.declare(fiel.get("__required__"), ""); item.setAttribute("required", s); s = Synt.declare(fiel.get("__repeated__"), ""); item.setAttribute("repeated", s); if ("file".equals(types.get(t) )) { if(!fiel.containsKey("href")) { fiel.put("href", "static/upload/data"); } if(!fiel.containsKey("path")) { fiel.put("path", "static/upload/data"); } if(!fiel.containsKey("temp")) { fiel.put("temp", "static/upload/temp"); } } else if ("date".equals(types.get(t) )) { if(!fiel.containsKey("type")) { fiel.put("type", "timestamp"); } } else if ("enum".equals(types.get(t) ) || "form".equals(types.get(t) )) { if(!fiel.containsKey("conf")) { fiel.put("conf", prefix +"/"+ id); } } else if (Synt.declare(fiel.get("findable"), false)) { if(!fiel.containsKey("lucnene-type")) { fiel.put("lucene-type", "search"); } } Map<String,Map<String,String>> preset = null; List<List<String>> select = null; / for(Object ot : fiel.entrySet( )) { Map.Entry et = (Map.Entry) ot; String k = (String) et.getKey( ); String v = (String) et.getValue(); if (k== null || v== null) { continue; } if (k.startsWith( "__" )) { continue; } if (k.startsWith( ":" )) { if (preset == null ) { preset = new LinkedHashMap(); } String l; if (n.equals( "@" )) { int p=k.indexOf('.' ); if (p == -1) continue; l = k.substring(1+ p); k = k.substring(0, p); k = id + k ; } else { l = k.substring(1 ); k = n; } Dict.put(preset, v, k, l); continue; } if (k.equals("datalist")) { select = Synt.asList(Data.toObject(v) ); continue; } Element para = docm.createElement("param"); item.appendChild ( para ); para.setAttribute("name" , k); para.appendChild ( docm.createTextNode(v) ); } / if (select != null) { Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(List a : select) { String c = Synt.declare( a.get(0), "" ); String l = Synt.declare( a.get(1), "" ); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } / if (preset != null) { for(Map.Entry<String,Map<String,String>> et0 : preset.entrySet()) { n = et0.getKey(); Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(Map.Entry<String,String> et1 : et0.getValue().entrySet()) { String c = et1.getKey( ); String l = et1.getValue(); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } } } saveDocument(Core.CONF_PATH+"/"+prefix+"/"+id+Cnst.FORM_EXT+".xml", docm); } private Document makeDocument() throws HongsException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.newDocument(); } catch (ParserConfigurationException e) { throw new HongsException.Common ( e); } } private void saveDocument(String path, Document docm) throws HongsException { File file = new File(path); File fold = file.getParentFile(); if (!fold.exists()) { fold.mkdirs(); } TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer tr = tf.newTransformer(); DOMSource ds = new DOMSource(docm); StreamResult sr = new StreamResult ( new OutputStreamWriter( new FileOutputStream(file), "utf-8")); tr.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tr.setOutputProperty(OutputKeys.METHOD , "xml" ); tr.setOutputProperty(OutputKeys.INDENT , "yes" ); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); tr.transform(ds, sr); } catch (TransformerConfigurationException e) { throw new HongsException.Common(e); } catch (IllegalArgumentException e) { throw new HongsException.Common(e); } catch (TransformerException e) { throw new HongsException.Common(e); } catch (FileNotFoundException e) { throw new HongsException.Common(e); } catch (UnsupportedEncodingException e) { throw new HongsException.Common(e); } } }
package com.afollestad.photoaffix.ui; import android.Manifest; import android.animation.ValueAnimator; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.os.PersistableBundle; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.Size; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.afollestad.dragselectrecyclerview.DragSelectRecyclerView; import com.afollestad.dragselectrecyclerview.DragSelectRecyclerViewAdapter; import com.afollestad.inquiry.Inquiry; import com.afollestad.inquiry.callbacks.GetCallback; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.color.ColorChooserDialog; import com.afollestad.photoaffix.R; import com.afollestad.photoaffix.adapters.PhotoGridAdapter; import com.afollestad.photoaffix.animation.HeightEvaluator; import com.afollestad.photoaffix.animation.ViewHideAnimationListener; import com.afollestad.photoaffix.data.Photo; import com.afollestad.photoaffix.dialogs.AboutDialog; import com.afollestad.photoaffix.dialogs.ImageSizingDialog; import com.afollestad.photoaffix.dialogs.ImageSpacingDialog; import com.afollestad.photoaffix.utils.Prefs; import com.afollestad.photoaffix.utils.Util; import com.afollestad.photoaffix.views.ColorCircleView; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import static com.afollestad.photoaffix.utils.Util.log; /** * @author Aidan Follestad (afollestad) */ public class MainActivity extends AppCompatActivity implements ColorChooserDialog.ColorCallback, ImageSpacingDialog.SpacingCallback, ImageSizingDialog.SizingCallback, DragSelectRecyclerViewAdapter.SelectionListener { private static final int PERMISSION_RC = 69; @BindView(R.id.appbar_toolbar) Toolbar toolbar; @BindView(R.id.list) public DragSelectRecyclerView list; @BindView(R.id.affixButton) Button affixButton; @BindView(R.id.settingsFrame) ViewGroup settingsFrame; @BindView(R.id.empty) TextView empty; @BindView(R.id.stackHorizontallyLabel) TextView stackHorizontallyLabel; @BindView(R.id.stackHorizontallySwitch) CheckBox stackHorizontallyCheck; @BindView(R.id.bgFillColorCircle) ColorCircleView bgFillColorCircle; @BindView(R.id.bgFillColorLabel) TextView bgFillColorLabel; @BindView(R.id.imagePaddingLabel) TextView imagePaddingLabel; @BindView(R.id.removeBgButton) Button removeBgFillBtn; @BindView(R.id.scalePriorityLabel) TextView scalePriorityLabel; @BindView(R.id.scalePrioritySwitch) CheckBox scalePrioritySwitch; private PhotoGridAdapter adapter; private Photo[] selectedPhotos; private int traverseIndex; private int originalSettingsFrameHeight = -1; private ValueAnimator settingsFrameAnimator; private Unbinder unbinder; // Avoids a rare crash public static void dismissDialog(@Nullable Dialog dialog) { if (dialog == null) return; try { dialog.dismiss(); } catch (Throwable ignored) { } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); unbinder = ButterKnife.bind(this); Inquiry.newInstance(this, null) .build(); toolbar.inflateMenu(R.menu.menu_main); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.clear) { clearSelection(); return true; } else if (item.getItemId() == R.id.about) { AboutDialog.show(MainActivity.this); return true; } return false; } }); list.setLayoutManager(new GridLayoutManager(this, getResources().getInteger(R.integer.grid_width))); adapter = new PhotoGridAdapter(this); adapter.restoreInstanceState(savedInstanceState); adapter.setSelectionListener(this); list.setAdapter(adapter); DefaultItemAnimator animator = new DefaultItemAnimator(); animator.setSupportsChangeAnimations(false); list.setItemAnimator(animator); final boolean stackHorizontally = Prefs.stackHorizontally(this); stackHorizontallyCheck.setChecked(stackHorizontally); stackHorizontallyLabel.setText(stackHorizontally ? R.string.stack_horizontally : R.string.stack_vertically); final boolean scalePriority = Prefs.scalePriority(this); scalePrioritySwitch.setChecked(scalePriority); scalePriorityLabel.setText(scalePriority ? R.string.scale_priority_on : R.string.scale_priority_off); final int bgFillColor = Prefs.bgFillColor(this); bgFillColorCircle.setColor(bgFillColor); final int[] padding = Prefs.imageSpacing(this); imagePaddingLabel.setText(getString(R.string.image_spacing_x, padding[0], padding[1])); if (bgFillColor != Color.TRANSPARENT) { removeBgFillBtn.setVisibility(View.VISIBLE); bgFillColorLabel.setText(R.string.background_fill_color); } else { bgFillColorLabel.setText(R.string.background_fill_color_transparent); } processIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntent(intent); } private void processIntent(Intent intent) { if (intent != null && Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) { ArrayList<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (uris != null && uris.size() > 1) { selectedPhotos = new Photo[uris.size()]; for (int i = 0; i < uris.size(); i++) selectedPhotos[i] = new Photo(uris.get(i)); beginProcessing(); } else { Toast.makeText(this, R.string.need_two_or_more, Toast.LENGTH_SHORT).show(); } } } @Override protected void onDestroy() { super.onDestroy(); unbinder.unbind(); unbinder = null; } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); if (adapter != null) adapter.saveInstanceState(outState); } private void refresh() { int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_RC); return; } Inquiry.get(this) .selectFrom(Uri.parse("content://media/external/images/media"), Photo.class) .sort("datetaken DESC") .where("_data IS NOT NULL") .all(new GetCallback<Photo>() { @Override public void result(Photo[] photos) { if (isFinishing()) return; if (empty != null) { adapter.setPhotos(photos); empty.setVisibility(photos == null || photos.length == 0 ? View.VISIBLE : View.GONE); } } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_RC) refresh(); } @Override protected void onResume() { super.onResume(); refresh(); } @Override protected void onPause() { super.onPause(); if (isFinishing()) Inquiry.destroy(this); } public void clearSelection() { if (Looper.myLooper() != Looper.getMainLooper()) { runOnUiThread(new Runnable() { @Override public void run() { clearSelection(); } }); return; } selectedPhotos = null; adapter.clearSelected(); toolbar.getMenu().findItem(R.id.clear).setVisible(false); } @OnClick(R.id.removeBgButton) public void onClickRemoveBgFill() { removeBgFillBtn.setVisibility(View.GONE); //noinspection ConstantConditions onColorSelection(null, Color.TRANSPARENT); } @OnClick(R.id.expandButton) public void onClickExpandButton(ImageView button) { if (originalSettingsFrameHeight == -1) { final int settingControlHeight = (int) getResources().getDimension(R.dimen.settings_control_height); originalSettingsFrameHeight = settingControlHeight * settingsFrame.getChildCount(); } if (settingsFrameAnimator != null) settingsFrameAnimator.cancel(); if (settingsFrame.getVisibility() == View.GONE) { settingsFrame.setVisibility(View.VISIBLE); button.setImageResource(R.drawable.ic_collapse); settingsFrameAnimator = ValueAnimator.ofObject( new HeightEvaluator(settingsFrame), 0, originalSettingsFrameHeight); } else { button.setImageResource(R.drawable.ic_expand); settingsFrameAnimator = ValueAnimator.ofObject( new HeightEvaluator(settingsFrame), originalSettingsFrameHeight, 0); settingsFrameAnimator.addListener(new ViewHideAnimationListener(settingsFrame)); } settingsFrameAnimator.setInterpolator(new FastOutSlowInInterpolator()); settingsFrameAnimator.setDuration(200); settingsFrameAnimator.start(); } private void beginProcessing() { affixButton.setEnabled(false); try { startProcessing(); } catch (OutOfMemoryError e) { Util.showMemoryError(MainActivity.this); } affixButton.setEnabled(true); } @OnClick(R.id.affixButton) public void onClickAffixButton(View v) { selectedPhotos = adapter.getSelectedPhotos(); beginProcessing(); } @OnClick({R.id.settingStackHorizontally, R.id.settingBgFillColor, R.id.settingImagePadding, R.id.settingScalePriority}) public void onClickSetting(View view) { switch (view.getId()) { case R.id.settingStackHorizontally: stackHorizontallyCheck.setChecked(!stackHorizontallyCheck.isChecked()); stackHorizontallyLabel.setText(stackHorizontallyCheck.isChecked() ? R.string.stack_horizontally : R.string.stack_vertically); Prefs.stackHorizontally(this, stackHorizontallyCheck.isChecked()); break; case R.id.settingBgFillColor: new ColorChooserDialog.Builder(this, R.string.background_fill_color_title) .backButton(R.string.back) .doneButton(R.string.done) .allowUserColorInputAlpha(false) .preselect(Prefs.bgFillColor(this)) .show(); break; case R.id.settingImagePadding: new ImageSpacingDialog().show(getFragmentManager(), "[IMAGE_PADDING_DIALOG]"); break; case R.id.settingScalePriority: scalePrioritySwitch.setChecked(!scalePrioritySwitch.isChecked()); scalePriorityLabel.setText(scalePrioritySwitch.isChecked() ? R.string.scale_priority_on : R.string.scale_priority_off); Prefs.scalePriority(this, scalePrioritySwitch.isChecked()); break; } } @Override public void onColorSelection(@NonNull ColorChooserDialog colorChooserDialog, @ColorInt int selectedColor) { if (selectedColor != Color.TRANSPARENT) { removeBgFillBtn.setVisibility(View.VISIBLE); bgFillColorLabel.setText(R.string.background_fill_color); } else { bgFillColorLabel.setText(R.string.background_fill_color_transparent); } Prefs.bgFillColor(this, selectedColor); bgFillColorCircle.setColor(selectedColor); } @Override public void onSpacingChanged(int horizontal, int vertical) { Prefs.imageSpacing(this, horizontal, vertical); imagePaddingLabel.setText(getString(R.string.image_spacing_x, horizontal, vertical)); } @Size(2) private int[] getNextBitmapSize() { if (selectedPhotos == null || selectedPhotos.length == 0) { selectedPhotos = adapter.getSelectedPhotos(); if (selectedPhotos == null || selectedPhotos.length == 0) return new int[]{10, 10}; // crash workaround } traverseIndex++; if (traverseIndex > selectedPhotos.length - 1) return null; Photo nextPhoto = selectedPhotos[traverseIndex]; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; InputStream is = null; try { is = Util.openStream(this, nextPhoto.getUri()); BitmapFactory.decodeStream(is, null, options); } catch (Exception e) { Util.showError(this, e); return new int[]{0, 0}; } finally { Util.closeQuietely(is); } return new int[]{options.outWidth, options.outHeight}; } @Nullable private BitmapFactory.Options getNextBitmapOptions() { if (selectedPhotos == null) return null; traverseIndex++; if (traverseIndex > selectedPhotos.length - 1) return null; Photo nextPhoto = selectedPhotos[traverseIndex]; InputStream is = null; BitmapFactory.Options options = null; try { is = Util.openStream(this, nextPhoto.getUri()); options = new BitmapFactory.Options(); //Only the properties, so we can get the width/height options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); } catch (Exception e) { Util.showError(this, e); return null; } catch (OutOfMemoryError e2) { Util.showMemoryError(MainActivity.this); return null; } finally { Util.closeQuietely(is); } return options; } private Bitmap getNextBitmap(BitmapFactory.Options options) { Photo nextPhoto = selectedPhotos[traverseIndex]; InputStream is = null; Bitmap bm = null; try { is = Util.openStream(this, nextPhoto.getUri()); bm = BitmapFactory.decodeStream(is, null, options); } catch (Exception e) { Util.showError(this, e); } catch (OutOfMemoryError e2) { Util.showMemoryError(MainActivity.this); } finally { Util.closeQuietely(is); } return bm; } public static void calculateInSampleSize(BitmapFactory.Options options, int reqHeight) { if (reqHeight < 1) { options.inSampleSize = 1; } else { options.inSampleSize = options.outHeight / reqHeight; } } private void startProcessing() { // Lock orientation so the Activity won't change configuration during processing Util.lockOrientation(this); final int[] imageSpacing = Prefs.imageSpacing(MainActivity.this); final int SPACING_HORIZONTAL = imageSpacing[0]; final int SPACING_VERTICAL = imageSpacing[1]; final boolean horizontal = stackHorizontallyCheck.isChecked(); int resultWidth; int resultHeight; if (horizontal) { log("Horizontally stacking"); // The width of the resulting image will be the largest width of the selected images // The height of the resulting image will be the sum of all the selected images' heights int maxHeight = -1; int minHeight = -1; // Traverse all selected images to find largest and smallest heights traverseIndex = -1; int[] size; while ((size = getNextBitmapSize()) != null) { if (size[0] == 0 && size[1] == 0) return; log("Image %d size: %d/%d", traverseIndex, size[0], size[1]); if (maxHeight == -1) maxHeight = size[1]; else if (size[1] > maxHeight) maxHeight = size[1]; if (minHeight == -1) minHeight = size[1]; else if (size[1] < minHeight) minHeight = size[1]; } log("Min height: %d, max height: %d", minHeight, maxHeight); // Traverse images again now that we know the min/max height, scale widths accordingly traverseIndex = -1; int totalWidth = 0; boolean scalePriority = Prefs.scalePriority(this); while ((size = getNextBitmapSize()) != null) { if (size[0] == 0 && size[1] == 0) return; int w = size[0]; int h = size[1]; float ratio = (float) w / (float) h; if (scalePriority) { // Scale to largest if (h < maxHeight) { h = maxHeight; w = (int) ((float) h * ratio); log("Height of image %d is less than max (%d), scaled up to %d/%d...", traverseIndex, maxHeight, w, h); } } else { // Scale to smallest if (h > minHeight) { h = minHeight; w = (int) ((float) h * ratio); log("Height of image %d is larger than min (%d), scaled down to %d/%d...", traverseIndex, minHeight, w, h); } } totalWidth += w; } // Compensate for spacing totalWidth += SPACING_HORIZONTAL * (selectedPhotos.length + 1); minHeight += SPACING_VERTICAL * 2; maxHeight += SPACING_VERTICAL * 2; // Crash avoidance if (totalWidth == 0) { Util.showError(this, new Exception("The total generated width is 0. Please " + "notify me of this through the Google+ community.")); return; } else if (maxHeight == 0) { Util.showError(this, new Exception("The max found height is 0. Please notify " + "me of this through the Google+ community.")); return; } // Print data and create large Bitmap log("Total width with spacing = %d, max height with spacing = %d", totalWidth, maxHeight); resultWidth = totalWidth; resultHeight = scalePriority ? maxHeight : minHeight; } else { log("Vertically stacking"); // The height of the resulting image will be the largest height of the selected images // The width of the resulting image will be the sum of all the selected images' widths int maxWidth = -1; int minWidth = -1; // Traverse all selected images and load min/max width, scale height accordingly traverseIndex = -1; int[] size; while ((size = getNextBitmapSize()) != null) { if (size[0] == 0 && size[1] == 0) return; log("Image %d size: %d/%d", traverseIndex, size[0], size[1]); if (maxWidth == -1) maxWidth = size[0]; else if (size[0] > maxWidth) maxWidth = size[0]; if (minWidth == -1) minWidth = size[0]; else if (size[0] < minWidth) minWidth = size[0]; } // Traverse images again now that we know the min/max height, scale widths accordingly traverseIndex = -1; int totalHeight = 0; boolean scalePriority = Prefs.scalePriority(this); while ((size = getNextBitmapSize()) != null) { if (size[0] == 0 && size[1] == 0) return; int w = size[0]; int h = size[1]; float ratio = (float) h / (float) w; if (scalePriority) { // Scale to largest if (w < maxWidth) { w = maxWidth; h = (int) ((float) w * ratio); log("Height of image %d is larger than min (%d), scaled down to %d/%d...", traverseIndex, maxWidth, w, h); } } else { // Scale to smallest if (w > minWidth) { w = minWidth; h = (int) ((float) w * ratio); log("Width of image %d is larger than min (%d), scaled height down to %d/%d...", traverseIndex, minWidth, w, h); } } totalHeight += h; } // Compensate for spacing totalHeight += SPACING_VERTICAL * (selectedPhotos.length + 1); minWidth += SPACING_HORIZONTAL * 2; maxWidth += SPACING_HORIZONTAL * 2; // Crash avoidance if (totalHeight == 0) { Util.showError(this, new Exception("The total generated height is 0. Please " + "notify me of this through the Google+ community.")); return; } else if (maxWidth == 0) { Util.showError(this, new Exception("The max found width is 0. Please notify " + "me of this through the Google+ community.")); return; } // Print data and create large Bitmap log("Max width with spacing = %d, total height with spacing = %d", maxWidth, totalHeight); resultWidth = scalePriority ? maxWidth : minWidth; resultHeight = totalHeight; } ImageSizingDialog.show(this, resultWidth, resultHeight); } @Override public void onSizingResult(double scale, int resultWidth, int resultHeight, Bitmap.CompressFormat format, int quality, boolean cancelled) { if (cancelled) { traverseIndex = -1; Util.unlockOrientation(this); return; } try { finishProcessing(scale, resultWidth, resultHeight, format, quality); } catch (OutOfMemoryError e) { Util.showMemoryError(this); } } private void finishProcessing(final double SCALE, final int resultWidth, final int resultHeight, final Bitmap.CompressFormat format, final int quality) { // Crash avoidance if (resultWidth == 0) { Util.showError(this, new Exception("The result width is 0. Please notify " + "me of this through the Google+ community.")); return; } else if (resultHeight == 0) { Util.showError(this, new Exception("The result height is 0. Please notify " + "me of this through the Google+ community.")); return; } log("IMAGE SCALE = %s, total scaled width = %d, height = %d", SCALE, resultWidth, resultHeight); final Bitmap result = Bitmap.createBitmap(resultWidth, resultHeight, Bitmap.Config.ARGB_8888); final boolean horizontal = stackHorizontallyCheck.isChecked(); final int[] imageSpacing = Prefs.imageSpacing(MainActivity.this); final int SPACING_HORIZONTAL = (int) (imageSpacing[0] * SCALE); // TODO should scale be multiplied here? final int SPACING_VERTICAL = (int) (imageSpacing[1] * SCALE); final Canvas resultCanvas = new Canvas(result); final Paint paint = new Paint(); paint.setFilterBitmap(true); paint.setAntiAlias(true); paint.setDither(true); @ColorInt final int bgFillColor = Prefs.bgFillColor(this); if (bgFillColor != Color.TRANSPARENT) { // Fill the canvas (blank image) with the user's selected background fill color resultCanvas.drawColor(bgFillColor); } final MaterialDialog progress = new MaterialDialog.Builder(this) .content(R.string.affixing_your_photos) .progress(true, -1) .cancelable(false) .show(); new Thread(new Runnable() { @Override public void run() { // Used to set destination dimensions when drawn onto the canvas, e.g. when padding is used final Rect dstRect = new Rect(0, 0, 10, 10); int processedCount = 0; if (horizontal) { int currentX = 0; traverseIndex = -1; BitmapFactory.Options bitmapOptions; while ((bitmapOptions = getNextBitmapOptions()) != null) { processedCount++; int scaledWidth = (int) (bitmapOptions.outWidth * SCALE); int scaledHeight = (int) (bitmapOptions.outHeight * SCALE); if (scaledHeight < resultHeight) { final float ratio = (float) scaledWidth / (float) scaledHeight; scaledHeight = resultHeight; scaledWidth = (int) ((float) scaledHeight * ratio); } log("CURRENT IMAGE width = %d, height = %d", bitmapOptions.outWidth, bitmapOptions.outHeight); log("SCALED IMAGE width = %d, height = %d", scaledWidth, scaledHeight); // Left is right of last image plus horizontal spacing dstRect.left = currentX + SPACING_HORIZONTAL; // Right is left plus width of the current image dstRect.right = dstRect.left + scaledWidth; // Centers images vertically final int centerY = (resultHeight / 2) - (SPACING_VERTICAL * 2); dstRect.top = centerY - (scaledHeight / 2); dstRect.bottom = centerY + (scaledHeight / 2); log("LEFT = %d, RIGHT = %d, TOP = %d, BOTTOM = %d", dstRect.left, dstRect.right, dstRect.top, dstRect.bottom); bitmapOptions.inJustDecodeBounds = false; calculateInSampleSize(bitmapOptions, dstRect.bottom - dstRect.top); final Bitmap bm = getNextBitmap(bitmapOptions); if (bm == null) break; bm.setDensity(Bitmap.DENSITY_NONE); resultCanvas.drawBitmap(bm, null, dstRect, paint); currentX = dstRect.right; bm.recycle(); } } else { int currentY = 0; traverseIndex = -1; BitmapFactory.Options bitmapOptions; while ((bitmapOptions = getNextBitmapOptions()) != null) { processedCount++; int scaledWidth = (int) (bitmapOptions.outWidth * SCALE); int scaledHeight = (int) (bitmapOptions.outHeight * SCALE); if (scaledWidth < resultWidth) { final float ratio = (float) scaledHeight / (float) scaledWidth; scaledWidth = resultWidth; scaledHeight = (int) ((float) scaledWidth * ratio); } log("CURRENT IMAGE width = %d, height = %d", bitmapOptions.outWidth, bitmapOptions.outHeight); log("SCALED IMAGE width = %d, height = %d", scaledWidth, scaledHeight); // Top is bottom of the last image plus vertical spacing dstRect.top = currentY + SPACING_VERTICAL; // Bottom is top plus height of the current image dstRect.bottom = dstRect.top + scaledHeight; // Centers images horizontally final int centerX = (resultWidth / 2) - (SPACING_HORIZONTAL * 2); dstRect.left = centerX - (scaledWidth / 2); dstRect.right = centerX + (scaledWidth / 2); log("LEFT = %d, RIGHT = %d, TOP = %d, BOTTOM = %d", dstRect.left, dstRect.right, dstRect.top, dstRect.bottom); bitmapOptions.inJustDecodeBounds = false; bitmapOptions.inSampleSize = (dstRect.right - dstRect.left) / bitmapOptions.outWidth; final Bitmap bm = getNextBitmap(bitmapOptions); if (bm == null) break; resultCanvas.drawBitmap(bm, null, dstRect, paint); currentY = dstRect.bottom; bm.recycle(); } } if (processedCount == 0) { try { result.recycle(); } catch (Throwable ignored) { } dismissDialog(progress); return; } // Save results to file File cacheFile = Util.makeTempFile(MainActivity.this, ".png"); log("Saving result to %s", cacheFile.getAbsolutePath().replace("%", "%%")); FileOutputStream os = null; try { os = new FileOutputStream(cacheFile); result.compress(format, quality, os); } catch (Exception e) { log("Error: %s", e.getMessage()); e.printStackTrace(); Util.showError(MainActivity.this, e); cacheFile = null; } finally { Util.closeQuietely(os); } // Recycle the large final image result.recycle(); // Close progress dialog and move on to the done phase dismissDialog(progress); done(cacheFile); } }).start(); } private void done(File file) { log("Done"); // Clear selection clearSelection(); // Unlock orientation so Activity can rotate again Util.unlockOrientation(MainActivity.this); // Add the affixed file to the media store so gallery apps can see it MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { log("Scanned %s, uri = %s", path, uri != null ? uri.toString().replace("%", "%%") : null); } }); try { // Open the result in the viewer startActivity(new Intent(this, ViewerActivity.class)
package com.android.wkzf.view; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.wkzf.library.view.WKClickView; public class WKClickViewActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_click_view); WKClickView wkClickView = (WKClickView)findViewById(R.id.click_view_semicircle); wkClickView.setEnabled(false); wkClickView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(WKClickViewActivity.this, "", Toast.LENGTH_SHORT).show(); } }); } }
package com.example.android.pets.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.example.android.pets.data.PetContract.PetEntry; import java.net.URI; public class PetProvider extends ContentProvider { private static final String LOG_TAG = PetProvider.class.getSimpleName(); // codes for Uri match private static final int PETS = 100; private static final int PETS_ID = 101; // Uri matcher private static final UriMatcher sUriMathcer = new UriMatcher(UriMatcher.NO_MATCH); // create the petDbHelper object to connect with the database private PetDbHelper mPetDbHelper; /** * Initialization * * @return */ @Override public boolean onCreate() { // initialize the object petDbHelper mPetDbHelper = new PetDbHelper(getContext()); return true; } /** * Uri Matcher * */ static { sUriMathcer.addURI(PetContract.CONTENT_AUTHORITY, PetContract.PATH_PETS, PETS); sUriMathcer.addURI(PetContract.CONTENT_AUTHORITY, PetContract.PATH_PETS + "/#", PETS_ID); } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { // read the database SQLiteDatabase database = mPetDbHelper.getReadableDatabase(); // Declare the Cursor to be returned in the end Cursor cursor; // Run the Uri Matcher final int matcher = sUriMathcer.match(uri); // Select between PETS or PETS_ID case switch (matcher) { case PETS: cursor = database.query( PetEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; case PETS_ID: selection = PetEntry._ID + "=?"; selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))}; cursor = database.query( PetEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; default: throw new IllegalArgumentException("Cannot query unknown URI " + uri); } // Set notification URI to the cursor cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { final int match = sUriMathcer.match(uri); switch (match) { case PETS: return insertPet(uri, values); default: throw new IllegalArgumentException("Insertion is not supported for " + uri); } } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { // connect with the database SQLiteDatabase database = mPetDbHelper.getWritableDatabase(); final int match = sUriMathcer.match(uri); int rowsDeleted; switch (match) { case PETS: rowsDeleted = database.delete(PetEntry.TABLE_NAME, selection, selectionArgs); break; case PETS_ID: // Get pet ID String id = String.valueOf(ContentUris.parseId(uri)); selection = PetEntry._ID + "=?"; selectionArgs = new String[]{id}; rowsDeleted = database.delete(PetEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException("Delete cannot be done for " + uri); } // notify all the listeners if (rowsDeleted > 0) { getContext().getContentResolver().notifyChange(uri, null); } // return the number of rows deleted return rowsDeleted; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { final int match = sUriMathcer.match(uri); switch (match) { case PETS: return updatePet(uri, values, selection, selectionArgs); case PETS_ID: // For PET_ID extract the pet ID from the URI String id = String.valueOf(ContentUris.parseId(uri)); selection = PetEntry._ID + "=?"; selectionArgs = new String[]{id}; return updatePet(uri, values, selection, selectionArgs); default: throw new IllegalArgumentException("Update is not supported for " + uri); } } @Nullable @Override public String getType(@NonNull Uri uri) { final int match = sUriMathcer.match(uri); switch (match) { case PETS: return PetEntry.CONTENT_LIST_TYPE; case PETS_ID: return PetEntry.CONTENT_ITEM_TYPE; default: throw new IllegalStateException("Unknown URI " + uri + " with match " + match); } } /** * Check if the entered gender is valid * UNKNOWN = 0 * MALE = 1 * FEMALE = 2 * * @param gender * @return */ private boolean isValidGender(int gender) { return gender == PetEntry.GENDER_UNKNOWN || gender == PetEntry.GENDER_MALE || gender == PetEntry.GENDER_FEMALE; } /** * Helper method to add Pet to the database. * This method is called inside the INSERT method * * @param uri * @param values * @return */ private Uri insertPet(Uri uri, ContentValues values) { // sanity check the values String name = values.getAsString(PetEntry.COLUMN_NAME); Integer gender = values.getAsInteger(PetEntry.COLUMN_GENDER); Integer weight = values.getAsInteger(PetEntry.COLUMN_WEIGHT); // check name if (name.isEmpty()) { throw new IllegalArgumentException("Pet requires a name"); } // check gender if (gender == null || !isValidGender(gender)) { throw new IllegalArgumentException("Pet requires valid gender"); } // check weight if ((weight != null) && (weight < 0)) { throw new IllegalArgumentException("Pet requires valid weight"); } // access the database in write mode SQLiteDatabase database = mPetDbHelper.getWritableDatabase(); // insert the pet to database long id = database.insert(PetEntry.TABLE_NAME, null, values); if (id == -1) { Log.e(LOG_TAG, "Failed to insert row for " + uri); return null; } // Notify all listeners that the data changed getContext().getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, id); } private int updatePet(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // NAME - sanity check if (values.containsKey(PetEntry.COLUMN_NAME)) { String name = values.getAsString(PetEntry.COLUMN_NAME); if (name == null) { throw new IllegalArgumentException("Pet requires a name"); } } // GENDER - sanity check if (values.containsKey(PetEntry.COLUMN_GENDER)) { Integer gender = values.getAsInteger(PetEntry.COLUMN_GENDER); if (gender == null || !isValidGender(gender)) { throw new IllegalArgumentException("Pet requires valid gender"); } } // WEIGHT - sanity check if (values.containsKey(PetEntry.COLUMN_WEIGHT)) { Integer weight = values.getAsInteger(PetEntry.COLUMN_WEIGHT); if (weight != null && weight < 0) { throw new IllegalArgumentException("Pet requires valid weight"); } } // connect with the database SQLiteDatabase database = mPetDbHelper.getWritableDatabase(); // if there is no value, do not try to update if (values.size() == 0) { return 0; } // perform the update in the database int rowsUpdated = database.update(PetEntry.TABLE_NAME, values, selection, selectionArgs); // notify listeners that the data changed, if necessary if (rowsUpdated > 0) { getContext().getContentResolver().notifyChange(uri, null); } // return the number of update lines return rowsUpdated; } }
package com.example.kevin.wear_where; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.app.DatePickerDialog; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.graphics.Color; import android.graphics.Typeface; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v4.widget.SwipeRefreshLayout; import android.text.InputType; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import com.example.kevin.wear_where.AsyncTask.DailyForecastAST; import com.example.kevin.wear_where.AsyncTask.GoogleDirectionsAST; import com.example.kevin.wear_where.AsyncTask.IntervalInformationAST; import com.example.kevin.wear_where.Google.Directions.DirectionsObject; import com.example.kevin.wear_where.Listeners.DateListener; import com.example.kevin.wear_where.MapInformation.MapInformation; import com.example.kevin.wear_where.WundergroundData.DailyForecast.DailyObject; import com.example.kevin.wear_where.wear.Clothing; import com.example.kevin.wear_where.wear.ClothingActivity; import com.example.kevin.wear_where.AsyncTask.CurrentConditionAST; import com.example.kevin.wear_where.AsyncTask.HourlyForecastAST; import com.example.kevin.wear_where.AsyncTask.ImageLoaderAST; import com.example.kevin.wear_where.WundergroundData.CurrentCondition.ConditionsObject; import com.example.kevin.wear_where.Database.TempRange; import com.example.kevin.wear_where.Database.DatabaseInterface; import com.example.kevin.wear_where.WundergroundData.HourlyForecast.HourlyObject; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment; import com.google.android.gms.location.places.ui.PlaceSelectionListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.maps.android.PolyUtil; import com.google.maps.android.SphericalUtil; import java.io.InputStream; import java.util.ArrayList; import java.io.IOException; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Locale; public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener { // Variable used to keep track of whether or not this is the initial start up of the application private int firstStart = 1; // Variable used to store an instance of the map in the road trip tab private GoogleMap maps; // Variable used to create an instance of the mapFragment (Call getMapAsync(this) on mapFragment to update the map) private MapFragment mapFragment; // Variable used to create an instance of the GoogleApiClient private GoogleApiClient mGoogleApiClient; // Variable used to keep track of your most recent location private Location mLastLocation; // Variables used to keep track of the latitude and longitude of your current location; private double latitude = 0; private double longitude = 0; // Variables used to create instances of the places fragments in the vacation tab and road trip tab private PlaceAutocompleteFragment vacationLocation; private PlaceAutocompleteFragment startingLocation; private PlaceAutocompleteFragment endingLocation; // Latitude and Longitude doubles initialized to 900 since this value is impossible private double vacationLatitude = 900; private double vacationLongitude = 900; private LatLng startingCoordinates = null; private LatLng endingCoordinates = null; // Variable that stores a parsed JSON object from the Google Directions API Query Result private DirectionsObject directionsObject; // Variable used to store the interval points pending weather info private ArrayList<LatLng> weatherPoints; // Variable used to store the markers that will be placed on the map private ArrayList<MarkerOptions> markers; // Variable used to store multiple points along the route between the starting and ending locations input in the road trip tab (used to draw the polyline on the map between the two points) private List<LatLng> polyline; private TextView temperature, location, description; // TextView for current weather information private ImageView conditionIcon; // ImageView for current condition image private ConditionsObject currentForecast; // Object holding the current weather information private HourlyObject hourlyForecast; // Object holding the hourly weather information private DailyObject dailyForecast; // Object holding the daily weather information // Hourly forecast widgets private TextView temperature1, description1, time1; private ImageView icon1; private TextView temperature2, description2, time2; private ImageView icon2; private TextView temperature3, description3, time3; private ImageView icon3; private TextView temperature4, description4, time4; private ImageView icon4; private TextView temperature5, description5, time5; private ImageView icon5; private TextView temperature6, description6, time6; private ImageView icon6; private TextView temperature7, description7, time7; private ImageView icon7; private TextView temperature8, description8, time8; private ImageView icon8; private TextView temperature9, description9, time9; private ImageView icon9; private TextView temperature10, description10, time10; private ImageView icon10; private TextView temperature11, description11, time11; private ImageView icon11; private TextView temperature12, description12, time12; private ImageView icon12; private TextView temperature13, description13, time13; private ImageView icon13; private TextView temperature14, description14, time14; private ImageView icon14; private TextView temperature15, description15, time15; private ImageView icon15; private TextView temperature16, description16, time16; private ImageView icon16; // Daily forecast widgets private ImageView day1icon; private TextView day1weekday, day1condition, day1low, day1high; private ImageView day2icon; private TextView day2weekday, day2condition, day2low, day2high; private ImageView day3icon; private TextView day3weekday, day3condition, day3low, day3high; private ImageView day4icon; private TextView day4weekday, day4condition, day4low, day4high; private ImageView day5icon; private TextView day5weekday, day5condition, day5low, day5high; private ImageView day6icon; private TextView day6weekday, day6condition, day6low, day6high; private ImageView day7icon; private TextView day7weekday, day7condition, day7low, day7high; private Calendar calendar; private DatePickerDialog.OnDateSetListener leaveDateListener, returnDateListener; private EditText leaveDate, returnDate; private Button submitButton; private SwipeRefreshLayout refreshSwipe; private String city; private String state; // Variable used for updateing database private DatabaseInterface datasource; // Variables used for updating temperature ranges private TempRange warmRange; private TempRange chillyRange; private Clothing clothes; public final static String FIRSTMESSAGE = "com.example.kevin.wear_where.MESSAGE_ONE"; public final static String SECONDMESSAGE = "com.example.kevin.wear_wear.MESSAGE_TWO"; final Context context = this; // Global Geocoder class private Geocoder geocoder; // Intent for new VacationDataActivity private Intent vacationData; private List<Address> vacationAddresses; /* Called BEFORE the activity is visible! i.e. do anything that needs to be done before the application is visible. Also called whenever the application is launched and there are no existing resources to work with (i.e. first start or application was killed before) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Set up the tab host TabHost tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); //Create tab1 TabHost.TabSpec homeTab = tabHost.newTabSpec("homeTab"); homeTab.setIndicator("Weather"); homeTab.setContent(R.id.layout1); tabHost.addTab(homeTab); //Create tab2 homeTab = tabHost.newTabSpec("homeTab2"); homeTab.setIndicator("Apparel"); homeTab.setContent(R.id.layout2); tabHost.addTab(homeTab); //Create tab3 homeTab = tabHost.newTabSpec("homeTab3"); homeTab.setIndicator("Vacation?"); homeTab.setContent(R.id.layout3); tabHost.addTab(homeTab); //Create tab4 homeTab = tabHost.newTabSpec("homeTab4"); homeTab.setIndicator("Road\nTrip!"); homeTab.setContent(R.id.layout4); tabHost.addTab(homeTab); //Get a reference to the google maps fragment in tab4 mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); final ScrollView scroll = (ScrollView) findViewById(R.id.layout4); ImageView transparent = (ImageView)findViewById(R.id.imagetrans); transparent.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // Disallow ScrollView to intercept touch events. scroll.requestDisallowInterceptTouchEvent(true); // Disable touch on transparent view return false; case MotionEvent.ACTION_UP: // Allow ScrollView to intercept touch events. scroll.requestDisallowInterceptTouchEvent(false); return true; case MotionEvent.ACTION_MOVE: scroll.requestDisallowInterceptTouchEvent(true); return false; default: return true; } } }); // Start up and open database datasource = new DatabaseInterface(this); datasource.open(); // If first time using app, add default values to database warmRange = datasource.getWarmRange(); if(warmRange == null){ datasource.createRange(60, 79); } chillyRange = datasource.getChillyRange(); if(chillyRange == null){ datasource.createRange(40, 59); } //Initialize clothing buttons and gender switch on tab2 Button miscellaneous = (Button)findViewById(R.id.miscellaneous); Button upperbody = (Button)findViewById(R.id.upperbody); Button lowerbody = (Button)findViewById(R.id.lowerbody); Button shoes = (Button)findViewById(R.id.shoes); Button overalls = (Button)findViewById(R.id.overalls); Switch genderSwitch = (Switch)findViewById(R.id.genderSwitch); //Instantiate clothing from main/assets/ folder AssetManager assetManager = this.getResources().getAssets(); try { InputStream firstFile = assetManager.open("herClothes.txt"); InputStream secondFile = assetManager.open("hisClothes.txt"); clothes = new Clothing(firstFile, secondFile); } catch (IOException e){ e.printStackTrace(); } //start switch on/off functions genderSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ Toast.makeText(getApplicationContext(),"Gender set to female", Toast.LENGTH_SHORT).show(); clothes.gender = "female"; } else { Toast.makeText(getApplicationContext(),"Gender set to male",Toast.LENGTH_SHORT).show(); clothes.gender = "male"; } } }); //Start onclick functions of buttons miscellaneous.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get latest temperature values from user warmRange = datasource.getWarmRange(); chillyRange = datasource.getChillyRange(); clothes.lowerWarm = (float) warmRange.getMin(); clothes.upperWarm = (float) warmRange.getMax(); clothes.lowerChilly = (float) chillyRange.getMin(); clothes.upperChilly = (float) chillyRange.getMax(); HashSet<String> currentSet = new HashSet<String>(); ArrayList<String> miscellaneous = clothes.getMisc(currentForecast.getTemperature()); String[] miscellaneousList = new String[miscellaneous.size()]; if (currentForecast.getCondition().contains("Rain") || currentForecast.getCondition().contains("Shower") || currentForecast.getCondition().contains("Storm")) { miscellaneousList = new String[miscellaneous.size()+1]; miscellaneousList[0] = "Umbrella"; for (int i = 1; i < miscellaneous.size()+1; i++) { miscellaneousList[i] = miscellaneous.get(i-1); currentSet.add(miscellaneous.get(i-1)); } } else{ for (int i = 0; i < miscellaneous.size(); i++){ miscellaneousList[i] = miscellaneous.get(i); currentSet.add(miscellaneous.get(i)); } } ArrayList<String> list2 = new ArrayList<>(); int hour = 25; String ampm = "25"; for (int i = 0; i < 16; i++) { String temp = hourlyForecast.getTemperatureF(i) + ""; ArrayList<String> arr = clothes.getMisc(currentForecast.getTemperature()); list2 = clothes.getMisc(temp); if (!list2.equals(arr)) { hour = i; ampm = hourlyForecast.getAMPM(i); break; } else if (i == 15){ list2 = new ArrayList<String>(); list2.add("There's nothing to be shown"); } } for (int i = 0; i < list2.size(); i++){ if (currentSet.contains(list2.get(i))){ list2.remove(i); } } String[] stringList2 = new String[list2.size()]; if (list2.size() > 1) { if (hourlyForecast.getCondition(hour).contains("Rain") || hourlyForecast.getCondition(hour).contains("Shower") || hourlyForecast.getCondition(hour).contains("Storm")) { stringList2 = new String[list2.size() + 1]; stringList2[0] = "Umbrella"; for (int i = 1; i < list2.size() + 1; i++) { stringList2[i] = list2.get(i - 1); } } else { for (int i = 0; i < list2.size(); i++) { stringList2[i] = list2.get(i); } } } else if (list2.size() == 1){ stringList2[0] = list2.get(0); } Intent myIntent = new Intent(MainActivity.this, ClothingActivity.class); myIntent.putExtra(FIRSTMESSAGE, miscellaneousList); myIntent.putExtra(SECONDMESSAGE, stringList2); myIntent.putExtra("TIME", hour); myIntent.putExtra("AMPM", ampm); myIntent.putExtra("CONDITION",currentForecast.getCondition()); myIntent.putExtra("THISTEMP",currentForecast.getTemperature() + ""); myIntent.putExtra("LATERCONDITION", hourlyForecast.getCondition(hour)); myIntent.putExtra("TEMP",hourlyForecast.getTemperatureF(hour) + ""); startActivity(myIntent); } }); upperbody.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get latest temperature values from user warmRange = datasource.getWarmRange(); chillyRange = datasource.getChillyRange(); clothes.lowerWarm = (float) warmRange.getMin(); clothes.upperWarm = (float) warmRange.getMax(); clothes.lowerChilly = (float) chillyRange.getMin(); clothes.upperChilly = (float) chillyRange.getMax(); HashSet<String> currentSet = new HashSet<String>(); ArrayList<String> upperbody = clothes.getUpperBody(currentForecast.getTemperature()); String[] upperbodyList = new String[upperbody.size()]; if (currentForecast.getCondition().contains("Rain") || currentForecast.getCondition().contains("Shower") || currentForecast.getCondition().contains("Storm")) { upperbodyList = new String[upperbody.size()+1]; upperbodyList[0] = "Rain Coat"; for (int i = 1; i < upperbody.size()+1; i++) { upperbodyList[i] = upperbody.get(i-1); currentSet.add(upperbody.get(i-1)); } } else{ for (int i = 0; i < upperbody.size(); i++){ upperbodyList[i] = upperbody.get(i); currentSet.add(upperbody.get(i)); } } ArrayList<String> list2 = new ArrayList<>(); int hour = 25; String ampm = "25"; for (int i = 0; i < 16; i++) { String temp = hourlyForecast.getTemperatureF(i) + ""; ArrayList<String> arr = clothes.getUpperBody(currentForecast.getTemperature()); list2 = clothes.getUpperBody(temp); if (list2 != arr) { hour = i; ampm = hourlyForecast.getAMPM(i); break; } else if (i == 15){ list2 = new ArrayList<String>(); list2.add("There's nothing to be shown"); } } for (int i = 0; i < list2.size(); i++){ if (currentSet.contains(list2.get(i))){ list2.remove(i); } } String[] stringList2 = new String[list2.size()]; if (list2.size() > 1) { if (hourlyForecast.getCondition(hour).contains("Rain") || hourlyForecast.getCondition(hour).contains("Shower") || hourlyForecast.getCondition(hour).contains("Storm")) { stringList2 = new String[list2.size() + 1]; stringList2[0] = "Umbrella"; for (int i = 1; i < list2.size() + 1; i++) { stringList2[i] = list2.get(i - 1); } } else { for (int i = 0; i < list2.size(); i++) { stringList2[i] = list2.get(i); } } } else if (list2.size() == 1){ stringList2[0] = list2.get(0); } Intent myIntent = new Intent(MainActivity.this, ClothingActivity.class); myIntent.putExtra(FIRSTMESSAGE, upperbodyList); myIntent.putExtra(SECONDMESSAGE, stringList2); myIntent.putExtra("CONDITION",currentForecast.getCondition()); myIntent.putExtra("LATERCONDITION", hourlyForecast.getCondition(hour)); myIntent.putExtra("TIME", hour); myIntent.putExtra("AMPM", ampm); myIntent.putExtra("TEMP",hourlyForecast.getTemperatureF(hour) + ""); myIntent.putExtra("THISTEMP",currentForecast.getTemperature() + ""); startActivity(myIntent); } }); lowerbody.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get latest temperature values from user warmRange = datasource.getWarmRange(); chillyRange = datasource.getChillyRange(); clothes.lowerWarm = (float) warmRange.getMin(); clothes.upperWarm = (float) warmRange.getMax(); clothes.lowerChilly = (float) chillyRange.getMin(); clothes.upperChilly = (float) chillyRange.getMax(); HashSet<String> currentSet = new HashSet<String>(); ArrayList<String> lowerbody = clothes.getLowerBody(currentForecast.getTemperature()); String[] lowerbodyList = new String[lowerbody.size()]; if (currentForecast.getCondition().contains("Rain") || currentForecast.getCondition().contains("Shower") || currentForecast.getCondition().contains("Storm")) { lowerbodyList = new String[lowerbody.size()+1]; lowerbodyList[0] = "Rain-Proof Pants"; for (int i = 1; i < lowerbody.size()+1; i++) { lowerbodyList[i] = lowerbody.get(i-1); currentSet.add(lowerbody.get(i-1)); } } else{ for (int i = 0; i < lowerbody.size(); i++){ lowerbodyList[i] = lowerbody.get(i); currentSet.add(lowerbody.get(i)); } } ArrayList<String> list2 = new ArrayList<>(); int hour = 25; String ampm = "25"; for (int i = 0; i < 16; i++) { String temp = hourlyForecast.getTemperatureF(i) + ""; ArrayList<String> arr = clothes.getLowerBody(currentForecast.getTemperature()); list2 = clothes.getLowerBody(temp); if (list2 != arr) { hour = i; ampm = hourlyForecast.getAMPM(i); break; } else if (i == 15){ list2 = new ArrayList<String>(); list2.add("There's nothing to be shown"); } } for (int i = 0; i < list2.size(); i++){ if (currentSet.contains(list2.get(i))){ list2.remove(i); } } String[] stringList2 = new String[list2.size()]; if (list2.size() > 1) { if (hourlyForecast.getCondition(hour).contains("Rain") || hourlyForecast.getCondition(hour).contains("Shower") || hourlyForecast.getCondition(hour).contains("Storm")) { stringList2 = new String[list2.size() + 1]; stringList2[0] = "Umbrella"; for (int i = 1; i < list2.size() + 1; i++) { stringList2[i] = list2.get(i - 1); } } else { for (int i = 0; i < list2.size(); i++) { stringList2[i] = list2.get(i); } } } else if (list2.size() == 1){ stringList2[0] = list2.get(0); } Intent myIntent = new Intent(MainActivity.this, ClothingActivity.class); myIntent.putExtra(FIRSTMESSAGE, lowerbodyList); myIntent.putExtra(SECONDMESSAGE, stringList2); myIntent.putExtra("CONDITION",currentForecast.getCondition()); myIntent.putExtra("LATERCONDITION", hourlyForecast.getCondition(hour)); myIntent.putExtra("TIME", hour); myIntent.putExtra("AMPM", ampm); myIntent.putExtra("TEMP",hourlyForecast.getTemperatureF(hour) + ""); myIntent.putExtra("THISTEMP",currentForecast.getTemperature() + ""); startActivity(myIntent); } }); shoes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get latest temperature values from user warmRange = datasource.getWarmRange(); chillyRange = datasource.getChillyRange(); clothes.lowerWarm = (float) warmRange.getMin(); clothes.upperWarm = (float) warmRange.getMax(); clothes.lowerChilly = (float) chillyRange.getMin(); clothes.upperChilly = (float) chillyRange.getMax(); HashSet<String> currentSet = new HashSet<String>(); ArrayList<String> shoes = clothes.getShoes(currentForecast.getTemperature()); String[] shoesList = new String[shoes.size()]; if (currentForecast.getCondition().contains("Rain") || currentForecast.getCondition().contains("Shower") || currentForecast.getCondition().contains("Storm")) { shoesList = new String[shoes.size()+1]; shoesList[0] = "Rain Boots"; for (int i = 1; i < shoes.size()+1; i++) { shoesList[i] = shoes.get(i-1); currentSet.add(shoes.get(i-1)); } } else{ for (int i = 0; i < shoes.size(); i++){ shoesList[i] = shoes.get(i); currentSet.add(shoes.get(i)); } } ArrayList<String> list2 = new ArrayList<>(); int hour = 25; String ampm = "25"; for (int i = 0; i < 16; i++) { String temp = hourlyForecast.getTemperatureF(i) + ""; ArrayList<String> arr = clothes.getShoes(currentForecast.getTemperature()); list2 = clothes.getShoes(temp); if (list2 != arr) { hour = i; ampm = hourlyForecast.getAMPM(i); break; } else if (i == 15){ list2 = new ArrayList<String>(); list2.add("There's nothing to be shown"); } } for (int i = 0; i < list2.size(); i++){ if (currentSet.contains(list2.get(i))){ list2.remove(i); } if (list2.size() == 0){ list2.add("There's nothing to be shown"); } } String[] stringList2 = new String[list2.size()]; if (list2.size() > 1) { if (hourlyForecast.getCondition(hour).contains("Rain") || hourlyForecast.getCondition(hour).contains("Shower") || hourlyForecast.getCondition(hour).contains("Storm")) { stringList2 = new String[list2.size() + 1]; stringList2[0] = "Umbrella"; for (int i = 1; i < list2.size() + 1; i++) { stringList2[i] = list2.get(i - 1); } } else { for (int i = 0; i < list2.size(); i++) { stringList2[i] = list2.get(i); } } } else if (list2.size() == 1){ stringList2[0] = list2.get(0); } Intent myIntent = new Intent(MainActivity.this, ClothingActivity.class); myIntent.putExtra(FIRSTMESSAGE, shoesList); myIntent.putExtra(SECONDMESSAGE, stringList2); myIntent.putExtra("CONDITION",currentForecast.getCondition()); myIntent.putExtra("LATERCONDITION", hourlyForecast.getCondition(hour)); myIntent.putExtra("TIME", hour); myIntent.putExtra("AMPM", ampm); myIntent.putExtra("TEMP",hourlyForecast.getTemperatureF(hour) + ""); myIntent.putExtra("THISTEMP",currentForecast.getTemperature() + ""); startActivity(myIntent); } }); overalls.setVisibility(View.GONE); /*if (clothes.gender.equals("male")){ overalls.setVisibility(View.GONE); } else { overalls.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { warmRange = datasource.getWarmRange(); chillyRange = datasource.getChillyRange(); clothes.lowerWarm = (float) warmRange.getMin(); clothes.upperWarm = (float) warmRange.getMax(); clothes.lowerChilly = (float) chillyRange.getMin(); clothes.upperChilly = (float) chillyRange.getMax(); HashSet<String> currentSet = new HashSet<String>(); ArrayList<String> overalls = clothes.getOveralls(currentForecast.getTemperature()); String[] overallsList = new String[overalls.size()]; for (int i = 0; i < overalls.size(); i++){ overallsList[i] = overalls.get(i); currentSet.add(overalls.get(i)); } ArrayList<String> list2 = new ArrayList<>(); int hour = 25; String ampm = "25"; for (int i = 0; i < 16; i++) { String temp = hourlyForecast.getTemperatureF(i) + ""; ArrayList<String> arr = clothes.getOveralls(currentForecast.getTemperature()); list2 = clothes.getOveralls(temp); if (list2 != arr) { hour = i; ampm = hourlyForecast.getAMPM(i); break; } else if (i == 15){ list2 = new ArrayList<String>(); list2.add("There's nothing to be shown"); } } for (int i = 0; i < list2.size(); i++){ if (currentSet.contains(list2.get(i))){ list2.remove(i); } } String[] stringList2 = new String[list2.size()]; if (currentForecast.getCondition().contains("Rain") || currentForecast.getCondition().contains("Shower") || currentForecast.getCondition().contains("Storm")){ stringList2 = new String[list2.size()+1]; stringList2[0] = "Umbrella"; for (int i = 1; i < list2.size()+1; i++){ stringList2[i] = list2.get(i-1); } } else{ for (int i = 0; i < list2.size(); i++){ stringList2[i] = list2.get(i); } } Intent myIntent = new Intent(MainActivity.this, ClothingActivity.class); myIntent.putExtra(FIRSTMESSAGE, overallsList); myIntent.putExtra(SECONDMESSAGE, stringList2); myIntent.putExtra("CONDITION",currentForecast.getCondition()); myIntent.putExtra("TIME", hour); myIntent.putExtra("AMPM", ampm); myIntent.putExtra("TEMP",hourlyForecast.getTemperatureF(hour) + ""); myIntent.putExtra("THISTEMP",currentForecast.getTemperature() + ""); startActivity(myIntent); } }); }*/ } //Called when the activity becomes visible to the user. Also called when coming back to the application from another application (assuming this application wasn't killed). @Override protected void onStart() { super.onStart(); vacationData = new Intent(MainActivity.this, VacationDataActivity.class); //Build and instantiate an instance of the Google API Client if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); } //Attempt to connect to Google Play Services if(mGoogleApiClient != null){ mGoogleApiClient.connect(); } //Set up PlaceAutocompleteFragments and their listeners vacationLocation = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.vacation_location_autocomplete_fragment); vacationLocation.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // Listener for the places fragment in the vacation tab (get whatever is needed from the places argument) vacationLatitude = place.getLatLng().latitude; vacationLongitude = place.getLatLng().longitude; try { vacationAddresses = geocoder.getFromLocation(vacationLatitude, vacationLongitude, 1); } catch (IOException e) { e.printStackTrace(); } } @Override public void onError(Status status) { // TODO: DO STUFF ON ERROR (Toast?) } }); startingLocation = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.starting_location_autocomplete_fragment); startingLocation.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // Listener for the places fragment pertaining to the starting location in the road trip tab (get whatever is needed from the places argument) startingCoordinates = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude); } @Override public void onError(Status status) { // TODO: DO STUFF ON ERROR (Toast?) } }); endingLocation = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.ending_location_autocomplete_fragment); endingLocation.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // Listener for the places fragment pertaining to the ending location in the road trip tab (get whatever is needed from the places argument) endingCoordinates = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude); } @Override public void onError(Status status) { // TODO: DO STUFF ON ERROR (Toast?) } }); // Assign hourly forecast widgets temperature = (TextView) findViewById(R.id.temperature); conditionIcon = (ImageView) findViewById(R.id.conditionIcon); location = (TextView) findViewById(R.id.location); description = (TextView) findViewById(R.id.description); temperature1 = (TextView) findViewById(R.id.temperature1); description1 = (TextView) findViewById(R.id.description1); time1 = (TextView) findViewById(R.id.time1); icon1 = (ImageView) findViewById(R.id.icon1); temperature2 = (TextView) findViewById(R.id.temperature2); description2 = (TextView) findViewById(R.id.description2); time2 = (TextView) findViewById(R.id.time2); icon2 = (ImageView) findViewById(R.id.icon2); temperature3 = (TextView) findViewById(R.id.temperature3); description3 = (TextView) findViewById(R.id.description3); time3 = (TextView) findViewById(R.id.time3); icon3 = (ImageView) findViewById(R.id.icon3); temperature4 = (TextView) findViewById(R.id.temperature4); description4 = (TextView) findViewById(R.id.description4); time4 = (TextView) findViewById(R.id.time4); icon4 = (ImageView) findViewById(R.id.icon4); temperature5 = (TextView) findViewById(R.id.temperature5); description5 = (TextView) findViewById(R.id.description5); time5 = (TextView) findViewById(R.id.time5); icon5 = (ImageView) findViewById(R.id.icon5); temperature6 = (TextView) findViewById(R.id.temperature6); description6 = (TextView) findViewById(R.id.description6); time6 = (TextView) findViewById(R.id.time6); icon6 = (ImageView) findViewById(R.id.icon6); temperature7 = (TextView) findViewById(R.id.temperature7); description7 = (TextView) findViewById(R.id.description7); time7 = (TextView) findViewById(R.id.time7); icon7 = (ImageView) findViewById(R.id.icon7); temperature8 = (TextView) findViewById(R.id.temperature8); description8 = (TextView) findViewById(R.id.description8); time8 = (TextView) findViewById(R.id.time8); icon8 = (ImageView) findViewById(R.id.icon8); temperature9 = (TextView) findViewById(R.id.temperature9); description9 = (TextView) findViewById(R.id.description9); time9 = (TextView) findViewById(R.id.time9); icon9 = (ImageView) findViewById(R.id.icon9); temperature10 = (TextView) findViewById(R.id.temperature10); description10 = (TextView) findViewById(R.id.description10); time10 = (TextView) findViewById(R.id.time10); icon10 = (ImageView) findViewById(R.id.icon10); temperature11 = (TextView) findViewById(R.id.temperature11); description11 = (TextView) findViewById(R.id.description11); time11 = (TextView) findViewById(R.id.time11); icon11 = (ImageView) findViewById(R.id.icon11); temperature12 = (TextView) findViewById(R.id.temperature12); description12 = (TextView) findViewById(R.id.description12); time12 = (TextView) findViewById(R.id.time12); icon12 = (ImageView) findViewById(R.id.icon12); temperature13 = (TextView) findViewById(R.id.temperature13); description13 = (TextView) findViewById(R.id.description13); time13 = (TextView) findViewById(R.id.time13); icon13 = (ImageView) findViewById(R.id.icon13); temperature14 = (TextView) findViewById(R.id.temperature14); description14 = (TextView) findViewById(R.id.description14); time14 = (TextView) findViewById(R.id.time14); icon14 = (ImageView) findViewById(R.id.icon14); temperature15 = (TextView) findViewById(R.id.temperature15); description15 = (TextView) findViewById(R.id.description15); time15 = (TextView) findViewById(R.id.time15); icon15 = (ImageView) findViewById(R.id.icon15); temperature16 = (TextView) findViewById(R.id.temperature16); description16 = (TextView) findViewById(R.id.description16); time16 = (TextView) findViewById(R.id.time16); icon16 = (ImageView) findViewById(R.id.icon16); // Assign daily forecast widget day1icon = (ImageView) findViewById(R.id.day1icon); day1weekday = (TextView) findViewById(R.id.day1weekday); day1condition = (TextView) findViewById(R.id.day1condition); day1low = (TextView) findViewById(R.id.day1low); day1high = (TextView) findViewById(R.id.day1high); day2icon = (ImageView) findViewById(R.id.day2icon); day2weekday = (TextView) findViewById(R.id.day2weekday); day2condition = (TextView) findViewById(R.id.day2condition); day2low = (TextView) findViewById(R.id.day2low); day2high = (TextView) findViewById(R.id.day2high); day3icon = (ImageView) findViewById(R.id.day3icon); day3weekday = (TextView) findViewById(R.id.day3weekday); day3condition = (TextView) findViewById(R.id.day3condition); day3low = (TextView) findViewById(R.id.day3low); day3high = (TextView) findViewById(R.id.day3high); day4icon = (ImageView) findViewById(R.id.day4icon); day4weekday = (TextView) findViewById(R.id.day4weekday); day4condition = (TextView) findViewById(R.id.day4condition); day4low = (TextView) findViewById(R.id.day4low); day4high = (TextView) findViewById(R.id.day4high); day5icon = (ImageView) findViewById(R.id.day5icon); day5weekday = (TextView) findViewById(R.id.day5weekday); day5condition = (TextView) findViewById(R.id.day5condition); day5low = (TextView) findViewById(R.id.day5low); day5high = (TextView) findViewById(R.id.day5high); day6icon = (ImageView) findViewById(R.id.day6icon); day6weekday = (TextView) findViewById(R.id.day6weekday); day6condition = (TextView) findViewById(R.id.day6condition); day6low = (TextView) findViewById(R.id.day6low); day6high = (TextView) findViewById(R.id.day6high); day7icon = (ImageView) findViewById(R.id.day7icon); day7weekday = (TextView) findViewById(R.id.day7weekday); day7condition = (TextView) findViewById(R.id.day7condition); day7low = (TextView) findViewById(R.id.day7low); day7high = (TextView) findViewById(R.id.day7high); // Leave date selector leaveDate = (EditText) findViewById(R.id.leaveDate); leaveDate.setInputType(InputType.TYPE_NULL); calendar = Calendar.getInstance(); leaveDateListener = new DateListener(leaveDate, calendar); leaveDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DatePickerDialog(MainActivity.this, leaveDateListener, calendar .get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show(); } }); // Return date selector returnDate = (EditText) findViewById(R.id.returnDate); returnDate.setInputType(InputType.TYPE_NULL); calendar = Calendar.getInstance(); returnDateListener = new DateListener(returnDate, calendar); returnDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DatePickerDialog(MainActivity.this, returnDateListener, calendar .get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show(); } }); // TODO: Create a class with the predefined method for the onclicklistener submitButton = (Button) findViewById(R.id.submitButton); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(vacationAddresses != null) { if (vacationAddresses.get(0).getCountryCode().equals("US")) { vacationData.putExtra("city", vacationAddresses.get(0).getLocality()); vacationData.putExtra("state", vacationAddresses.get(0).getAdminArea()); } else if (vacationAddresses.get(0).getAdminArea() == null) { vacationData.putExtra("city", vacationAddresses.get(0).getLocality()); vacationData.putExtra("state", vacationAddresses.get(0).getCountryCode()); } else { vacationData.putExtra("city", vacationAddresses.get(0).getAdminArea()); vacationData.putExtra("state", vacationAddresses.get(0).getCountryCode()); } } vacationData.putExtra("leaveDate", leaveDate.getText().toString()); vacationData.putExtra("returnDate", returnDate.getText().toString()); if(vacationData.getStringExtra("city") != null && vacationData.getStringExtra("state") != null && vacationData.getStringExtra("leaveDate") != null && vacationData.getStringExtra("returnDate") != null) { startActivity(vacationData); } else Toast.makeText(MainActivity.this, "Please fill in all fields", Toast.LENGTH_SHORT).show(); } }); // Refresh Handler refreshSwipe = (SwipeRefreshLayout) findViewById(R.id.refresh); refreshSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getLocation(); completeRefresh(); } }); } // Executes once google play services establishes a connection @Override public void onConnected(Bundle arg0) { getLocation(); } // Executes once the connection for google play services is suspended @Override public void onConnectionSuspended(int arg0) { } // Executes if the attempt to connect to google play services fails @Override public void onConnectionFailed(ConnectionResult arg0) { } //use this to get the current location public void getLocation() { int MY_PERMISSION_ACCESS_COARSE_LOCATION = 77; int MY_PERMISSION_ACCESS_FINE_LOCATION = 77; if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_ACCESS_COARSE_LOCATION ); } if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION ); } //get the last location from the GoogleApiClient mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { latitude = mLastLocation.getLatitude(); longitude = mLastLocation.getLongitude(); geocoder = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); city = addresses.get(0).getLocality(); state = addresses.get(0).getAdminArea(); location.setText(city + ", " + state); getCurrentRequest(); getHourlyRequest(); getDailyRequest(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Error getting location. Check your internet connection.", Toast.LENGTH_SHORT).show(); } } //update the map with the current location mapFragment.getMapAsync(this); } private void displayCurrentResults() { try { String iconURL = currentForecast.getConditionImageLink(); new ImageLoaderAST(iconURL, conditionIcon).execute(); temperature.setText("" + currentForecast.getTemperature() + (char) 0x00B0 + " F"); description.setText("" + currentForecast.getCondition()); location.setText("" + city + ", " + state); } catch(Exception e){ Toast.makeText(MainActivity.this, "Error fetching information. Try restarting the application", Toast.LENGTH_SHORT).show(); } } public void displayHourlyResults(){ try { String iconURL = hourlyForecast.getIconURL(0); new ImageLoaderAST(iconURL, icon1).execute(); iconURL = hourlyForecast.getIconURL(1); new ImageLoaderAST(iconURL, icon2).execute(); iconURL = hourlyForecast.getIconURL(2); new ImageLoaderAST(iconURL, icon3).execute(); iconURL = hourlyForecast.getIconURL(3); new ImageLoaderAST(iconURL, icon4).execute(); iconURL = hourlyForecast.getIconURL(4); new ImageLoaderAST(iconURL, icon5).execute(); iconURL = hourlyForecast.getIconURL(5); new ImageLoaderAST(iconURL, icon6).execute(); iconURL = hourlyForecast.getIconURL(6); new ImageLoaderAST(iconURL, icon7).execute(); iconURL = hourlyForecast.getIconURL(7); new ImageLoaderAST(iconURL, icon8).execute(); iconURL = hourlyForecast.getIconURL(8); new ImageLoaderAST(iconURL, icon9).execute(); iconURL = hourlyForecast.getIconURL(9); new ImageLoaderAST(iconURL, icon10).execute(); iconURL = hourlyForecast.getIconURL(10); new ImageLoaderAST(iconURL, icon11).execute(); iconURL = hourlyForecast.getIconURL(11); new ImageLoaderAST(iconURL, icon12).execute(); iconURL = hourlyForecast.getIconURL(12); new ImageLoaderAST(iconURL, icon13).execute(); iconURL = hourlyForecast.getIconURL(13); new ImageLoaderAST(iconURL, icon14).execute(); iconURL = hourlyForecast.getIconURL(14); new ImageLoaderAST(iconURL, icon15).execute(); iconURL = hourlyForecast.getIconURL(15); new ImageLoaderAST(iconURL, icon16).execute(); temperature1.setText("" + hourlyForecast.getTemperatureF(0) + (char) 0x00B0 + " F"); time1.setText("" + hourlyForecast.getHour(0) + ":00" + hourlyForecast.getAMPM(0)); description1.setText("" + hourlyForecast.getCondition(0)); temperature2.setText("" + hourlyForecast.getTemperatureF(1) + (char) 0x00B0 + " F"); time2.setText("" + hourlyForecast.getHour(1) + ":00" + hourlyForecast.getAMPM(1)); description2.setText("" + hourlyForecast.getCondition(1)); temperature3.setText("" + hourlyForecast.getTemperatureF(2) + (char) 0x00B0 + " F"); time3.setText("" + hourlyForecast.getHour(2) + ":00" + hourlyForecast.getAMPM(2)); description3.setText("" + hourlyForecast.getCondition(2)); temperature4.setText("" + hourlyForecast.getTemperatureF(3) + (char) 0x00B0 + " F"); time4.setText("" + hourlyForecast.getHour(3) + ":00" + hourlyForecast.getAMPM(3)); description4.setText("" + hourlyForecast.getCondition(3)); temperature5.setText("" + hourlyForecast.getTemperatureF(4) + (char) 0x00B0 + " F"); time5.setText("" + hourlyForecast.getHour(4) + ":00" + hourlyForecast.getAMPM(4)); description5.setText("" + hourlyForecast.getCondition(4)); temperature6.setText("" + hourlyForecast.getTemperatureF(5) + (char) 0x00B0 + " F"); time6.setText("" + hourlyForecast.getHour(5) + ":00" + hourlyForecast.getAMPM(5)); description6.setText("" + hourlyForecast.getCondition(5)); temperature7.setText("" + hourlyForecast.getTemperatureF(6) + (char) 0x00B0 + " F"); time7.setText("" + hourlyForecast.getHour(6) + ":00" + hourlyForecast.getAMPM(6)); description7.setText("" + hourlyForecast.getCondition(6)); temperature8.setText("" + hourlyForecast.getTemperatureF(7) + (char) 0x00B0 + " F"); time8.setText("" + hourlyForecast.getHour(7) + ":00" + hourlyForecast.getAMPM(7)); description8.setText("" + hourlyForecast.getCondition(7)); temperature9.setText("" + hourlyForecast.getTemperatureF(8) + (char) 0x00B0 + " F"); time9.setText("" + hourlyForecast.getHour(8) + ":00" + hourlyForecast.getAMPM(8)); description9.setText("" + hourlyForecast.getCondition(8)); temperature10.setText("" + hourlyForecast.getTemperatureF(9) + (char) 0x00B0 + " F"); time10.setText("" + hourlyForecast.getHour(9) + ":00" + hourlyForecast.getAMPM(9)); description10.setText("" + hourlyForecast.getCondition(9)); temperature11.setText("" + hourlyForecast.getTemperatureF(10) + (char) 0x00B0 + " F"); time11.setText("" + hourlyForecast.getHour(10) + ":00" + hourlyForecast.getAMPM(10)); description11.setText("" + hourlyForecast.getCondition(10)); temperature12.setText("" + hourlyForecast.getTemperatureF(11) + (char) 0x00B0 + " F"); time12.setText("" + hourlyForecast.getHour(11) + ":00" + hourlyForecast.getAMPM(11)); description12.setText("" + hourlyForecast.getCondition(11)); temperature13.setText("" + hourlyForecast.getTemperatureF(12) + (char) 0x00B0 + " F"); time13.setText("" + hourlyForecast.getHour(12) + ":00" + hourlyForecast.getAMPM(12)); description13.setText("" + hourlyForecast.getCondition(12)); temperature14.setText("" + hourlyForecast.getTemperatureF(13) + (char) 0x00B0 + " F"); time14.setText("" + hourlyForecast.getHour(13) + ":00" + hourlyForecast.getAMPM(13)); description14.setText("" + hourlyForecast.getCondition(13)); temperature15.setText("" + hourlyForecast.getTemperatureF(14) + (char) 0x00B0 + " F"); time15.setText("" + hourlyForecast.getHour(14) + ":00" + hourlyForecast.getAMPM(14)); description15.setText("" + hourlyForecast.getCondition(14)); temperature16.setText("" + hourlyForecast.getTemperatureF(15) + (char) 0x00B0 + " F"); time16.setText("" + hourlyForecast.getHour(15) + ":00" + hourlyForecast.getAMPM(15)); description16.setText("" + hourlyForecast.getCondition(15)); TextView warningText = (TextView) findViewById(R.id.warningText); Boolean rain = false; Boolean snow = false; for (int i = 0; i < 16; i++) { if (hourlyForecast.getCondition(i).contains("Rain") || hourlyForecast.getCondition(i).contains("Shower") || hourlyForecast.getCondition(i).contains("Storm")) { rain = true; } if (hourlyForecast.getCondition(i).contains("Snow Showers") || hourlyForecast.getCondition(i).contains("Snow")) { snow = true; } } if (rain == true && snow == true) { warningText.setText("WARNING: There's rain and snow today!!! Bring an umbrella and bundle up!"); } else if (rain == true) { warningText.setText("WARNING: There's rain today!!! Bring an umbrella!"); } else if (snow == true) { warningText.setText("WARNING: There's snow today!!! Bundle up!"); } } catch(Exception e){ Toast.makeText(MainActivity.this, "Error fetching information. Try restarting the application", Toast.LENGTH_SHORT).show(); } } public void displayDailyResults(){ try { String iconURL = dailyForecast.getIconURL(1); new ImageLoaderAST(iconURL, day1icon).execute(); iconURL = dailyForecast.getIconURL(2); new ImageLoaderAST(iconURL, day2icon).execute(); iconURL = dailyForecast.getIconURL(3); new ImageLoaderAST(iconURL, day3icon).execute(); iconURL = dailyForecast.getIconURL(4); new ImageLoaderAST(iconURL, day4icon).execute(); iconURL = dailyForecast.getIconURL(5); new ImageLoaderAST(iconURL, day5icon).execute(); iconURL = dailyForecast.getIconURL(6); new ImageLoaderAST(iconURL, day6icon).execute(); iconURL = dailyForecast.getIconURL(7); new ImageLoaderAST(iconURL, day7icon).execute(); day1weekday.setText(dailyForecast.getDate(1)); day1condition.setText(dailyForecast.getCondition(1)); day1low.setText("Low: " + dailyForecast.getLow(1) + (char) 0x00B0 + " F"); day1high.setText("High: " + dailyForecast.getHigh(1) + (char) 0x00B0 + " F"); day2weekday.setText(dailyForecast.getDate(2)); day2condition.setText(dailyForecast.getCondition(2)); day2low.setText("Low " + dailyForecast.getLow(2) + (char) 0x00B0 + " F"); day2high.setText("High: " + dailyForecast.getHigh(2) + (char) 0x00B0 + " F"); day3weekday.setText(dailyForecast.getDate(3)); day3condition.setText(dailyForecast.getCondition(3)); day3low.setText("Low: " + dailyForecast.getLow(3) + (char) 0x00B0 + " F"); day3high.setText("High: " + dailyForecast.getHigh(3) + (char) 0x00B0 + " F"); day4weekday.setText(dailyForecast.getDate(4)); day4condition.setText(dailyForecast.getCondition(4)); day4low.setText("Low: " + dailyForecast.getLow(4) + (char) 0x00B0 + " F"); day4high.setText("High: " + dailyForecast.getHigh(4) + (char) 0x00B0 + " F"); day5weekday.setText(dailyForecast.getDate(5)); day5condition.setText(dailyForecast.getCondition(5)); day5low.setText("Low: " + dailyForecast.getLow(5) + (char) 0x00B0 + " F"); day5high.setText("High: " + dailyForecast.getHigh(5) + (char) 0x00B0 + " F"); day6weekday.setText(dailyForecast.getDate(6)); day6condition.setText(dailyForecast.getCondition(6)); day6low.setText("Low: " + dailyForecast.getLow(6) + (char) 0x00B0 + " F"); day6high.setText("High: " + dailyForecast.getHigh(6) + (char) 0x00B0 + " F"); day7weekday.setText(dailyForecast.getDate(7)); day7condition.setText(dailyForecast.getCondition(7)); day7low.setText("Low: " + dailyForecast.getLow(7) + (char) 0x00B0 + " F"); day7high.setText("High: " + dailyForecast.getHigh(7) + (char) 0x00B0 + " F"); } catch(Exception e){ Toast.makeText(MainActivity.this, "Error fetching information. Try restarting the application", Toast.LENGTH_SHORT).show(); } } public void getHourlyRequest(){ new HourlyForecastAST(city, state){ @Override public void onPostExecute(HourlyObject result){ hourlyForecast = result; displayHourlyResults(); } }.execute(); } public void getCurrentRequest(){ new CurrentConditionAST(city, state){ @Override protected void onPostExecute(ConditionsObject item) { currentForecast = item; displayCurrentResults(); } }.execute(); } public void getDailyRequest(){ new DailyForecastAST(city, state){ @Override protected void onPostExecute(DailyObject item) { dailyForecast = item; displayDailyResults(); } }.execute(); } // Begin code for tab 4 @Override public void onMapReady(GoogleMap map) { // Get a handle to the googleMap maps = map; int MY_PERMISSION_ACCESS_COARSE_LOCATION = 77; int MY_PERMISSION_ACCESS_FINE_LOCATION = 77; if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_ACCESS_COARSE_LOCATION ); } if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION ); } map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker arg0) { // Return null so getInfoContents will be called return null; } @Override public View getInfoContents(Marker marker) { // Create the layout that will be used for the information window Context context = getApplicationContext(); LinearLayout info = new LinearLayout(context); info.setOrientation(LinearLayout.VERTICAL); // TextView used to tell the user if it is a starting, interval, or ending point TextView title = new TextView(context); title.setTextColor(Color.BLACK); title.setGravity(Gravity.CENTER); title.setTypeface(null, Typeface.BOLD); title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); title.setText(marker.getTitle()); // TextView used to tell the user the information pertaining to the corresponding interval TextView snippet = new TextView(context); snippet.setGravity(Gravity.CENTER); snippet.setTextColor(Color.GRAY); snippet.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); snippet.setText(marker.getSnippet()); // Add the textViews to the LinearLayout info.addView(title); info.addView(snippet); // Return the layout that will be used for the marker information window return info; } }); // First start, configure the map to how we want it (center upon current location, and enable button to focus on current location) if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED) { if (firstStart == 1) { maps.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15)); maps.setMyLocationEnabled(true); firstStart = 0; } } } public void placeMarkers(View view) { //If the starting and ending points have been initialized then set the markers on the map if (startingCoordinates != null && endingCoordinates != null) { maps.clear(); // Get the route between starting and ending destinations getRouteBetweenPoints(startingCoordinates, endingCoordinates); LatLngBounds tripBounds; if ((startingCoordinates.latitude < endingCoordinates.latitude) && (startingCoordinates.longitude < endingCoordinates.longitude)) { // Constructor of LatLngBounds(LatLng southwest, LatLng northeast) is satisfied, just create the LatLngBounds object. tripBounds = new LatLngBounds(startingCoordinates, endingCoordinates); } else if (startingCoordinates.latitude < endingCoordinates.latitude && (startingCoordinates.longitude > endingCoordinates.longitude)) { // Need to swap starting & ending longitudes to satisfy constructor of LatLngBounds(LatLng southwest, LatLng northeast) tripBounds = new LatLngBounds(new LatLng(startingCoordinates.latitude, endingCoordinates.longitude), new LatLng(endingCoordinates.latitude, startingCoordinates.longitude)); } else if ((startingCoordinates.latitude > endingCoordinates.latitude) && (startingCoordinates.longitude < endingCoordinates.longitude)) { // Need to swap starting & ending latitudes to satisfy constructor of LatLngBounds(LatLng southwest, LatLng northeast) tripBounds = new LatLngBounds(new LatLng(endingCoordinates.latitude, startingCoordinates.longitude), new LatLng(startingCoordinates.latitude, endingCoordinates.longitude)); } else /* (startingCoordinates.latitude > endingCoordinates.latitude) && (startingCoordinates.longitude > endingCoordinates.longitude)*/ { // Need to swap starting & ending coordinates to satisfy constructor of LatLngBounds(LatLng southwest, LatLng northeast) tripBounds = new LatLngBounds(endingCoordinates, startingCoordinates); } maps.moveCamera(CameraUpdateFactory.newLatLngBounds(tripBounds, 48)); //update the map with the corresponding markers for the starting and ending points mapFragment.getMapAsync(this); } else { // Reset the coordinates startingCoordinates = null; endingCoordinates = null; // Let the user know to requery startingLocation.setText(""); endingLocation.setText(""); // Toast to let the user know what to do Toast toast = Toast.makeText(getApplicationContext(), "You must enter both a starting AND an ending location!" + '\n' + "Please try again.", Toast.LENGTH_SHORT); toast.show(); } } @Override protected void onResume() { datasource.open(); // Neet to reopen database on resume super.onResume(); } @Override protected void onPause() { datasource.close(); // Need to close database when the app is paused super.onPause(); } /* Menu Code Provide settings for user to update Serach functionality for a place based on city & state */ public void showPopup(View v) { PopupMenu popup = new PopupMenu(this, v); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.warm: // get prompts.xml view, set temperature range LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); // Set default value for wheel final NumberPicker pickmin = (NumberPicker) promptsView.findViewById(R.id.min); pickmin.setMinValue(0); pickmin.setMaxValue(100); pickmin.setValue(60); pickmin.setWrapSelectorWheel(false); // Set default value for wheel final NumberPicker pickmax = (NumberPicker) promptsView.findViewById(R.id.max); pickmax.setMinValue(0); pickmax.setMaxValue(100); pickmax.setValue(79); pickmin.setWrapSelectorWheel(false); // Update wheels with database values TempRange range = datasource.getWarmRange(); if(range != null){ pickmin.setValue(range.getMin()); pickmax.setValue(range.getMax()); } // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // Update database with new values TempRange range = datasource.getWarmRange(); if(range == null){ datasource.createRange(pickmin.getValue(), pickmax.getValue()); } else{ datasource.updateRange(range, pickmin.getValue(), pickmax.getValue()); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); return true; case R.id.chilly: // get prompts.xml view, set temperature range LayoutInflater li3 = LayoutInflater.from(context); View promptsView3 = li3.inflate(R.layout.prompt, null); AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder3.setView(promptsView3); // Set default value for wheel final NumberPicker pickmin2 = (NumberPicker) promptsView3.findViewById(R.id.min); pickmin2.setMinValue(0); pickmin2.setMaxValue(100); pickmin2.setValue(40); // Set default value for wheel final NumberPicker pickmax2 = (NumberPicker) promptsView3.findViewById(R.id.max); pickmax2.setMinValue(0); pickmax2.setMaxValue(100); pickmax2.setValue(59); // Update wheels with database values TempRange range2 = datasource.getChillyRange(); if(range2 != null){ pickmin2.setValue(range2.getMin()); pickmax2.setValue(range2.getMax()); } // set dialog message alertDialogBuilder3 .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // Update database with new values TempRange range2 = datasource.getChillyRange(); if(range2 == null){ datasource.createRange(pickmin2.getValue(), pickmax2.getValue()); } else{ datasource.updateRange(range2, pickmin2.getValue(), pickmax2.getValue()); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog3 = alertDialogBuilder3.create(); // show it alertDialog3.show(); return true; case R.id.search: // get search_input.xml view, ask user for city & state LayoutInflater li2 = LayoutInflater.from(context); View promptsView2 = li2.inflate(R.layout.search_input, null); AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder2.setView(promptsView2); // Variables used for getting user inputs final EditText cityInput = (EditText) promptsView2.findViewById(R.id.cityInput); final EditText stateInput = (EditText) promptsView2.findViewById(R.id.stateInput); // set dialog message alertDialogBuilder2 .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // Get user inputs final String city_input = cityInput.getText().toString(); final String state_input = stateInput.getText().toString(); // get search_result.xml view LayoutInflater li3 = LayoutInflater.from(context); View promptsView3 = li3.inflate(R.layout.search_result, null); AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder3.setView(promptsView3); final TextView searchResult = (TextView) promptsView3.findViewById(R.id.searchResult); // API call based on city & state provided by user new CurrentConditionAST(city_input, state_input){ @Override protected void onPostExecute(ConditionsObject item) { ConditionsObject resultForecast = item; searchResult.setText("The weather in " + city_input + ", " + state_input + " is " + resultForecast.getTemperature() + (char) 0x00B0 + " F"); displayCurrentResults(); } }.execute(); // set dialog message alertDialogBuilder3 .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog3 = alertDialogBuilder3.create(); // show it alertDialog3.show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog2 = alertDialogBuilder2.create(); // show it alertDialog2.show(); return true; default: return false; } } }); popup.inflate(R.menu.menu); popup.show(); } public void completeRefresh(){ refreshSwipe.setRefreshing(false); } public void getRouteBetweenPoints(final LatLng starting, final LatLng ending) { new GoogleDirectionsAST(starting, ending) { @Override protected void onPostExecute(DirectionsObject item) { directionsObject = item; // Create a list of LatLng objects to get the weather for weatherPoints = new ArrayList<LatLng>(); weatherPoints.add(starting); // Create a counter to keep track of accumulated distance between intervals double counter = 0; // Uses overview polyline (not as laggy but will do for now) String encodedOverviewPolyline = directionsObject.getRoutesArray().getEncodedOverviewPolyLine().getEncodedOverviewPolyline(); polyline = PolyUtil.decode(encodedOverviewPolyline); // Store the total distance for interval calculation double totalDistance = Double.parseDouble(directionsObject.getRoutesArray().getLegsArray().getDistance().getMeters()); /* Get the number of intervals we should have based on the distance between starting and ending we should only get the weather if the trip is greater than 80km */ double numIntervals = 0.0; if (totalDistance >= 80000) { // Divide the total distance by 80km to get how many intervals we should have numIntervals = totalDistance / 80000; } // If the number of intervals is less than 2 and the trip is greater than 1 mile, make an interval at midpoint between starting and ending if (totalDistance >= 1609 && numIntervals < 2) { numIntervals = 2; } // If we have more than 9 intervals, reduce the number of intervals to 9. if (numIntervals > 9) { numIntervals = 9; } // Get the distance between each interval and the previous interval double interval; if (numIntervals > 0.0) { // Divide the total distance by the number of intervals to get the distance between each interval interval = totalDistance / (int) numIntervals; } else { // Else we shouldn't have any intervals other than starting and ending points interval = Double.MAX_VALUE; } // Add all LatLng objects that create the polyline for (int i = 0; i < polyline.size() - 1; ++i) { // Add the interval polyline to the map maps.addPolyline(new PolylineOptions().add(polyline.get(i), polyline.get(i+1)).width(8).color(Color.rgb(93,188,210))); // Keep track of which LatLng objects to get weather information for, store each object in weatherPoints counter += SphericalUtil.computeDistanceBetween(polyline.get(i), polyline.get(i+1)); if (counter >= interval) { weatherPoints.add(polyline.get(i)); counter = SphericalUtil.computeDistanceBetween(polyline.get(i), polyline.get(i+1)); } } // Add the final interval point weatherPoints.add(ending); // If there are more than 3 points on the map... if (weatherPoints.size() > 3) { // Check whether the second to last point is too close to the ending point double distBetweenEndingAndSecondToEnding = SphericalUtil.computeDistanceBetween(weatherPoints.get(weatherPoints.size() - 2), weatherPoints.get(weatherPoints.size() - 1)); double distBetweenSecondToEndingAndThirdToEnding = SphericalUtil.computeDistanceBetween(weatherPoints.get(weatherPoints.size() - 3), weatherPoints.get(weatherPoints.size() - 2)); if (distBetweenEndingAndSecondToEnding < 0.5 * distBetweenSecondToEndingAndThirdToEnding) { weatherPoints.remove(weatherPoints.size() - 2); } } try { // Get the information pertaining to each interval in weatherPoints getIntervalInformation(weatherPoints); } catch (Exception e) { Toast.makeText(MainActivity.this, "Error getting the map information, try again!", Toast.LENGTH_SHORT).show(); } // MOST ACCURATE POLYLINE, BUT EXTREMELY LAGGY!!! /*ArrayList<StepsArrayItem> stepsArrayItems = directionsObject.getRoutesArray().getLegsArray().getStepsArray().getStepsArrayItems(); for(int i = 0; i < stepsArrayItems.size(); ++i) { List<LatLng> encodedPolyline = stepsArrayItems.get(i).getEncodedPolyline().getPolyline(); for(int j = 0; j < encodedPolyline.size() - 1; ++j) { Polyline line = maps.addPolyline(new PolylineOptions().add(encodedPolyline.get(j), encodedPolyline.get(j + 1)).width(5).color(Color.RED)); } }*/ } }.execute(); } public void getIntervalInformation (ArrayList<LatLng> intervals) { try { // Get the MarkerOptions for the intervals passed into the markers new IntervalInformationAST(intervals) { @Override protected void onPostExecute(MapInformation mapInformation) { markers = mapInformation.intervalInformation; // ArrayLists holding overallSuggestions ArrayList<String> overallMisc = new ArrayList<>(); ArrayList<String> overallUpperbody = new ArrayList<>(); ArrayList<String> overallLowerbody = new ArrayList<>(); ArrayList<String> overallShoes = new ArrayList<>(); // Get the overall suggestions for (int i = 0; i < mapInformation.intervalTemperatures.size(); ++i) { ArrayList<String> misc = clothes.getMisc(mapInformation.intervalTemperatures.get(i)); for (int j = 0; j < misc.size(); ++j) { if (misc.size() == 0) { break; } if (!overallMisc.contains(misc.get(j))) { overallMisc.add(misc.get(j)); } } ArrayList<String> upperbody = clothes.getUpperBody(mapInformation.intervalTemperatures.get(i)); for (int j = 0; j < upperbody.size(); ++j) { if (upperbody.size() == 0) { break; } if (!overallUpperbody.contains(upperbody.get(j))) { overallUpperbody.add(upperbody.get(j)); } } ArrayList<String> lowerbody = clothes.getLowerBody(mapInformation.intervalTemperatures.get(i)); for (int j = 0; j < lowerbody.size(); ++j) { if (lowerbody.size() == 0) { break; } if (!overallLowerbody.contains(lowerbody.get(j))) { overallLowerbody.add(lowerbody.get(j)); } } ArrayList<String> shoes = clothes.getShoes(mapInformation.intervalTemperatures.get(i)); for (int j = 0; j < shoes.size(); ++j) { if (shoes.size() == 0) { break; } if (!overallShoes.contains(shoes.get(j))) { overallShoes.add(shoes.get(j)); } } } // If the returned list is not null, then add the markers to the map if (markers != null) { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.intervalInformationLayout); linearLayout.removeAllViews(); // Display the overallSuggestions TextView intervalDetailsTitle = (TextView) findViewById(R.id.intervalDetailsTitle); intervalDetailsTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); intervalDetailsTitle.setText("Interval Details"); IntervalAdapter adapter = new IntervalAdapter(context, mapInformation, clothes); for (int i = 0; i < markers.size(); ++i) { linearLayout.addView(adapter.getView(i, null, null)); maps.addMarker(markers.get(i)); } // Display the overallSuggestions TextView overallSuggestionsTitle = (TextView) findViewById(R.id.overallSuggestionTitleTextView); overallSuggestionsTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); overallSuggestionsTitle.setText("Bring these on your trip!"); TextView overallSuggestions = (TextView) findViewById(R.id.overallSuggestionTextView); overallSuggestions.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); String misc = overallMisc.toString(); if (misc.length() == 2) { misc = "[N/A]"; } String upperbody = overallUpperbody.toString(); if (upperbody.length() == 2) { upperbody = "[N/A]"; } String lowerbody = overallLowerbody.toString(); if (lowerbody.length() == 2) { lowerbody = "[N/A]"; } String shoes = overallShoes.toString(); if (shoes.length() == 2) { shoes = "[N/A]"; } overallSuggestions.setText("Miscellaneous:" + '\n' + misc.substring(1, misc.length() - 1) + "\n\n" + "Upperbody:" + '\n' + upperbody.substring(1, upperbody.length() - 1) + "\n\n" + "Lowerbody:" + '\n' + lowerbody.substring(1, lowerbody.length() - 1) + "\n\n" + "Shoes:" + '\n' + shoes.substring(1, shoes.length() - 1) + '\n'); } // Else, notify the user that the attempt to get information has failed. else { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.intervalInformationLayout); linearLayout.removeAllViews(); TextView overallSuggestionsTitle = (TextView) findViewById(R.id.overallSuggestionTextView); overallSuggestionsTitle.setText(null); overallSuggestionsTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 0); TextView intervalDetailsTitle = (TextView) findViewById(R.id.intervalDetailsTitle); intervalDetailsTitle.setText(null); intervalDetailsTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 0); TextView overallSuggestions = (TextView) findViewById(R.id.overallSuggestionTextView); overallSuggestions.setText(null); overallSuggestions.setTextSize(TypedValue.COMPLEX_UNIT_SP, 0); Toast toast = Toast.makeText(getApplicationContext(), "An error has occured while trying to fetch the queried route." + '\n' + "Please try again!", Toast.LENGTH_SHORT); toast.show(); maps.clear(); } } }.execute(); // Refresh the map this.updateMap(); } catch (Exception e) { Toast.makeText(MainActivity.this, "Error getting the map information, try again!", Toast.LENGTH_SHORT).show(); } } public void updateMap() { mapFragment.getMapAsync(this); } // End Code for tab 4 }
package ljdp.minechem.common.items; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; public class ItemFusionStar extends Item { public ItemFusionStar(int id) { super(id); setMaxStackSize(1); this.setMaxDamage(2000); this.setNoRepair(); this.setUnlocalizedName("name.fusionStar"); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4) { int damage = itemStack.getItemDamage(); int usesLeft = damage - 2000; int percentFinal = usesLeft / 2000; list.add(percentFinal + " % Remaining "); } @Override @SideOnly(Side.CLIENT) public Icon getIconFromDamage(int par1) { return Item.netherStar.getIconFromDamage(par1); } @Override public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) { return false; } }
package de.gurkenlabs.litiengine.configuration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.File; import java.util.UUID; import java.util.logging.Logger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.gurkenlabs.litiengine.util.io.FileUtilities; public class ConfigurationTests { private static void deleteTempConfigFile(final Configuration config) { if (config != null) { final File configFile = new File(config.getFileName()); if (configFile.exists()) { configFile.delete(); } } } @BeforeEach public void setup() { Logger.getLogger(FileUtilities.class.getName()).setUseParentHandlers(false); Logger.getLogger(Configuration.class.getName()).setUseParentHandlers(false); } @Test public void testConfigurationGroupInitialization() { Configuration config = null; final TestConfigurationGroup group = new TestConfigurationGroup(); try { config = new Configuration(group); config.load(); assertTrue(config.getConfigurationGroup(group.getClass()).equals(group)); assertEquals("test-prefix", group.getPrefix()); assertTrue(config.getConfigurationGroup("test-prefix").equals(group)); } finally { deleteTempConfigFile(config); } } @Test public void testDefaultFileCreation() { Configuration config = null; try { config = new Configuration(); config.load(); assertTrue(new File(config.getFileName()).exists()); } finally { deleteTempConfigFile(config); } } @Test public void testFieldInitialization() { Configuration config = null; final TestConfigurationGroup group = new TestConfigurationGroup(); try { deleteTempConfigFile(config); config = new Configuration(group); config.load(); assertTrue(new File(config.getFileName()).exists()); config.load(); final TestConfigurationGroup configGroup = config.getConfigurationGroup(TestConfigurationGroup.class); assertEquals(100, configGroup.getTestInt()); assertEquals(101, configGroup.getTestByte()); assertEquals(102, configGroup.getTestShort()); assertEquals(103, configGroup.getTestLong()); assertEquals(104.0d, configGroup.getTestDouble(), 0.00001); assertEquals(105.0f, configGroup.getTestFloat(), 0.00001f); assertEquals("test", configGroup.getTestString()); assertEquals(true, configGroup.isTestBoolean()); assertEquals(TEST.TEST1, configGroup.getTestEnum()); assertEquals("", configGroup.getTestWithNoSetter()); System.out.println(new String[] { "test", "testicle" }); System.out.println(configGroup.getTestStringArray()); assertArrayEquals(new String[] { "test", "testicle" }, configGroup.getTestStringArray()); } finally { deleteTempConfigFile(config); } } @Test public void testFileName() { final String testFileName = UUID.randomUUID().toString() + ".properties"; Configuration config = null; try { config = new Configuration(testFileName); config.load(); assertTrue(new File(testFileName).exists()); } finally { deleteTempConfigFile(config); } } private enum TEST { TEST1, TEST2; } @ConfigurationGroupInfo(prefix = "test-prefix") @SuppressWarnings("unused") private class TestConfigurationGroup extends ConfigurationGroup { private int testInt = 100; private byte testByte = 101; private short testShort = 102; private long testLong = 103; private double testDouble = 104.0d; private float testFloat = 105.0f; private String testString = "test"; private boolean testBoolean = true; private TEST testEnum = TEST.TEST1; private String[] testStringArray = new String[] { "test", "testicle" }; private String testWithNoSetter; public byte getTestByte() { return this.testByte; } public double getTestDouble() { return this.testDouble; } public TEST getTestEnum() { return this.testEnum; } public float getTestFloat() { return this.testFloat; } public int getTestInt() { return this.testInt; } public long getTestLong() { return this.testLong; } public short getTestShort() { return this.testShort; } public String getTestString() { return this.testString; } public boolean isTestBoolean() { return this.testBoolean; } public void setTestBoolean(final boolean testBoolean) { this.testBoolean = testBoolean; } public void setTestByte(final byte testByte) { this.testByte = testByte; } public void setTestDouble(final double testDouble) { this.testDouble = testDouble; } public void setTestEnum(final TEST testEnum) { this.testEnum = testEnum; } public void setTestFloat(final float testFloat) { this.testFloat = testFloat; } public void setTestInt(final int test1) { this.testInt = test1; } public void setTestLong(final long testLong) { this.testLong = testLong; } public void setTestShort(final short testShort) { this.testShort = testShort; } public void setTestString(final String testString) { this.testString = testString; } public String[] getTestStringArray() { return testStringArray; } public void setTestStringArray(String[] testStringArray) { this.testStringArray = testStringArray; } public String getTestWithNoSetter() { return testWithNoSetter; } } }
package io.spine.test; import io.spine.test.TimeTests.BackToTheFuture; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static io.spine.test.TimeTests.BackToTheFuture.THIRTY_YEARS_IN_HOURS; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Alexander Yevsyukov */ public class BackToTheFutureShould { private BackToTheFuture timeProvider; @Before public void setUp() { timeProvider = new BackToTheFuture(); } @Test public void create_with_start_in_the_future() { assertTrue(TimeTests.Future.isFuture(timeProvider.getCurrentTime())); } @Test public void rewind_backward() { // Rewind to somewhere around present. Assert.assertNotEquals(timeProvider.getCurrentTime(), timeProvider.backward(THIRTY_YEARS_IN_HOURS)); // ... and back to 30 years in the past. timeProvider.backward(THIRTY_YEARS_IN_HOURS); assertFalse(TimeTests.Future.isFuture(timeProvider.getCurrentTime())); } @SuppressWarnings("MagicNumber") @Test public void rewind_forward() { // Rewind to somewhere around present. timeProvider.backward(THIRTY_YEARS_IN_HOURS); timeProvider.forward(THIRTY_YEARS_IN_HOURS + 24L); assertTrue(TimeTests.Future.isFuture(timeProvider.getCurrentTime())); } }
package com.italikdesign.pont.chaban; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatDelegate; import android.support.v7.app.NotificationCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.italikdesign.inappbilling.util.IabException; import com.italikdesign.inappbilling.util.IabHelper; import com.italikdesign.inappbilling.util.IabResult; import com.italikdesign.inappbilling.util.Inventory; import com.italikdesign.inappbilling.util.Purchase; import com.onesignal.OneSignal; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "com.italikdesign.inappbilling"; public static final String ITEM_SKU = "test8"; NavigationView navigationView = null; Toolbar toolbar = null; IabHelper mHelper; boolean mIsPremium = false; boolean mIsUserPremium = false; boolean searchAllowed = false; static boolean active = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); toolbar.setTitle("Le Pont Chaban Delmas"); toolbar.setSubtitle("Dates et Heures de Levées"); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); navigationView = (NavigationView) findViewById(R.id.nav_view); //How to change elements in the header programatically View headerView = navigationView.getHeaderView(0); TextView emailText = (TextView) headerView.findViewById(R.id.subnav); emailText.setText("Les Levées"); navigationView.setNavigationItemSelectedListener(this); //Preferences App-billing SharedPreferences prefs = getSharedPreferences( "com.italikdesign.pont.chaban", 0); mIsPremium = prefs.getBoolean("premium", false); if (mIsPremium) { MainFragmentDisAd fragment = new MainFragmentDisAd(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } else { MainFragment fragment = new MainFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } //InAppBilling String base64EncodedPublicKey = getString(R.string.base64); // compute your public key and store it in base64EncodedPublicKey mHelper = new IabHelper(this, base64EncodedPublicKey); int status = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); // Showing status if (status != ConnectionResult.SUCCESS) { mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { @SuppressLint("LongLogTag") public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { // Oh no, there was a problem. Log.d(TAG, "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up. Now, let's get an inventory of Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } } ); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressLint("LongLogTag") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data); } else { Log.i(TAG, "onActivityResult handled by IABUtil."); } } IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { @SuppressLint("LongLogTag") @Override public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.d(TAG, "Achat validé: " + result + ", achat: " + purchase); if (result.isFailure()) { complain("erreur lors de l'achat: " + result); // Handle error return; } if (!verifyDeveloperPayload(purchase)) { complain("Error purchasing. Authenticity verification failed."); return; } Log.d(TAG, "Purchase successful."); if (purchase.getSku().equals(ITEM_SKU)) { // bought the premium upgrade! Log.d(TAG, "Purchase is premium upgrade. Congratulating user."); alert("Thank you for upgrading to premium!"); mIsPremium = true; SharedPreferences prefs = getBaseContext().getSharedPreferences( "com.italikdesign.pont.chaban", 0); prefs.edit().putBoolean("premium", true).apply(); } } }; IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { @SuppressLint("LongLogTag") @Override public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); if (result.isFailure()) { complain("Failed to query inventory: " + result); return; } /*if (inventory.hasPurchase(PREM_SKU)) { mHelper.consumeAsync(inventory.getPurchase(PREM_SKU), null); }*/ Log.d(TAG, "Query inventory was successful."); Purchase premiumPurchase = inventory.getPurchase(ITEM_SKU); mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); if (mIsPremium) { searchAllowed = true; mIsUserPremium = true; Log.d(TAG, "Should be premium by now..."); SharedPreferences prefs = getBaseContext().getSharedPreferences( "com.italikdesign.pont.chaban", 0); prefs.edit().putBoolean("premium", true).apply(); } Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. * It will be the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase * and verifying it here might seem like a good approach, but this will * fail in the case where the user purchases an item on one device and * then uses your app on a different device, because on the other device * you will not have access to the random string you originally * generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different * between them, so that one user's purchase can't be replayed to * another user. * * 2. The payload must be such that you can verify it even when the app * wasn't the one who initiated the purchase flow (so that items * purchased by the user on one device work on other devices owned by * the user). * * Using your own server to store and verify developer payloads across * app installations is recommended. */ return true; } /*public void consumeItem() { mHelper.queryInventoryAsync(mReceivedInventoryListener); }*/ IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() { @Override public void onQueryInventoryFinished(IabResult result, Inventory inventory) { if (result.isFailure()) { // Handle failure } else { searchAllowed = false; //mHelper.consumeAsync(inventory.getPurchase(PREM_SKU), // mConsumeFinishedListener); } } }; IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { @Override public void onConsumeFinished(Purchase purchase, IabResult result) { if (result.isSuccess()) { } else { // handle error } } }; @Override public void onDestroy() { super.onDestroy(); if (mHelper != null) mHelper.dispose(); mHelper = null; } @SuppressLint("LongLogTag") void complain(String message) { Log.e(TAG, "**** TrivialDrive Error: " + message); alert("Error: " + message); } @SuppressLint("LongLogTag") void alert(String message) { AlertDialog.Builder bld = new AlertDialog.Builder(this); bld.setMessage(message); bld.setNeutralButton("OK", null); Log.d(TAG, "Showing alert dialog: " + message); bld.create().show(); } @SuppressLint("LongLogTag") @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_agenda) { if (mIsPremium) { MainFragmentDisAd fragment = new MainFragmentDisAd(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } else { MainFragment fragment = new MainFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } } // Handle the camera action else if (id == R.id.nav_notification) { Preferences fragment = new Preferences(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } else if (id == R.id.nav_cadena) { Log.d(TAG, "Upgrade button clicked; launching purchase flow for upgrade."); /* * TODO: for security, generate your payload here for verification. See * the comments on verifyDeveloperPayload() for more info. Since this is * a SAMPLE, we just use an empty string, but on a production app you * should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001, mPurchaseFinishedListener, payload); } else if (id == R.id.nav_apropos) { //Set the fragment initially AproposFragment fragment = new AproposFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } else if (id == R.id.nav_share) { Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name)); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.partage)); startActivity(Intent.createChooser(shareIntent, getString(R.string.app_name))); } else if (id == R.id.nav_github) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://github.com/marlenech/PontChabanDelmas")); startActivity(intent); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } //for Pushbots (customPushReceiver) public static boolean isActive(){ return active; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { } static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } }
package de.lessvoid.nifty.elements; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import de.lessvoid.nifty.EndNotify; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEvent; import de.lessvoid.nifty.NiftyMethodInvoker; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.FocusHandler; import de.lessvoid.nifty.controls.NiftyControl; import de.lessvoid.nifty.controls.NiftyInputControl; import de.lessvoid.nifty.effects.Effect; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.effects.EffectImpl; import de.lessvoid.nifty.effects.EffectManager; import de.lessvoid.nifty.effects.ElementEffectStateCache; import de.lessvoid.nifty.effects.Falloff; import de.lessvoid.nifty.elements.events.ElementDisableEvent; import de.lessvoid.nifty.elements.events.ElementEnableEvent; import de.lessvoid.nifty.elements.events.ElementHideEvent; import de.lessvoid.nifty.elements.events.ElementShowEvent; import de.lessvoid.nifty.elements.render.ElementRenderer; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.elements.render.PanelRenderer; import de.lessvoid.nifty.elements.render.TextRenderer; import de.lessvoid.nifty.elements.tools.ElementTreeTraverser; import de.lessvoid.nifty.input.NiftyMouseInputEvent; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.layout.BoxConstraints; import de.lessvoid.nifty.layout.LayoutPart; import de.lessvoid.nifty.layout.align.HorizontalAlign; import de.lessvoid.nifty.layout.align.VerticalAlign; import de.lessvoid.nifty.layout.manager.LayoutManager; import de.lessvoid.nifty.loaderv2.types.ElementType; import de.lessvoid.nifty.loaderv2.types.PopupType; import de.lessvoid.nifty.loaderv2.types.apply.ApplyRenderText; import de.lessvoid.nifty.loaderv2.types.apply.ApplyRenderer; import de.lessvoid.nifty.loaderv2.types.apply.ApplyRendererImage; import de.lessvoid.nifty.loaderv2.types.apply.ApplyRendererPanel; import de.lessvoid.nifty.loaderv2.types.apply.Convert; import de.lessvoid.nifty.loaderv2.types.helper.PaddingAttributeParser; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.MouseOverHandler; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.spi.time.TimeProvider; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; /** * @author void */ public class Element implements NiftyEvent, EffectManager.Notify { @Nonnull private static final Logger log = Logger.getLogger(Element.class.getName()); @Nonnull private final ElementType elementType; @Nullable private String id; private int renderOrder; @Nullable private Element parent; @Nullable private List<Element> children; /** * This set defines the render order of the child elements using a Comparator. */ @Nullable private Set<Element> elementsRenderOrderSet; /** * This is the shared instance of the comparator used to get the rendering oder for the child elements of another * element. */ @Nonnull private static final Comparator<Element> RENDER_ORDER_COMPARATOR = new RenderOrderComparator(); /** * We keep a copy of the elementsRenderOrderSet in a simple array for being more GC friendly while rendering. */ @Nullable private Element[] elementsRenderOrder; /** * The LayoutManager we should use for all child elements. */ @Nullable private LayoutManager layoutManager; /** * The LayoutPart for laying out this element. */ @Nonnull private final LayoutPart layoutPart; /** * The ElementRenderer we should use to render this element. */ @Nonnull private final ElementRenderer[] elementRenderer; @Nonnull private EffectManager effectManager; @Nonnull private ElementInteraction interaction; /** * Effect state cache (this includes info about the child state) and is only * update when Effect states are changed. */ @Nonnull private final ElementEffectStateCache effectStateCache = new ElementEffectStateCache(); /** * Nifty instance this element is attached to. */ @Nonnull private final Nifty nifty; /** * The focus handler this element is attached to. */ @Nonnull private final FocusHandler focusHandler; /** * Whether the element is enabled or not. */ private boolean enabled; /** * This helps us to keep track when you enable or disable this multiple times. We don't want * to start the onEnabled/onDisabled effects when the element is already enabled/disabled. */ private int enabledCount; /** * Whether the element is visible or not. */ private boolean visible; /** * this is set to true, when there's no interaction with the element * possible. this happens when the onEndScreen effect starts. */ private boolean done; /** * this is set to true when there's no interaction with this element possibe. * (as long as onStartScreen and onEndScreen events are active even when this * element is not using the onStartScreen effect at all but a parent element did) */ private boolean interactionBlocked; /** * Whether the element is visible to mouse events. */ private boolean visibleToMouseEvents; private boolean clipChildren; /** * The attached control when this element is a control. */ @Nullable private NiftyInputControl attachedInputControl = null; /** * Whether this element can be focused or not. */ private boolean focusable = false; /** * This attribute determines the element before (!) the new element will be inserted into the focusHandler. * You can set this to any element id on the screen and this element will be inserted right before the * given element. This is especially useful when you dynamically remove and add elements and you need to * enforce a specific focus order. * <p/> * The default value is null which will simply add the elements as they are created. */ @Nullable private String focusableInsertBeforeElementId; /** * The screen this element is part of. */ @Nullable private Screen screen; @Nonnull private TimeProvider time; @Nonnull private final List<String> elementDebugOut = new ArrayList<String>(); @Nonnull private final StringBuilder elementDebug = new StringBuilder(); private boolean parentClipArea = false; private int parentClipX; private int parentClipY; private int parentClipWidth; private int parentClipHeight; // this will be set to true when constraints, padding, margin and so on have been changed and this change should // publish an event on the event bus later private boolean constraintsChanged; /* * Whether or not this element should ignore all mouse events. */ private boolean ignoreMouseEvents; /* * Whether or not this element should ignore all keyboard events. */ private boolean ignoreKeyboardEvents; @Nonnull private static final Convert convert; @Nonnull private static final Map<Class<? extends ElementRenderer>, ApplyRenderer> rendererApplier; static { convert = new Convert(); rendererApplier = new HashMap<Class<? extends ElementRenderer>, ApplyRenderer>(); rendererApplier.put(TextRenderer.class, new ApplyRenderText(convert)); rendererApplier.put(ImageRenderer.class, new ApplyRendererImage(convert)); rendererApplier.put(PanelRenderer.class, new ApplyRendererPanel(convert)); } @Nullable private Map<String, Object> userData; public Element( @Nonnull final Nifty nifty, @Nonnull final ElementType elementType, @Nullable final String id, @Nullable final Element parent, @Nonnull final FocusHandler focusHandler, final boolean visibleToMouseEvents, @Nonnull final TimeProvider timeProvider, @Nonnull final ElementRenderer... elementRenderer) { this( nifty, elementType, id, parent, new LayoutPart(), focusHandler, visibleToMouseEvents, timeProvider, elementRenderer); } /** * Use this constructor to specify a LayoutPart */ public Element( @Nonnull final Nifty nifty, @Nonnull final ElementType elementType, @Nullable final String id, @Nullable final Element parent, @Nonnull final LayoutPart layoutPart, @Nonnull final FocusHandler focusHandler, final boolean visibleToMouseEvents, @Nonnull final TimeProvider timeProvider, @Nonnull final ElementRenderer... elementRenderer) { this.nifty = nifty; this.elementType = elementType; this.id = id; this.parent = parent; this.elementRenderer = elementRenderer; this.effectManager = new EffectManager(this); this.effectManager.setAlternateKey(this.nifty.getAlternateKey()); this.layoutPart = layoutPart; this.enabled = true; this.enabledCount = 0; this.visible = true; this.done = false; this.interactionBlocked = false; this.focusHandler = focusHandler; this.visibleToMouseEvents = visibleToMouseEvents; this.time = timeProvider; this.interaction = new ElementInteraction(this.nifty, this); } /** * This is used when the element is being created from an ElementType in the loading process. */ public void initializeFromAttributes( @Nonnull final Screen targetScreen, @Nonnull final Attributes attributes, @Nonnull final NiftyRenderEngine renderEngine) { BoxConstraints boxConstraints = layoutPart.getBoxConstraints(); boxConstraints.setHeight(convert.sizeValue(attributes.get("height"))); boxConstraints.setWidth(convert.sizeValue(attributes.get("width"))); boxConstraints.setX(convert.sizeValue(attributes.get("x"))); boxConstraints.setY(convert.sizeValue(attributes.get("y"))); boxConstraints.setHorizontalAlign(convert.horizontalAlign(attributes.get("align"))); boxConstraints.setVerticalAlign(convert.verticalAlign(attributes.get("valign"))); String paddingLeft = Convert.DEFAULT_PADDING; String paddingRight = Convert.DEFAULT_PADDING; String paddingTop = Convert.DEFAULT_PADDING; String paddingBottom = Convert.DEFAULT_PADDING; if (attributes.isSet("padding")) { try { String padding = attributes.get("padding"); assert padding != null; // checked by isSet PaddingAttributeParser paddingParser = new PaddingAttributeParser(padding); paddingLeft = paddingParser.getLeft(); paddingRight = paddingParser.getRight(); paddingTop = paddingParser.getTop(); paddingBottom = paddingParser.getBottom(); } catch (Exception e) { log.warning(e.getMessage()); } } boxConstraints.setPaddingLeft(convert.paddingSizeValue(attributes.get("paddingLeft"), paddingLeft)); boxConstraints.setPaddingRight(convert.paddingSizeValue(attributes.get("paddingRight"), paddingRight)); boxConstraints.setPaddingTop(convert.paddingSizeValue(attributes.get("paddingTop"), paddingTop)); boxConstraints.setPaddingBottom(convert.paddingSizeValue(attributes.get("paddingBottom"), paddingBottom)); String marginLeft = Convert.DEFAULT_MARGIN; String marginRight = Convert.DEFAULT_MARGIN; String marginTop = Convert.DEFAULT_MARGIN; String marginBottom = Convert.DEFAULT_MARGIN; if (attributes.isSet("margin")) { try { String margin = attributes.get("margin"); assert margin != null; // checked by isSet PaddingAttributeParser marginParser = new PaddingAttributeParser(margin); marginLeft = marginParser.getLeft(); marginRight = marginParser.getRight(); marginTop = marginParser.getTop(); marginBottom = marginParser.getBottom(); } catch (Exception e) { log.warning(e.getMessage()); } } boxConstraints.setMarginLeft(convert.paddingSizeValue(attributes.get("marginLeft"), marginLeft)); boxConstraints.setMarginRight(convert.paddingSizeValue(attributes.get("marginRight"), marginRight)); boxConstraints.setMarginTop(convert.paddingSizeValue(attributes.get("marginTop"), marginTop)); boxConstraints.setMarginBottom(convert.paddingSizeValue(attributes.get("marginBottom"), marginBottom)); this.clipChildren = attributes.getAsBoolean("childClip", Convert.DEFAULT_CHILD_CLIP); this.renderOrder = attributes.getAsInteger("renderOrder", Convert.DEFAULT_RENDER_ORDER); boolean visible = attributes.getAsBoolean("visible", Convert.DEFAULT_VISIBLE); if (visible) { this.visible = true; } this.visibleToMouseEvents = attributes.getAsBoolean("visibleToMouse", Convert.DEFAULT_VISIBLE_TO_MOUSE); this.layoutManager = convert.layoutManager(attributes.get("childLayout")); this.focusable = attributes.getAsBoolean("focusable", Convert.DEFAULT_FOCUSABLE); this.focusableInsertBeforeElementId = attributes.get("focusableInsertBeforeElementId"); for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; ApplyRenderer rendererApply = rendererApplier.get(renderer.getClass()); rendererApply.apply(targetScreen, this, attributes, renderEngine); } } public void initializeFromPostAttributes(@Nonnull final Attributes attributes) { visible = attributes.getAsBoolean("visible", Convert.DEFAULT_VISIBLE); } @Nullable public String getId() { return id; } /** * Get the parent of this element. * * @return either the parent of the element or {@code this} in case the element is the root element */ @Nonnull public Element getParent() { return parent == null ? this : parent; } /** * Check if this element has a parent. If this is not the case the element is a root element. * * @return {@code true} in case the element has a parent */ public boolean hasParent() { return parent != null; } public void setParent(@Nullable final Element element) { parent = element; // This element has a new parent. Check the parent's clip area and update this element accordingly. if (parentHasClipArea()) { setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight); publishEvent(); } else { parentClipArea = false; } } private boolean parentHasClipArea() { if (parent == null) { return false; } return parent.parentClipArea; } @Nonnull public String getElementStateString(@Nonnull final String offset) { return getElementStateString(offset, ".*"); } @Nonnull public String getElementStateString(@Nonnull final String offset, @Nonnull final String regex) { elementDebugOut.clear(); elementDebugOut.add(" type: [" + elementType.output(offset.length()) + "]"); elementDebugOut.add(" style [" + getElementType().getAttributes().get("style") + "]"); elementDebugOut.add(" state [" + getState() + "]"); elementDebugOut.add(" position [x=" + getX() + ", y=" + getY() + ", w=" + getWidth() + ", h=" + getHeight() + "]"); elementDebugOut.add(" constraint [" + outputSizeValue(layoutPart.getBoxConstraints().getX()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getY()) + ", " + outputSizeValue(layoutPart .getBoxConstraints().getWidth()) + ", " + outputSizeValue(layoutPart.getBoxConstraints().getHeight()) + "]"); elementDebugOut.add(" padding [" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingLeft()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingRight()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingTop()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getPaddingBottom()) + "]"); elementDebugOut.add(" margin [" + outputSizeValue(layoutPart.getBoxConstraints().getMarginLeft()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginRight()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginTop()) + ", " + "" + outputSizeValue(layoutPart.getBoxConstraints().getMarginBottom()) + "]"); StringBuilder state = new StringBuilder(); if (focusable) { state.append(" focusable"); } if (enabled) { if (state.length() > 0) { state.append(","); } state.append(" enabled(").append(enabledCount).append(")"); } if (visible) { if (state.length() > 0) { state.append(","); } state.append(" visible"); } if (visibleToMouseEvents) { if (state.length() > 0) { state.append(","); } state.append(" mouseable"); } if (clipChildren) { if (state.length() > 0) { state.append(","); } state.append(" clipChildren"); } elementDebugOut.add(" flags [" + state + "]"); elementDebugOut.add(" effects [" + effectManager.getStateString(offset) + "]"); elementDebugOut.add(" renderOrder [" + renderOrder + "]"); if (parentClipArea) { elementDebugOut.add(" parent clip [x=" + parentClipX + ", y=" + parentClipY + ", w=" + parentClipWidth + ", " + "h=" + parentClipHeight + "]"); } StringBuilder renderOrder = new StringBuilder(); renderOrder.append(" render order: "); if (children != null && elementsRenderOrderSet != null) { for (Element e : elementsRenderOrderSet) { renderOrder.append("[").append(e.id).append(" (") .append((e.renderOrder == 0) ? children.indexOf(e) : e.renderOrder).append(")]"); } } elementDebugOut.add(renderOrder.toString()); elementDebug.delete(0, elementDebug.length()); for (int i = 0; i < elementDebugOut.size(); i++) { String line = elementDebugOut.get(i); if (line.matches(regex)) { if (elementDebug.length() > 0) { elementDebug.append("\n").append(offset); } elementDebug.append(line); } } return elementDebug.toString(); } @Nonnull private String getState() { if (isEffectActive(EffectEventId.onStartScreen)) { return "starting"; } if (isEffectActive(EffectEventId.onEndScreen)) { return "ending"; } if (!visible) { return "hidden"; } if (interactionBlocked) { return "interactionBlocked"; } if (!enabled) { return "disabled"; } return "normal"; } @Nullable private String outputSizeValue(@Nullable final SizeValue value) { if (value == null) { return "null"; } else { return value.toString(); } } /** * Gets the x location of the top left corner of this element. */ public int getX() { return layoutPart.getBox().getX(); } /** * Gets the y location of the top left corner of this element. */ public int getY() { return layoutPart.getBox().getY(); } public int getHeight() { return layoutPart.getBox().getHeight(); } public int getWidth() { return layoutPart.getBox().getWidth(); } public void setHeight(int height) { layoutPart.getBox().setHeight(height); } public void setWidth(int width) { layoutPart.getBox().setWidth(width); } @Nonnull public List<Element> getChildren() { if (children == null) { return Collections.emptyList(); } return Collections.unmodifiableList(children); } /** * Get the amount of children assigned to this element. * * @return the amaount of children */ public int getChildrenCount() { return elementsRenderOrder != null ? elementsRenderOrder.length : 0; } /** * Get all children, children of children, etc, recursively. * * @return an iterator that will traverse the element's entire tree downward. */ @Nonnull public Iterator<Element> getDescendants() { if (children == null) { // We don't want to give up Java 1.6 compatibility right now. Since Collections.emptyIterator() is Java 1.7 API // for now we've made our own replacement (see end of class). If we finally switch over to 1.7 we can use the // original method. // return Collections.emptyIterator(); return emptyIterator(); } return new ElementTreeTraverser(this); } /** * Adds a child element to the end of the list of this element's children. */ public void addChild(@Nonnull final Element child) { insertChild(child, getChildrenCount()); } /** * Inserts a child element at the specified index in this element's list of children. */ public void insertChild(@Nonnull final Element child, final int index) { final int lastValidIndex = getChildrenCount(); int usedIndex = index; if (index < 0 || index > lastValidIndex) { log.severe("Index is out of range. Index: " + index + " Last valid: " + lastValidIndex); usedIndex = Math.min(lastValidIndex, Math.max(0, index)); } if (children == null) { children = new ArrayList<Element>(); } children.add(usedIndex, child); if (elementsRenderOrderSet == null) { elementsRenderOrderSet = new TreeSet<Element>(RENDER_ORDER_COMPARATOR); } if (!elementsRenderOrderSet.add(child)) { log.severe("Adding the element failed as it seems this element is already part of the children list. This is " + "bad. Rebuilding the children list is required now."); final int childCount = children.size(); boolean foundProblem = false; for (int i = 0; i < childCount; i++) { if (i == usedIndex) { continue; } Element testChild = children.get(i); if (testChild.equals(child)) { foundProblem = true; children.remove(i); break; } } if (!foundProblem) { /* Can't locate the issue, recovery failed -> undoing insert and throwing exception */ children.remove(usedIndex); throw new IllegalStateException("Insert item failed, render list refused the item, " + "but duplicate couldn't be located in the children list. Element is corrupted."); } } else { elementsRenderOrder = elementsRenderOrderSet.toArray(new Element[elementsRenderOrderSet.size()]); } } /** * Set the index of this element in it's parent's list of children. */ public void setIndex(final int index) { if (parent == null) { return; } List<Element> parentChildren = parent.children; if (parentChildren == null) { log.severe("Element tree corrupted. Parent element has not children."); } else { final int curInd = parentChildren.indexOf(this); if (curInd >= 0 && index != curInd) { Element shouldBeThis = parentChildren.remove(curInd); if (shouldBeThis.equals(this)) { parentChildren.add(index, this); } else { log.severe("Setting index failed, detected index did not return correct element. Undoing operation"); parentChildren.add(curInd, shouldBeThis); } } } } public void render(@Nonnull final NiftyRenderEngine r) { if (visible) { if (effectManager.isEmpty()) { r.saveStates(); renderElement(r); renderChildren(r); r.restoreStates(); } else { r.saveStates(); effectManager.renderPre(r, this); renderElement(r); effectManager.renderPost(r, this); renderChildren(r); r.restoreStates(); r.saveStates(); effectManager.renderOverlay(r, this); r.restoreStates(); } } } private void renderElement(@Nonnull final NiftyRenderEngine r) { for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; renderer.render(this, r); } } private void renderChildren(@Nonnull final NiftyRenderEngine r) { if (clipChildren) { r.enableClip(getX(), getY(), getX() + getWidth(), getY() + getHeight()); renderInternalChildElements(r); r.disableClip(); } else { renderInternalChildElements(r); } } private void renderInternalChildElements(@Nonnull final NiftyRenderEngine r) { if (elementsRenderOrder != null) { for (int i = 0; i < elementsRenderOrder.length; i++) { Element p = elementsRenderOrder[i]; p.render(r); } } } public void setLayoutManager(@Nullable final LayoutManager newLayout) { this.layoutManager = newLayout; } public void resetLayout() { TextRenderer textRenderer = getRenderer(TextRenderer.class); if (textRenderer != null) { textRenderer.resetLayout(this); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.resetLayout(); } } } private void preProcessConstraintWidth() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.preProcessConstraintWidth(); } } preProcessConstraintWidthThisLevel(); } private void preProcessConstraintWidthThisLevel() { // This is either the original width value, or a value we set here. SizeValue myWidth = getConstraintWidth(); if (layoutManager != null) { // unset width, or width="sum" or width="max" // try to calculate the width constraint using the children // but only if all child elements have a fixed pixel width. // The difference between an unset width and width="sum" is that the latter does not fail if // there are values that are not pixel, it simply considers them to be "0". // width="sum" also simply sums the width values, it does not care about the layout manager. if (myWidth.hasDefault()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); // if all (!) child elements have a pixel fixed width we can calculate a new width constraint for this element! if (!layoutPartChild.isEmpty() && getChildrenCount() == layoutPartChild.size()) { SizeValue newWidth = layoutManager.calculateConstraintWidth(this.layoutPart, layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.def(newWidthPx)); } } else { setConstraintWidth(SizeValue.def()); } } else if (myWidth.hasSum()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); SizeValue newWidth = layoutPart.getSumWidth(layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.sum(newWidthPx)); } else { setConstraintWidth(SizeValue.sum(0)); } } else if (myWidth.hasMax()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentWidth(); SizeValue newWidth = layoutPart.getMaxWidth(layoutPartChild); if (newWidth.hasValue()) { int newWidthPx = newWidth.getValueAsInt(0); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingLeft().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); newWidthPx += this.layoutPart.getBoxConstraints().getPaddingRight().getValueAsInt(newWidth.getValueAsInt (newWidthPx)); setConstraintWidth(SizeValue.max(newWidthPx)); } else { setConstraintWidth(SizeValue.max(0)); } } } } @Nonnull private List<LayoutPart> getLayoutChildrenWithIndependentWidth() { if (children == null) { return Collections.emptyList(); } final int childrenCount = children.size(); List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); SizeValue childWidth = e.getConstraintWidth(); if (childWidth.isPixel() && childWidth.isIndependentFromParent()) { layoutPartChild.add(e.layoutPart); } } return layoutPartChild; } private void preProcessConstraintHeight() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.preProcessConstraintHeight(); } } preProcessConstraintHeightThisLevel(); } private void preProcessConstraintHeightThisLevel() { // This is either the original height value, or a value we set here. SizeValue myHeight = getConstraintHeight(); if (layoutManager != null) { // unset height, or height="sum" or height="max" // try to calculate the height constraint using the children // but only if all child elements have a fixed pixel height. // The difference between an unset height and height="sum" is that the latter does not fail if // there are values that are not pixel, it simply considers them to be "0". // height="sum" also simply sums the height values, it does not care about the layout manager. if (myHeight.hasDefault()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); // if all (!) child elements have a pixel fixed height we can calculate a new height constraint for this // element! if (!layoutPartChild.isEmpty() && getChildrenCount() == layoutPartChild.size()) { SizeValue newHeight = layoutManager.calculateConstraintHeight(this.layoutPart, layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight .getValueAsInt(newHeightPx)); setConstraintHeight(SizeValue.def(newHeightPx)); } } else { setConstraintHeight(SizeValue.def()); } } else if (myHeight.hasSum()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); SizeValue newHeight = layoutPart.getSumHeight(layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); setConstraintHeight(SizeValue.sum(newHeightPx)); } else { setConstraintHeight(SizeValue.sum(0)); } } else if (myHeight.hasMax()) { List<LayoutPart> layoutPartChild = getLayoutChildrenWithIndependentHeight(); SizeValue newHeight = layoutPart.getMaxHeight(layoutPartChild); if (newHeight.hasValue()) { int newHeightPx = newHeight.getValueAsInt(0); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingTop().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); newHeightPx += this.layoutPart.getBoxConstraints().getPaddingBottom().getValueAsInt(newHeight.getValueAsInt (newHeightPx)); setConstraintHeight(SizeValue.max(newHeightPx)); } else { setConstraintHeight(SizeValue.max(0)); } } } } @Nonnull private List<LayoutPart> getLayoutChildrenWithIndependentHeight() { if (children == null) { return Collections.emptyList(); } final int childrenCount = children.size(); List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); SizeValue childHeight = e.getConstraintHeight(); if (childHeight.isPixel() && childHeight.isIndependentFromParent()) { layoutPartChild.add(e.layoutPart); } } return layoutPartChild; } private void processLayoutInternal() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); TextRenderer textRenderer = w.getRenderer(TextRenderer.class); if (textRenderer != null) { textRenderer.setWidthConstraint(w, w.getConstraintWidth(), getWidth(), nifty.getRenderEngine()); } } } } private void processLayout() { processLayoutInternal(); if (layoutManager != null) { if (children != null) { final int childrenCount = children.size(); // we need a list of LayoutPart and not of Element, so we'll build one on the fly here List<LayoutPart> layoutPartChild = new ArrayList<LayoutPart>(childrenCount); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); layoutPartChild.add(w.layoutPart); } // use out layoutManager to layout our children layoutManager.layoutElements(layoutPart, layoutPartChild); } if (attachedInputControl != null) { NiftyControl niftyControl = attachedInputControl.getNiftyControl(NiftyControl.class); if (niftyControl != null) { if (niftyControl.isBound()) { niftyControl.layoutCallback(); } } } if (children != null) { // repeat this step for all child elements final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.processLayout(); } } } if (clipChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.setParentClipArea(getX(), getY(), getWidth(), getHeight()); } } } public void layoutElements() { prepareLayout(); processLayout(); prepareLayout(); processLayout(); prepareLayout(); processLayout(); publishConstraintsChangedEvent(); } private void publishConstraintsChangedEvent() { if (constraintsChanged) { publishEvent(); constraintsChanged = false; } if (children != null) { for (int i = 0; i < children.size(); i++) { children.get(i).publishConstraintsChangedEvent(); } } } private void prepareLayout() { preProcessConstraintWidth(); preProcessConstraintHeight(); } private void setParentClipArea(final int x, final int y, final int width, final int height) { parentClipArea = true; parentClipX = x; parentClipY = y; parentClipWidth = width; parentClipHeight = height; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.setParentClipArea(parentClipX, parentClipY, parentClipWidth, parentClipHeight); } } } public void resetEffects() { effectManager.reset(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetEffects(); } } } public void resetAllEffects() { effectManager.resetAll(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetAllEffects(); } } } public void resetForHide() { effectManager.resetForHide(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetForHide(); } } } public void resetSingleEffect(@Nonnull final EffectEventId effectEventId) { effectManager.resetSingleEffect(effectEventId); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetSingleEffect(effectEventId); } } } public void resetSingleEffect(@Nonnull final EffectEventId effectEventId, @Nonnull final String customKey) { effectManager.resetSingleEffect(effectEventId, customKey); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetSingleEffect(effectEventId, customKey); } } } public void resetMouseDown() { interaction.resetMouseDown(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.resetMouseDown(); } } } public void setConstraintX(@Nonnull final SizeValue newX) { layoutPart.getBoxConstraints().setX(newX); notifyListeners(); } public void setConstraintY(@Nonnull final SizeValue newY) { layoutPart.getBoxConstraints().setY(newY); notifyListeners(); } public void setConstraintWidth(@Nonnull final SizeValue newWidth) { layoutPart.getBoxConstraints().setWidth(newWidth); notifyListeners(); } public void setConstraintHeight(@Nonnull final SizeValue newHeight) { layoutPart.getBoxConstraints().setHeight(newHeight); notifyListeners(); } @Nonnull public SizeValue getConstraintX() { return layoutPart.getBoxConstraints().getX(); } @Nonnull public SizeValue getConstraintY() { return layoutPart.getBoxConstraints().getY(); } @Nonnull public SizeValue getConstraintWidth() { return layoutPart.getBoxConstraints().getWidth(); } @Nonnull public SizeValue getConstraintHeight() { return layoutPart.getBoxConstraints().getHeight(); } public void setConstraintHorizontalAlign(@Nonnull final HorizontalAlign newHorizontalAlign) { layoutPart.getBoxConstraints().setHorizontalAlign(newHorizontalAlign); } public void setConstraintVerticalAlign(@Nonnull final VerticalAlign newVerticalAlign) { layoutPart.getBoxConstraints().setVerticalAlign(newVerticalAlign); } @Nonnull public HorizontalAlign getConstraintHorizontalAlign() { return layoutPart.getBoxConstraints().getHorizontalAlign(); } @Nonnull public VerticalAlign getConstraintVerticalAlign() { return layoutPart.getBoxConstraints().getVerticalAlign(); } public void registerEffect( @Nonnull final EffectEventId theId, @Nonnull final Effect e) { log.fine("[" + id + "] register: " + theId.toString() + "(" + e.getStateString() + ")"); effectManager.registerEffect(theId, e); } public void startEffect(@Nonnull final EffectEventId effectEventId) { startEffect(effectEventId, null); } public void startEffect(@Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify) { startEffect(effectEventId, effectEndNotify, null); } public void startEffect( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { startEffectDoIt(effectEventId, effectEndNotify, customKey, true); } public void startEffectWithoutChildren(@Nonnull final EffectEventId effectEventId) { startEffectWithoutChildren(effectEventId, null); } public void startEffectWithoutChildren( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify) { startEffectWithoutChildren(effectEventId, effectEndNotify, null); } public void startEffectWithoutChildren( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { startEffectDoIt(effectEventId, effectEndNotify, customKey, false); } private void startEffectDoIt( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey, final boolean withChildren) { if (effectEventId == EffectEventId.onStartScreen) { if (!visible) { return; } done = false; interactionBlocked = true; } if (effectEventId == EffectEventId.onEndScreen) { if (!visible && (effectEndNotify != null)) { // it doesn't make sense to start the onEndScreen effect when the element is hidden // just call the effectEndNotify directly and quit effectEndNotify.perform(); return; } done = true; interactionBlocked = true; } // whenever the effect ends we forward to this event // that checks first, if all child elements are finished // and when yes forwards to the actual effectEndNotify event. // this way we ensure that all child finished the effects // before forwarding this to the real event handler. // little bit tricky though :/ LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotify); // start the effect for our self effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey); // notify all child elements of the start effect if (withChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.startEffectInternal(effectEventId, forwardToSelf, customKey); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(true); } } // just in case there was no effect activated, we'll check here, if we're already done forwardToSelf.perform(); } private void startEffectInternal( @Nonnull final EffectEventId effectEventId, @Nullable final EndNotify effectEndNotify, @Nullable final String customKey) { if (effectEventId == EffectEventId.onStartScreen) { if (!visible) { return; } done = false; interactionBlocked = true; } if (effectEventId == EffectEventId.onEndScreen) { if (!visible) { return; } done = true; interactionBlocked = true; } // whenever the effect ends we forward to this event // that checks first, if all child elements are finished // and when yes forwards to the actual effectEndNotify event. // this way we ensure that all child finished the effects // before forwarding this to the real event handler. // little bit tricky though :/ LocalEndNotify forwardToSelf = new LocalEndNotify(effectEventId, effectEndNotify); // start the effect for our self effectManager.startEffect(effectEventId, this, time, forwardToSelf, customKey); // notify all child elements of the start effect if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.startEffectInternal(effectEventId, forwardToSelf, customKey); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(true); } } } public void stopEffect(@Nonnull final EffectEventId effectEventId) { stopEffectInternal(effectEventId, true); } public void stopEffectWithoutChildren(@Nonnull final EffectEventId effectEventId) { stopEffectInternal(effectEventId, false); } private void stopEffectInternal(@Nonnull final EffectEventId effectEventId, final boolean withChildren) { if (EffectEventId.onStartScreen == effectEventId || EffectEventId.onEndScreen == effectEventId) { interactionBlocked = false; if (!visible) { return; } } effectManager.stopEffect(effectEventId); // notify all child elements of the start effect if (withChildren && children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.stopEffect(effectEventId); } } if (effectEventId == EffectEventId.onFocus) { if (attachedInputControl != null) { attachedInputControl.onFocus(false); } } } /** * Checks if a certain effect is still active in this element or any of its children. * * @return true if the effect has ended and false otherwise */ public boolean isEffectActive(@Nonnull final EffectEventId effectEventId) { return effectStateCache.get(effectEventId); } public void enable() { if (enabled) { return; } enableInternal(); } private void enableInternal() { enabledCount++; if (enabledCount == 0) { enabled = true; enableEffect(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).enableInternal(); } } } else { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).enableInternal(); } } } } void enableEffect() { stopEffectWithoutChildren(EffectEventId.onDisabled); startEffectWithoutChildren(EffectEventId.onEnabled); if (id != null) { nifty.publishEvent(id, new ElementEnableEvent(this)); } } public void disable() { if (!enabled) { return; } disableInternal(); } private void disableInternal() { enabledCount if (enabledCount == -1) { enabled = false; disableFocus(); disableEffect(); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).disableInternal(); } } } else { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).disableInternal(); } } } } public void disableFocus() { if (focusHandler.getKeyboardFocusElement() == this) { Element prevElement = focusHandler.getNext(this); prevElement.setFocus(); } focusHandler.lostKeyboardFocus(this); focusHandler.lostMouseFocus(this); // make sure we don't have child elements that still have the focus if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).disableFocus(); } } } void disableEffect() { stopEffectWithoutChildren(EffectEventId.onHover); stopEffectWithoutChildren(EffectEventId.onStartHover); stopEffectWithoutChildren(EffectEventId.onEndHover); stopEffectWithoutChildren(EffectEventId.onEnabled); startEffectWithoutChildren(EffectEventId.onDisabled); if (id != null) { nifty.publishEvent(id, new ElementDisableEvent(this)); } } public boolean isEnabled() { return enabled; } public void show() { show(null); } public void show(@Nullable final EndNotify perform) { // don't show if show is still in progress if (isEffectActive(EffectEventId.onShow)) { return; } // stop any onHide effects when a new onShow effect is about to be started if (isEffectActive(EffectEventId.onHide)) { resetSingleEffect(EffectEventId.onHide); } // show internalShow(); startEffectWithoutChildren(EffectEventId.onShow, perform); } private void internalShow() { visible = true; effectManager.restoreForShow(); if (id != null) { nifty.publishEvent(id, new ElementShowEvent(this)); } } public void setVisible(final boolean visibleParam) { if (visibleParam) { show(); } else { hide(); } } public void hide() { hide(null); } public void hide(@Nullable final EndNotify perform) { // don't hide if not visible if (!isVisible()) { return; } // don't hide if hide is still in progress if (isEffectActive(EffectEventId.onHide)) { return; } // stop any onShow effects when a new onHide effect is about to be started if (isEffectActive(EffectEventId.onShow)) { resetSingleEffect(EffectEventId.onShow); } // start effect and shizzle startEffect(EffectEventId.onHide, new EndNotify() { @Override public void perform() { resetForHide(); internalHide(); if (perform != null) { perform.perform(); } } }); } public void showWithoutEffects() { internalShow(); } public void hideWithoutEffect() { // don't hide if not visible if (!isVisible()) { return; } resetEffects(); internalHide(); } private void internalHide() { visible = false; disableFocus(); if (id != null) { nifty.publishEvent(id, new ElementHideEvent(this)); } } /** * Returns true if this element is visible. Please note that this is with regards to that element only. It's possible * that this element is invisible (because of any of its parent elements is invisible) and still this method will * return true; * * @return if this element is visible returns true. when the element is invisible returns false. */ public boolean isVisible() { return visible; } /** * Returns true if this element is visible and all of its parent hierarchy is visible too. * @return if this element is really visible and false if it is invisible. */ public boolean isVisibleWithParent() { if (parent == null) { return visible; } return visible && parent.isVisibleWithParent(); } public void setHotSpotFalloff(@Nullable final Falloff newFalloff) { effectManager.setFalloff(newFalloff); } @Nullable public Falloff getFalloff() { return effectManager.getFalloff(); } public boolean canHandleMouseEvents() { if (isEffectActive(EffectEventId.onStartScreen)) { return false; } if (isEffectActive(EffectEventId.onEndScreen)) { return false; } if (!visible) { return false; } if (done) { return false; } if (!visibleToMouseEvents) { return false; } if (!focusHandler.canProcessMouseEvents(this)) { return false; } if (interactionBlocked) { return false; } if (!enabled) { return false; } if (isIgnoreMouseEvents()) { return false; } return true; } /** * This is a special version of canHandleMouseEvents() that will return true if this element is able to process * mouse events in general. This method will return true even when the element is temporarily not able to handle * events because onStartScreen or onEndScreen effects are active. * * @return true can handle mouse events, false can't handle them */ boolean canTheoreticallyHandleMouseEvents() { if (!visible) { return false; } if (done) { return false; } if (!visibleToMouseEvents) { return false; } if (!focusHandler.canProcessMouseEvents(this)) { return false; } if (!enabled) { return false; } if (isIgnoreMouseEvents()) { return false; } return true; } /** * This should check if the mouse event is inside the current element and if it is * forward the event to it's child. The purpose of this is to build a list of all * elements from front to back that are available for a certain mouse position. */ public void buildMouseOverElements( @Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime, @Nonnull final MouseOverHandler mouseOverHandler) { boolean isInside = isInside(mouseEvent); if (canHandleMouseEvents()) { if (isInside) { mouseOverHandler.addMouseOverElement(this); } else { mouseOverHandler.addMouseElement(this); } } else if (canTheoreticallyHandleMouseEvents()) { if (isInside) { mouseOverHandler.canTheoreticallyHandleMouse(this); } } if (visible) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); w.buildMouseOverElements(mouseEvent, eventTime, mouseOverHandler); } } } } public void mouseEventHoverPreprocess(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { effectManager.handleHoverDeactivate(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); } /** * Process mouse event for this element * @param mouseEvent * @param eventTime is the current time in milliseconds * @return True if the event has been processed */ public boolean mouseEvent(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { mouseEventHover(mouseEvent); return interaction.process(mouseEvent, eventTime, isInside(mouseEvent), canHandleInteraction(), focusHandler.hasExclusiveMouseFocus(this)); } private void mouseEventHover(@Nonnull final NiftyMouseInputEvent mouseEvent) { effectManager.handleHover(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); effectManager.handleHoverStartAndEnd(this, mouseEvent.getMouseX(), mouseEvent.getMouseY()); } /** * Handles the MouseOverEvent. Must not call child elements. This is handled by the caller. * * @return true the mouse event has been consumed and false when the mouse event can be processed further down */ public boolean mouseOverEvent(@Nonnull final NiftyMouseInputEvent mouseEvent, final long eventTime) { boolean isMouseEventConsumed = false; if (interaction.onMouseOver(this, mouseEvent)) { isMouseEventConsumed = true; } if ((mouseEvent.getMouseWheel() != 0) && interaction.onMouseWheel(this, mouseEvent)) { isMouseEventConsumed = true; } return isMouseEventConsumed; } /** * Checks to see if the given mouse position is inside of this element. */ private boolean isInside(@Nonnull final NiftyMouseInputEvent inputEvent) { return isMouseInsideElement(inputEvent.getMouseX(), inputEvent.getMouseY()); } public boolean isMouseInsideElement(final int mouseX, final int mouseY) { if (parentClipArea) { // must be inside the parent to continue if (isInsideParentClipArea(mouseX, mouseY)) { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } else { return false; } } else { return mouseX >= getX() && mouseX <= (getX() + getWidth()) && mouseY > (getY()) && mouseY < (getY() + getHeight()); } } private boolean isInsideParentClipArea(final int mouseX, final int mouseY) { return mouseX >= parentClipX && mouseX <= (parentClipX + parentClipWidth) && mouseY > (parentClipY) && mouseY < (parentClipY + parentClipHeight); } /** * @deprecated Use {@link #onClickAndReleasePrimaryMouseButton()} instead. * * Simulates a click-release of the primary mouse button on the element. * * @see #onClickAndReleasePrimaryMouseButton() * @see #onClickAndReleaseSecondaryMouseButton() * @see #onClickAndReleaseSecondaryMouseButton() */ @Deprecated public void onClick() { onClickAndReleasePrimaryMouseButton(); } /** * Simulates a click-release of the primary mouse button on the element. * * This method is called automatically in many cases as a response to receiving a * {@link de.lessvoid.nifty.input.NiftyStandardInputEvent#Activate} event. * * An element will not respond to a click-release of the primary mouse button in the following situations: * * 1) When the element is disabled. * * 2) When a {@link de.lessvoid.nifty.screen.Screen} is starting or ending, or more specifically, when: * {@link de.lessvoid.nifty.effects.EffectEventId#onStartScreen} or * {@link de.lessvoid.nifty.effects.EffectEventId#onEndScreen} effects are active on the current * {@link de.lessvoid.nifty.screen.Screen}. * * 3) If there is no current {@link de.lessvoid.nifty.screen.Screen}, i.e., the current * {@link de.lessvoid.nifty.screen.Screen} is null. * * @see de.lessvoid.nifty.elements.ElementInteraction#clickAndReleasePrimaryMouseButton(de.lessvoid.nifty.Nifty) * @see #onClickAndReleaseSecondaryMouseButton() * @see #onClickAndReleaseTertiaryMouseButton() * @see de.lessvoid.nifty.input.NiftyStandardInputEvent#Activate * @see #isEnabled() * @see #enable() * @see #disable() * @see Screen#isEffectActive(de.lessvoid.nifty.effects.EffectEventId) * @see de.lessvoid.nifty.effects.EffectEventId#onStartScreen * @see de.lessvoid.nifty.effects.EffectEventId#onEndScreen * @see de.lessvoid.nifty.Nifty#getCurrentScreen() */ public void onClickAndReleasePrimaryMouseButton() { if (!canHandleInteraction()) { return; } interaction.clickAndReleasePrimaryMouseButton(nifty); } /** * Simulates a click-release of the secondary mouse button on the element. * * An element will not respond to a click-release of the secondary mouse button in the following situations: * * 1) When the element is disabled. * * 2) When a {@link de.lessvoid.nifty.screen.Screen} is starting or ending, or more specifically, when: * {@link de.lessvoid.nifty.effects.EffectEventId#onStartScreen} or * {@link de.lessvoid.nifty.effects.EffectEventId#onEndScreen} effects are active on the current * {@link de.lessvoid.nifty.screen.Screen}. * * 3) If there is no current {@link de.lessvoid.nifty.screen.Screen}, i.e., the current * {@link de.lessvoid.nifty.screen.Screen} is null. * * @see de.lessvoid.nifty.elements.ElementInteraction#clickAndReleaseSecondaryMouseButton(de.lessvoid.nifty.Nifty) * @see #onClickAndReleasePrimaryMouseButton() * @see #onClickAndReleaseTertiaryMouseButton() * @see #isEnabled() * @see #enable() * @see #disable() * @see Screen#isEffectActive(de.lessvoid.nifty.effects.EffectEventId) * @see de.lessvoid.nifty.effects.EffectEventId#onStartScreen * @see de.lessvoid.nifty.effects.EffectEventId#onEndScreen * @see de.lessvoid.nifty.Nifty#getCurrentScreen() */ public void onClickAndReleaseSecondaryMouseButton() { if (!canHandleInteraction()) { return; } interaction.clickAndReleaseSecondaryMouseButton(nifty); } /** * Simulates a click-release of the tertiary mouse button on the element. * * An element will not respond to a click-release of the tertiary mouse button in the following situations: * * 1) When the element is disabled. * * 2) When a {@link de.lessvoid.nifty.screen.Screen} is starting or ending, or more specifically, when: * {@link de.lessvoid.nifty.effects.EffectEventId#onStartScreen} or * {@link de.lessvoid.nifty.effects.EffectEventId#onEndScreen} effects are active on the current * {@link de.lessvoid.nifty.screen.Screen}. * * 3) If there is no current {@link de.lessvoid.nifty.screen.Screen}, i.e., the current * {@link de.lessvoid.nifty.screen.Screen} is null. * * @see de.lessvoid.nifty.elements.ElementInteraction#clickAndReleaseTertiaryMouseButton(de.lessvoid.nifty.Nifty) * @see #onClickAndReleasePrimaryMouseButton() * @see #onClickAndReleaseSecondaryMouseButton() * @see #isEnabled() * @see #enable() * @see #disable() * @see Screen#isEffectActive(de.lessvoid.nifty.effects.EffectEventId) * @see de.lessvoid.nifty.effects.EffectEventId#onStartScreen * @see de.lessvoid.nifty.effects.EffectEventId#onEndScreen * @see de.lessvoid.nifty.Nifty#getCurrentScreen() */ public void onClickAndReleaseTertiaryMouseButton() { if (!canHandleInteraction()) { return; } interaction.clickAndReleaseTertiaryMouseButton(nifty); } private boolean canHandleInteraction() { if (screen == null || !enabled) { return false; } return !screen.isEffectActive(EffectEventId.onStartScreen) && !screen.isEffectActive(EffectEventId.onEndScreen); } /** * @return the element or null if an element with the specified id cannot be found */ @Nullable public Element findElementById(@Nullable final String findId) { if (findId == null) { return null; } if (id != null && id.equals(findId)) { return this; } if (childIdMatch(findId, id)) { return this; } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); Element found = e.findElementById(findId); if (found != null) { return found; } } } return null; } private boolean childIdMatch(@Nonnull final String name, @Nullable final String id) { if (name.startsWith(" if (id != null && id.endsWith(name)) { return true; } } return false; } public void setOnClickAlternateKey(final String newAlternateKey) { interaction.setAlternateKey(newAlternateKey); } public void setAlternateKey(@Nullable final String alternateKey) { effectManager.setAlternateKey(alternateKey); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.setAlternateKey(alternateKey); } } } @Nonnull public EffectManager getEffectManager() { return effectManager; } public void setEffectManager(@Nonnull final EffectManager effectManagerParam) { effectManager = effectManagerParam; } private void bindToScreen(@Nonnull final Screen newScreen) { screen = newScreen; if (id != null) { screen.registerElementId(id); } } private void bindToFocusHandler(final boolean isPopup) { if (!focusable) { return; } if (hasAncestorPopup() && !isPopup) { return; } if (screen == null) { log.severe("Trying to bind element [" + String.valueOf(getId()) + "] to focus handler while screen is not " + "bound."); } else { focusHandler.addElement(this, screen.findElementById(focusableInsertBeforeElementId)); } } private boolean hasAncestorPopup() { return findAncestorPopupElement() != null; } @Nullable private Element findAncestorPopupElement() { if (elementType instanceof PopupType) { return this; } if (parent == null) { return null; } return parent.findAncestorPopupElement(); } public void onStartScreen() { onStartScreenSubscribeControllerAnnotations(); onStartScreenInternal(); } private void onStartScreenSubscribeControllerAnnotations() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.onStartScreenSubscribeControllerAnnotations(); } } if (attachedInputControl != null) { nifty.subscribeAnnotations(attachedInputControl.getController()); } } private void onStartScreenInternal() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element e = children.get(i); e.onStartScreenInternal(); } } if (screen == null) { log.severe("Internal start of screen called, but no screen is bound to the element [" + String.valueOf(getId()) + "]"); } else { if (attachedInputControl != null) { attachedInputControl.onStartScreen(nifty, screen); } } } /** * Gets this element's renderer matching the specified class. * * @param <T> the {@link de.lessvoid.nifty.elements.render.ElementRenderer} type to check for * @param requestedRendererClass the {@link de.lessvoid.nifty.elements.render.ElementRenderer} class to check for * @return the {@link de.lessvoid.nifty.elements.render.ElementRenderer} that matches the specified class, or null if * there is no matching renderer */ @Nullable public <T extends ElementRenderer> T getRenderer(@Nonnull final Class<T> requestedRendererClass) { for (int i = 0; i < elementRenderer.length; i++) { ElementRenderer renderer = elementRenderer[i]; if (requestedRendererClass.isInstance(renderer)) { return requestedRendererClass.cast(renderer); } } return null; } public void setVisibleToMouseEvents(final boolean newVisibleToMouseEvents) { this.visibleToMouseEvents = newVisibleToMouseEvents; } public boolean keyEvent(@Nonnull final KeyboardInputEvent inputEvent) { if (attachedInputControl != null && id != null) { return attachedInputControl.keyEvent(nifty, inputEvent, id); } return false; } public void setClipChildren(final boolean clipChildrenParam) { this.clipChildren = clipChildrenParam; } public boolean isClipChildren() { return this.clipChildren; } public void setRenderOrder(final int renderOrder) { this.renderOrder = renderOrder; if (parent != null) { parent.renderOrderChanged(this); } } private void renderOrderChanged(@Nonnull final Element element) { if (elementsRenderOrderSet == null) { log.warning("Can't report a changed order, parent doesn't seem to have children?! O.o"); return; } Iterator<Element> childItr = elementsRenderOrderSet.iterator(); boolean foundOldEntry = false; while (childItr.hasNext()) { Element checkElement = childItr.next(); if (checkElement.equals(element)) { childItr.remove(); foundOldEntry = true; break; } } if (foundOldEntry) { elementsRenderOrderSet.add(element); if (elementsRenderOrder == null || elementsRenderOrder.length != elementsRenderOrderSet.size()) { elementsRenderOrder = new Element[elementsRenderOrderSet.size()]; } elementsRenderOrder = elementsRenderOrderSet.toArray(elementsRenderOrder); } else { log.warning("Failed to locate the element with changed id in the render set."); } } public int getRenderOrder() { return renderOrder; } /** * Attempts to set the focus to this element. */ public void setFocus() { if (nifty.getCurrentScreen() != null) { if (isFocusable()) { focusHandler.setKeyFocus(this); } } } public void attachInputControl(final NiftyInputControl newInputControl) { attachedInputControl = newInputControl; } private boolean hasParentActiveOnStartOrOnEndScreenEffect() { if (parent != null) { return parent.effectManager.isActive(EffectEventId.onStartScreen) || parent.effectManager.isActive(EffectEventId.onEndScreen) || parent.hasParentActiveOnStartOrOnEndScreenEffect(); } return false; } private void resetInteractionBlocked() { interactionBlocked = false; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.resetInteractionBlocked(); } } } /** * @author void */ public class LocalEndNotify implements EndNotify { @Nonnull private final EffectEventId effectEventId; @Nullable private final EndNotify effectEndNotify; public LocalEndNotify( @Nonnull final EffectEventId effectEventIdParam, @Nullable final EndNotify effectEndNotifyParam) { effectEventId = effectEventIdParam; effectEndNotify = effectEndNotifyParam; } @Override public void perform() { if (effectEventId.equals(EffectEventId.onStartScreen) || effectEventId.equals(EffectEventId.onEndScreen)) { if (interactionBlocked && !hasParentActiveOnStartOrOnEndScreenEffect() && !isEffectActive(effectEventId)) { resetInteractionBlocked(); } } // notify parent if: // a) the effect is done for our self // b) the effect is done for all of our children if (!isEffectActive(effectEventId)) { // all fine. we can notify the actual event handler if (effectEndNotify != null) { effectEndNotify.perform(); } } } } public void setId(@Nullable final String id) { @Nullable String oldId = this.id; this.id = id; if (parent == null) { return; } if (oldId == null && id == null) { return; } if ((oldId != null && oldId.equals(id)) || (id != null && id.equals(oldId))) { return; } /* So the ID changed and we got a parent. This means the render order set is likely to be corrupted now. We need to update it to ensure that everything is still working properly. */ parent.renderOrderChanged(this); } @Nonnull public ElementType getElementType() { return elementType; } @Nonnull public ElementRenderer[] getElementRenderer() { return elementRenderer; } public void setFocusable(final boolean isFocusable) { this.focusable = isFocusable; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.setFocusable(isFocusable); } } } @Nullable public NiftyInputControl getAttachedInputControl() { return attachedInputControl; } public void bindControls(@Nonnull final Screen target) { if (screen == target) { return; } bindToScreen(target); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.bindControls(target); } } if (attachedInputControl != null) { attachedInputControl.bindControl(nifty, target, this, elementType.getAttributes()); } } public void initControls(final boolean isPopup) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.initControls(isPopup); } } if (attachedInputControl != null) { attachedInputControl.initControl(elementType.getAttributes()); } bindToFocusHandler(isPopup); } /** * Removes this element and all of its children from the focusHandler. */ public void removeFromFocusHandler() { focusHandler.remove(this); if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.removeFromFocusHandler(); } } } @Nonnull public FocusHandler getFocusHandler() { return focusHandler; } public void setStyle(@Nonnull final String newStyle) { final String oldStyle = getStyle(); if (oldStyle != null) { removeStyle(oldStyle); } elementType.getAttributes().set("style", newStyle); elementType.applyStyles(nifty.getDefaultStyleResolver()); if (screen == null) { log.warning("Can't properly apply style as long as the element is not bound to a screen."); } else { elementType.applyAttributes(screen, this, elementType.getAttributes(), nifty.getRenderEngine()); elementType.applyEffects(nifty, screen, this); elementType.applyInteract(nifty, screen, this); } log.fine("after setStyle [" + newStyle + "]\n" + elementType.output(0)); publishEvent(); } @Nullable public String getStyle() { return elementType.getAttributes().get("style"); } void removeStyle(@Nonnull final String style) { log.fine("before removeStyle [" + style + "]\n" + elementType.output(0)); elementType.removeWithTag(style); effectManager.removeAllEffects(); log.fine("after removeStyle [" + style + "]\n" + elementType.output(0)); publishEvent(); } /** * Adds an additional input handler to this element and its children. * * @param handler additional handler */ public void addInputHandler(@Nonnull final KeyInputHandler handler) { if (attachedInputControl != null) { attachedInputControl.addInputHandler(handler); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.addInputHandler(handler); } } } /** * Adds an additional input handler to this element and its children. * * @param handler additional handler */ public void addPreInputHandler(@Nonnull final KeyInputHandler handler) { if (attachedInputControl != null) { attachedInputControl.addPreInputHandler(handler); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); child.addPreInputHandler(handler); } } } @Nullable public <T extends Controller> T findControl( @Nonnull final String elementName, @Nonnull final Class<T> requestedControlClass) { Element element = findElementById(elementName); if (element == null) { return null; } return element.getControl(requestedControlClass); } @Nullable public <T extends NiftyControl> T findNiftyControl( @Nonnull final String elementName, @Nonnull final Class<T> requestedControlClass) { Element element = findElementById(elementName); if (element == null) { return null; } return element.getNiftyControl(requestedControlClass); } @Nullable public <T extends Controller> T getControl(@Nonnull final Class<T> requestedControlClass) { if (attachedInputControl != null) { T t = attachedInputControl.getControl(requestedControlClass); if (t != null) { return t; } } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); T t = child.getControl(requestedControlClass); if (t != null) { return t; } } } return null; } @Nullable public <T extends NiftyControl> T getNiftyControl(@Nonnull final Class<T> requestedControlClass) { if (attachedInputControl != null) { T t = attachedInputControl.getNiftyControl(requestedControlClass); if (t != null) { return t; } } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element child = children.get(i); T t = child.getNiftyControl(requestedControlClass); if (t != null) { return t; } } } log.warning("missing element/control with id [" + id + "] for requested control class [" + requestedControlClass.getName() + "]"); return null; } public boolean isFocusable() { return focusable && enabled && visible && hasVisibleParent() && !isIgnoreKeyboardEvents(); } private boolean hasVisibleParent() { if (parent != null) { return parent.visible && parent.hasVisibleParent(); } return true; } public void setOnMouseOverMethod(@Nullable final NiftyMethodInvoker onMouseOverMethod) { interaction.setOnMouseOver(onMouseOverMethod); } @Nonnull public LayoutPart getLayoutPart() { return layoutPart; } public boolean isVisibleToMouseEvents() { return visibleToMouseEvents; } @Nonnull public SizeValue getPaddingLeft() { return layoutPart.getBoxConstraints().getPaddingLeft(); } @Nonnull public SizeValue getPaddingRight() { return layoutPart.getBoxConstraints().getPaddingRight(); } @Nonnull public SizeValue getPaddingTop() { return layoutPart.getBoxConstraints().getPaddingTop(); } @Nonnull public SizeValue getPaddingBottom() { return layoutPart.getBoxConstraints().getPaddingBottom(); } @Nonnull public SizeValue getMarginLeft() { return layoutPart.getBoxConstraints().getMarginLeft(); } @Nonnull public SizeValue getMarginRight() { return layoutPart.getBoxConstraints().getMarginRight(); } @Nonnull public SizeValue getMarginTop() { return layoutPart.getBoxConstraints().getMarginTop(); } @Nonnull public SizeValue getMarginBottom() { return layoutPart.getBoxConstraints().getMarginBottom(); } public void setPaddingLeft(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingLeft(paddingValue); notifyListeners(); } public void setPaddingRight(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingRight(paddingValue); notifyListeners(); } public void setPaddingTop(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingTop(paddingValue); notifyListeners(); } public void setPaddingBottom(@Nonnull final SizeValue paddingValue) { layoutPart.getBoxConstraints().setPaddingBottom(paddingValue); notifyListeners(); } public void setMarginLeft(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginLeft(value); notifyListeners(); } public void setMarginRight(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginRight(value); notifyListeners(); } public void setMarginTop(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginTop(value); notifyListeners(); } public void setMarginBottom(@Nonnull final SizeValue value) { layoutPart.getBoxConstraints().setMarginBottom(value); notifyListeners(); } @Override @Nonnull public String toString() { return id + " (" + super.toString() + ")"; } public boolean isStarted() { return isEffectActive(EffectEventId.onStartScreen); } public void markForRemoval() { markForRemoval(null); } public void markForRemoval(@Nullable final EndNotify endNotify) { if (screen == null) { log.warning("Marking the element [" + String.valueOf(getId()) + "] for removal is not possible when there is " + "not screen bound."); } else { nifty.removeElement(screen, this, endNotify); } } public void markForMove(@Nonnull final Element destination) { markForMove(destination, null); } public void markForMove(@Nonnull final Element destination, @Nullable final EndNotify endNotify) { if (screen == null) { log.warning("Marking the element [" + String.valueOf(getId()) + "] for moving is not possible when there is not" + " screen bound."); } else { nifty.moveElement(screen, this, destination, endNotify); } } public void reactivate() { done = false; if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).reactivate(); } } } private void notifyListeners() { constraintsChanged = true; } private void publishEvent() { if (id != null) { nifty.publishEvent(id, this); } } @Nonnull public Nifty getNifty() { return nifty; } @Nonnull public <T extends EffectImpl> List<Effect> getEffects( @Nonnull final EffectEventId effectEventId, @Nonnull final Class<T> requestedClass) { return effectManager.getEffects(effectEventId, requestedClass); } public void onEndScreen(@Nonnull final Screen screen) { if (id != null) { screen.unregisterElementId(id); nifty.unsubscribeElement(screen, id); } if (attachedInputControl != null) { attachedInputControl.onEndScreen(nifty, screen, id); } if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).onEndScreen(screen); } } } @Nonnull public ElementInteraction getElementInteraction() { return interaction; } public void setIgnoreMouseEvents(final boolean newValue) { ignoreMouseEvents = newValue; if (newValue) { focusHandler.lostMouseFocus(this); } } public boolean isIgnoreMouseEvents() { return ignoreMouseEvents; } public void setIgnoreKeyboardEvents(final boolean newValue) { ignoreKeyboardEvents = newValue; if (newValue) { focusHandler.lostKeyboardFocus(this); } } public boolean isIgnoreKeyboardEvents() { return ignoreKeyboardEvents; } @Override public void effectStateChanged(@Nonnull final EffectEventId eventId, final boolean active) { // Get the oldState first. boolean oldState = effectStateCache.get(eventId); // The given EffectEventId changed its state. This means we now must update // the ElementEffectStartedCache for this element. We do this by recalculating // our state taking the state of all child elements into account. boolean newState = isEffectActiveRecalc(eventId); // When our state has been changed due to the update we will update the cache // and tell our parent element to update as well. if (newState != oldState) { effectStateCache.set(eventId, newState); if (parent != null) { parent.effectStateChanged(eventId, newState); } } } private boolean isEffectActiveRecalc(@Nonnull final EffectEventId eventId) { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { Element w = children.get(i); if (w.isEffectActiveRecalc(eventId)) { return true; } } } return effectManager.isActive(eventId); } // package private to prevent public access void internalRemoveElement(@Nonnull final Element element) { if (elementsRenderOrderSet != null && children != null) { // so now that's odd: we need to remove the element first from the // elementsRenderOrder and THEN from the elements list. this is because // the elementsRenderOrder comparator uses the index of the element in // the elements list >_< // the main issue here is of course the splitted data structure. something // we need to address in 1.4 or 2.0. elementsRenderOrderSet.remove(element); // now that the element has been removed from the elementsRenderOrder set // we can remove it from the elements list as well. children.remove(element); if (children.isEmpty()) { elementsRenderOrderSet = null; children = null; } else if (children.size() != elementsRenderOrderSet.size()) { log.severe("Problem at removing a element. RenderOrderSet and children list don't have the same size " + "anymore. Rebuilding the render order set."); elementsRenderOrderSet.clear(); elementsRenderOrderSet.addAll(children); } } if (elementsRenderOrderSet != null) { elementsRenderOrder = elementsRenderOrderSet.toArray(new Element[elementsRenderOrderSet.size()]); } else { elementsRenderOrder = null; } } // package private to prevent public access void internalRemoveElementWithChildren() { if (children != null) { final int childrenCount = children.size(); for (int i = 0; i < childrenCount; i++) { children.get(i).internalRemoveElementWithChildren(); } } elementsRenderOrderSet = null; children = null; elementsRenderOrder = null; } /** * Sets custom user data for this element. * * @param key the key for the object to set */ public void setUserData(@Nonnull final String key, @Nullable final Object data) { if (data == null) { if (userData != null) { userData.remove(key); if (userData.isEmpty()) { userData = null; } } } else { if (userData == null) { userData = new HashMap<String, Object>(); } userData.put(key, data); } } /** * Gets custom user data set with {@link #setUserData(String, Object)} by key */ @Nullable @SuppressWarnings("unchecked") public <T> T getUserData(@Nonnull final String key) { if (userData == null) { return null; } return (T) userData.get(key); } /** * Gets all custom user data keys set with {@link #setUserData(String, Object)} */ @Nonnull public Set<String> getUserDataKeys() { if (userData != null) { return userData.keySet(); } return Collections.emptySet(); } /** * This uses the renderOrder attribute of the elements to compare them. If the renderOrder * attribute is not set (is 0) then the index of the element in the elements list is used * as the renderOrder value. This is done to keep the original sort order of the elements for * rendering. The value is not cached and is directly recalculated using the element index in * the list. The child count for an element is usually low (< 10) and the comparator is only * executed when the child elements change. So this lookup shouldn't hurt performance too much. * <p/> * If you change the default value of renderOrder then your value is being used. So if you set it * to some high value (> 1000 to be save) this element is rendered after all the other elements. * If you set it to some very low value (< -1000 to be save) then this element is rendered before * all the others. */ private static final class RenderOrderComparator implements Comparator<Element> { @Override public int compare(@Nonnull final Element o1, @Nonnull final Element o2) { if (o1 == o2) { return 0; } int o1RenderOrder = getRenderOrder(o1); int o2RenderOrder = getRenderOrder(o2); if (o1RenderOrder < o2RenderOrder) { return -1; } else if (o1RenderOrder > o2RenderOrder) { return 1; } // this means the renderOrder values are equal. since this is a set // we can't return 0 because this would mean (for the set) that the // elements are equal and one of the values will be removed. so here // we simply compare the String representation of the elements so that // we keep a fixed sort order. String o1Id = o1.id; String o2Id = o2.id; if (o1Id == null && o2Id != null) { return -1; } else if (o1Id != null && o2Id == null) { return 1; } else if (o1Id != null) { int idCompareResult = o1Id.compareTo(o2Id); if (idCompareResult != 0) { return idCompareResult; } } // ids equal or both null use super.toString() // hashCode() should return a value thats different for both elements since // adding the same element twice to the same parent element is not supported. return Integer.valueOf(o1.hashCode()).compareTo(Integer.valueOf(o2.hashCode())); } private int getRenderOrder(@Nonnull final Element element) { if (element.renderOrder != 0) { return element.renderOrder; } return element.getParent().getChildren().indexOf(element); } } // We don't want to give up Java 1.6 compatibility right now. @SuppressWarnings("unchecked") @Nonnull private static <T> Iterator<T> emptyIterator() { return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR; } private static class EmptyIterator<E> implements Iterator<E> { static final EmptyIterator<Object> EMPTY_ITERATOR = new EmptyIterator<Object>(); @Override public boolean hasNext() { return false; } @Override @Nonnull public E next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } } }
package net.miz_hi.smileessence.model.status.user; import net.miz_hi.smileessence.Client; import net.miz_hi.smileessence.model.status.IStatusModel; import net.miz_hi.smileessence.preference.EnumPreferenceKey; import net.miz_hi.smileessence.status.EnumNameStyle; import net.miz_hi.smileessence.task.impl.GetUserTask; import net.miz_hi.smileessence.util.StringUtils; import twitter4j.User; import java.util.Date; import java.util.concurrent.Future; public class UserModel implements IStatusModel { public long userId; public String screenName; public String name; public String homePageUrl; public String location; public String description; public String iconUrl; public String biggerIconUrl; public String headerImageUrl; public int statusCount; public int friendCount; public int followerCount; public int favoriteCount; public Date createdAt; public boolean isProtected; private UserModel() { } public UserModel(User user) { userId = user.getId(); updateData(user); } public UserModel updateData(User user) { screenName = user.getScreenName(); name = user.getName(); homePageUrl = user.getURLEntity().getExpandedURL(); location = user.getLocation(); description = StringUtils.replaceUrlEntity(user.getDescription(), user.getDescriptionURLEntities()); iconUrl = user.getProfileImageURL(); biggerIconUrl = user.getBiggerProfileImageURL(); headerImageUrl = user.getProfileBannerURL(); statusCount = user.getStatusesCount(); friendCount = user.getFriendsCount(); followerCount = user.getFollowersCount(); favoriteCount = user.getFavouritesCount(); createdAt = user.getCreatedAt(); isProtected = user.isProtected(); // ImageCache.preCache(iconUrl); return this; } public User getRawUser() { Future<User> resp = new GetUserTask(userId).callAsync(); try { return resp.get(); } catch (Exception e) { e.printStackTrace(); return null; } } public boolean isMe() { return userId == Client.getMainAccount().getUserId(); } public static UserModel getNullUserModel() { UserModel user = new UserModel(); user.screenName = ""; user.name = ""; user.homePageUrl = ""; user.location = ""; user.description = ""; user.iconUrl = ""; user.headerImageUrl = ""; user.statusCount = 0; user.friendCount = 0; user.followerCount = 0; user.favoriteCount = 0; user.createdAt = new Date(); user.isProtected = false; return user; } @Override public UserModel getUser() { return this; } @Override public String getTextTop() { StringBuilder builder = new StringBuilder(); String style = Client.getPreferenceValue(EnumPreferenceKey.NAME_STYLE); if (style.equals(EnumNameStyle.S_N.get()) || style.equals(EnumNameStyle.S.get())) { builder.append(screenName); } else if (style.equals(EnumNameStyle.N_S.get()) || style.equals(EnumNameStyle.N.get())) { builder.append(name); } if (style.equals(EnumNameStyle.S_N.get())) { builder.append(" / "); builder.append(name); } else if (style.equals(EnumNameStyle.N_S.get())) { builder.append(" / "); builder.append(screenName); } return builder.toString(); } @Override public String getTextContent() { if (description.length() > 100) { return description.substring(0, 100) + "..."; } else { return description; } } @Override public String getTextBottom() { return location; } }
package com.samourai.wallet.network.dojo; import android.content.Context; import android.util.Log; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.util.WebUtil; import org.json.JSONException; import org.json.JSONObject; import io.reactivex.Observable; public class DojoUtil { private static String dojoParams = null; private static DojoUtil instance = null; private static final String TAG = "DojoUtil"; private static Context context = null; private DojoUtil() { ; } public static DojoUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new DojoUtil(); } return instance; } public void clear() { dojoParams = null; } public boolean isValidPairingPayload(String data) { try { JSONObject obj = new JSONObject(data); if(obj.has("pairing")) { JSONObject pObj = obj.getJSONObject("pairing"); if(pObj.has("type") && pObj.has("version") && pObj.has("apikey") && pObj.has("url")) { return true; } else { return false; } } else { return false; } } catch(JSONException je) { return false; } } public String getDojoParams() { return dojoParams; } public synchronized Observable<Boolean> setDojoParams(String dojoParams) { return Observable.fromCallable(() -> { DojoUtil.dojoParams = dojoParams; Log.i(TAG, "setDojoParams: ".concat(dojoParams)); String url = getUrl(dojoParams); if(url.charAt(url.length() - 1) != '/') { url = url + "/"; JSONObject obj = new JSONObject(dojoParams); if(obj.has("pairing") && obj.getJSONObject("pairing").has("url")) { obj.getJSONObject("pairing").put("url", url); DojoUtil.dojoParams = obj.toString(); } } if(SamouraiWallet.getInstance().isTestNet()) { WebUtil.SAMOURAI_API2_TESTNET_TOR = url; } else { WebUtil.SAMOURAI_API2_TOR = url; } String apiToken = getApiKey(dojoParams); APIFactory.getInstance(context).setAppToken(apiToken); APIFactory.getInstance(context).getToken(true); return true; }); } public synchronized void removeDojoParams() { DojoUtil.dojoParams = null; if(SamouraiWallet.getInstance().isTestNet()) { WebUtil.SAMOURAI_API2_TESTNET_TOR = WebUtil.SAMOURAI_API2_TESTNET_TOR_DIST; } else { WebUtil.SAMOURAI_API2_TOR = WebUtil.SAMOURAI_API2_TOR_DIST; } APIFactory.getInstance(context).setAppToken(null); APIFactory.getInstance(context).getToken(false); } public String getVersion(String data) { if(!isValidPairingPayload(data)) { return null; } try { JSONObject obj = new JSONObject(data); JSONObject pObj = obj.getJSONObject("pairing"); return pObj.getString("version"); } catch(JSONException je) { return null; } } public String getApiKey(String data) { if(!isValidPairingPayload(data)) { return null; } try { JSONObject obj = new JSONObject(data); JSONObject pObj = obj.getJSONObject("pairing"); return pObj.getString("apikey"); } catch(JSONException je) { return null; } } public String getUrl(String data) { if(!isValidPairingPayload(data)) { return null; } try { JSONObject obj = new JSONObject(data); JSONObject pObj = obj.getJSONObject("pairing"); return pObj.getString("url"); } catch(JSONException je) { return null; } } public JSONObject toJSON() { JSONObject obj = null; try { if(dojoParams != null) { obj = new JSONObject(dojoParams); } else { obj = new JSONObject(); } } catch(JSONException je) { ; } return obj; } public void fromJSON(JSONObject obj) { if(isValidPairingPayload(obj.toString())) { dojoParams = obj.toString(); if (dojoParams != null) { if (SamouraiWallet.getInstance().isTestNet()) { WebUtil.SAMOURAI_API2_TESTNET_TOR = getUrl(dojoParams); } else { WebUtil.SAMOURAI_API2_TOR = getUrl(dojoParams); } String apiToken = getApiKey(dojoParams); APIFactory.getInstance(context).setAppToken(apiToken); } } } }
package org.anddev.andengine.collision; /** * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class BaseCollisionChecker { // Constants // Fields // Constructors // Getter & Setter // Methods for/from SuperClass/Interfaces // Methods public static boolean checkAxisAlignedBoxCollision(final float pLeftA, final float pTopA, final float pRightA, final float pBottomA, final float pLeftB, final float pTopB, final float pRightB, final float pBottomB) { return (pLeftA < pRightB && pLeftB < pRightA && pTopA < pBottomB && pTopB < pBottomA); } public static boolean checkLineCollision(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { return ((relativeCCW(pX1, pY1, pX2, pY2, pX3, pY3) * relativeCCW(pX1, pY1, pX2, pY2, pX4, pY4) <= 0) && (relativeCCW(pX3, pY3, pX4, pY4, pX1, pY1) * relativeCCW(pX3, pY3, pX4, pY4, pX2, pY2) <= 0)); } /** * Returns an indicator of where the specified point (PX,&nbsp;PY) lies with * respect to the line segment from (X1,&nbsp;Y1) to (X2,&nbsp;Y2). The * return value can be either 1, -1, or 0 and indicates in which direction * the specified line must pivot around its first endpoint, (X1,&nbsp;Y1), * in order to point at the specified point (PX,&nbsp;PY). * <p> * A return value of 1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the negative Y axis. In * the default coordinate system used by Java 2D, this direction is * counterclockwise. * <p> * A return value of -1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the positive Y axis. In * the default coordinate system, this direction is clockwise. * <p> * A return value of 0 indicates that the point lies exactly on the line * segment. Note that an indicator value of 0 is rare and not useful for * determining colinearity because of floating point rounding issues. * <p> * If the point is colinear with the line segment, but not between the * endpoints, then the value will be -1 if the point lies * "beyond (X1,&nbsp;Y1)" or 1 if the point lies "beyond (X2,&nbsp;Y2)". * * @param pX1 * ,&nbsp;Y1 the coordinates of the beginning of the specified * line segment * @param pX2 * ,&nbsp;Y2 the coordinates of the end of the specified line * segment * @param pPX * ,&nbsp;PY the coordinates of the specified point to be * compared with the specified line segment * @return an integer that indicates the position of the third specified * coordinates with respect to the line segment formed by the first * two specified coordinates. */ public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) { pX2 -= pX1; pY2 -= pY1; pPX -= pX1; pPY -= pY1; float ccw = pPX * pY2 - pPY * pX2; if (ccw == 0.0f) { // The point is colinear, classify based on which side of // the segment the point falls on. We can calculate a // relative value using the projection of PX,PY onto the // segment - a negative value indicates the point projects // outside of the segment in the direction of the particular // endpoint used as the origin for the projection. ccw = pPX * pX2 + pPY * pY2; if (ccw > 0.0f) { // Reverse the projection to be relative to the original X2,Y2 // X2 and Y2 are simply negated. // PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted // from them (based on the original values) // Since we really want to get a positive answer when the // point is "beyond (X2,Y2)", then we want to calculate // the inverse anyway - thus we leave X2 & Y2 negated. pPX -= pX2; pPY -= pY2; ccw = pPX * pX2 + pPY * pY2; if (ccw < 0.0f) { ccw = 0.0f; } } } return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); } // Inner and Anonymous Classes }
package com.zfdang.zsmth_android; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import com.zfdang.SMTHApplication; import com.zfdang.zsmth_android.helpers.RecyclerViewUtil; import com.zfdang.zsmth_android.listeners.OnTopicFragmentInteractionListener; import com.zfdang.zsmth_android.listeners.OnVolumeUpDownListener; import com.zfdang.zsmth_android.models.Topic; import com.zfdang.zsmth_android.models.TopicListContent; import com.zfdang.zsmth_android.newsmth.SMTHHelper; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import java.util.List; import okhttp3.ResponseBody; /** * A fragment representing a list of Items. * <p/> * Activities containing this fragment MUST implement the {@link OnTopicFragmentInteractionListener} * interface. */ public class HotTopicFragment extends Fragment implements OnVolumeUpDownListener { private final String TAG = "HotTopicFragment"; private OnTopicFragmentInteractionListener mListener; private RecyclerView mRecyclerView = null; private SmartRefreshLayout mRefreshLayout = null; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public HotTopicFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_hot_topic, container, false); // pull to refresh for android recyclerview mRefreshLayout = (SmartRefreshLayout) rootView; mRefreshLayout.setEnableLoadmore(false); mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshLayout) { RefreshGuidanceFromWWW(); } }); // ItemItemDecoration // ItemItemAnimator // itemhighlight,guidance itembackgroun (android:background="@drawable/recyclerview_item_bg") mRecyclerView = (RecyclerView) rootView.findViewById(R.id.guidance_recycler_view); // Set the adapter if (mRecyclerView != null) { mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL, 0)); Context context = rootView.getContext(); mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(context)); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setAdapter(new HotTopicRecyclerViewAdapter(TopicListContent.HOT_TOPICS, mListener)); } getActivity().setTitle(SMTHApplication.App_Title_Prefix + ""); if (TopicListContent.HOT_TOPICS.size() == 0) { RefreshGuidance(); } return rootView; } public void showLoadingHints() { MainActivity activity = (MainActivity) getActivity(); if (activity != null) activity.showProgress("..."); } public void clearLoadingHints() { // disable progress bar MainActivity activity = (MainActivity) getActivity(); if (activity != null) { activity.dismissProgress(); } // disable SmartFreshLayout if(mRefreshLayout.isRefreshing()) { mRefreshLayout.finishRefresh(100); } } public void RefreshGuidance() { // called by onCreate & refresh menu item showLoadingHints(); RefreshGuidanceFromWWW(); } public void RefreshGuidanceFromWWW() { final SMTHHelper helper = SMTHHelper.getInstance(); helper.wService.getAllHotTopics().flatMap(new Function<ResponseBody, ObservableSource<Topic>>() { @Override public ObservableSource<Topic> apply(@NonNull ResponseBody responseBody) throws Exception { try { String response = responseBody.string(); List<Topic> results = SMTHHelper.ParseHotTopicsFromWWW(response); return Observable.fromIterable(results); } catch (Exception e) { Log.d(TAG, Log.getStackTraceString(e)); } return null; } }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Topic>() { @Override public void onSubscribe(@NonNull Disposable disposable) { // clearHotTopics current hot topics TopicListContent.clearHotTopics(); mRecyclerView.getAdapter().notifyDataSetChanged(); } @Override public void onNext(@NonNull Topic topic) { // Log.d(TAG, topic.toString()); TopicListContent.addHotTopic(topic); mRecyclerView.getAdapter().notifyItemInserted(TopicListContent.HOT_TOPICS.size() - 1); } @Override public void onError(@NonNull Throwable e) { clearLoadingHints(); Toast.makeText(SMTHApplication.getAppContext(), "!\n" + e.toString(), Toast.LENGTH_LONG).show(); } @Override public void onComplete() { Topic topic = new Topic("-- END --"); TopicListContent.addHotTopic(topic); mRecyclerView.getAdapter().notifyItemInserted(TopicListContent.HOT_TOPICS.size() - 1); clearLoadingHints(); } }); } // If you run your application on a device with API 23 (marshmallow) then onAttach(Context) will be called. // On all previous Android Versions onAttach(Activity) will be called. @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnTopicFragmentInteractionListener) { mListener = (OnTopicFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnTopicFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.main_action_refresh) { RefreshGuidance(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onVolumeUpDown(int keyCode) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { RecyclerViewUtil.ScrollRecyclerViewByKey(mRecyclerView, keyCode); } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { RecyclerViewUtil.ScrollRecyclerViewByKey(mRecyclerView, keyCode); } return true; } }
package de.reneruck.contactor; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import de.reneruck.contactor.models.Contact; public class EditContactActivity extends AppCompatActivity { private ContactsOpenHelper sqlHelper; private Contact currentContact; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_contact); this.sqlHelper = new ContactsOpenHelper(getApplicationContext()); this.currentContact = new Contact(getIntent().getIntExtra("contactId", -1)); if (this.currentContact.getId() != -1) { loadContactData(); populateFields(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_edit_contact, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void populateFields() { ((EditText) findViewById(R.id.input_name)).setText(this.currentContact.getName()); ((EditText) findViewById(R.id.input_email)).setText(this.currentContact.getEmail()); ((EditText) findViewById(R.id.input_phone_private)).setText(this.currentContact.getPhonePrivate()); ((EditText) findViewById(R.id.input_phone_work)).setText(this.currentContact.getPhoneWork()); } private void loadContactData() { String[] contactIds = new String[]{String.valueOf(this.currentContact.getId())}; Cursor contactResult = this.sqlHelper.getReadableDatabase().rawQuery("select * from contacts where _id = ?", contactIds); contactResult.moveToFirst(); this.currentContact = new Contact(contactResult); } }
package org.irmacard.android.util.credentials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import org.irmacard.credentials.info.CredentialDescription; import org.irmacard.credentials.info.DescriptionStore; import org.irmacard.credentials.info.InfoException; import org.irmacard.credentials.info.IssuerDescription; import org.irmacard.credentials.info.TreeWalkerI; import org.irmacard.credentials.info.VerificationDescription; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class AndroidWalker implements TreeWalkerI { static final String IRMA_CORE = "irma_configuration/"; static final String TAG = "AWalker"; DescriptionStore descriptionStore; AssetManager assetManager; public AndroidWalker(AssetManager assetManager) { this.assetManager = assetManager; } @Override public void parseConfiguration(DescriptionStore descriptionStore) throws InfoException { this.descriptionStore = descriptionStore; InputStream s; try { s = assetManager.open(IRMA_CORE + "android/issuers.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(s)); String issuer = null; while ((issuer = in.readLine()) != null) { Log.i("filecontent", "Found issuer: " + issuer); String issuerDesc = IRMA_CORE + issuer + "/description.xml"; Log.i("filecontent", "Parsing log of: " + issuerDesc); IssuerDescription id = new IssuerDescription(assetManager.open(issuerDesc)); descriptionStore.addIssuerDescription(id); Log.i("filecontent", "Issuer added to result"); tryProcessCredentials(issuer); } } catch (IOException e) { new InfoException(e, "Failed to read (from) android/issuers.txt file"); } try { s = assetManager.open(IRMA_CORE + "android/verifiers.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(s)); String issuer = null; while ((issuer = in.readLine()) != null) { // FIXME: this will duplicate stuff in the store, or at least do extra work. Log.i("filecontent", "Found verifier: " + issuer); String issuerDesc = IRMA_CORE + issuer + "/description.xml"; Log.i("filecontent", "Parsing log of: " + issuerDesc); IssuerDescription id = new IssuerDescription(assetManager.open(issuerDesc)); descriptionStore.addIssuerDescription(id); Log.i("filecontent", "Issuer added to result"); tryProcessVerifications(issuer); } } catch (IOException e) { new InfoException(e, "Failed to read (from) android/issuers.txt file"); } } private void tryProcessCredentials(String issuer) throws InfoException { String path = IRMA_CORE + issuer + "/Issues"; try { Log.i("credential", "Examining path " + path); for(String cred : assetManager.list(path)) { String credentialSpec = path + "/" + cred + "/description.xml"; Log.i("issuer+credential", "Reading credential " + credentialSpec); CredentialDescription cd = new CredentialDescription(assetManager.open(credentialSpec)); descriptionStore.addCredentialDescription(cd); Log.i("credential", cd.toString()); } } catch (IOException e) { new InfoException(e, "Failed to read credentials issued by " + issuer + "."); } } private void tryProcessVerifications(String verifier) throws InfoException { String path = IRMA_CORE + verifier + "/Verifies"; try { Log.i("credential", "Examining path " + path); for(String cred : assetManager.list(path)) { String proofSpec = path + "/" + cred + "/description.xml"; Log.i("issuer+credential", "Reading proofSpec " + proofSpec); VerificationDescription vd = new VerificationDescription(assetManager.open(proofSpec)); descriptionStore.addVerificationDescription(vd); Log.i("credential", vd.toString()); } } catch (IOException e) { new InfoException(e, "Failed to read verifications used by " + verifier + "."); } } @Override public InputStream retrieveFile(URI path) throws InfoException { try { return assetManager.open(IRMA_CORE + path.toString()); } catch (IOException e) { e.printStackTrace(); throw new InfoException(e, "reading file " + path); } } public Bitmap getIssuerLogo(IssuerDescription issuer) { Bitmap logo = null; String issuerID = issuer.getID(); try { logo = BitmapFactory.decodeStream(retrieveFile(new URI(issuerID + "/logo.png"))); } catch (InfoException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return logo; } public Bitmap getVerificationLogo(VerificationDescription verification) { Bitmap logo = null; // TODO: is this correct? String issuerID = verification.getIssuerID(); try { logo = BitmapFactory.decodeStream(retrieveFile(new URI(issuerID + "/logo.png"))); } catch (InfoException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return logo; } }
package de.ulrichraab.rxcontacts.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.List; import de.ulrichraab.rxcontacts.Contact; import de.ulrichraab.rxcontacts.RxContacts; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.functions.Func2; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private ContactAdapter contactAdapter; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeRecyclerView(); requestContacts(); } private void initializeRecyclerView () { ContactAdapter contactAdapter = getContactAdapter(); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); RecyclerView rv = (RecyclerView) findViewById(R.id.recyclerView_contacts); if (rv != null) { rv.setAdapter(contactAdapter); rv.setLayoutManager(linearLayoutManager); } } private ContactAdapter getContactAdapter () { if (contactAdapter != null) { return contactAdapter; } contactAdapter = new ContactAdapter(); return contactAdapter; } private void requestContacts () { RxContacts .fetch(this) .filter(new Func1<Contact, Boolean>() { @Override public Boolean call (Contact contact) { return contact.inVisibleGroup == 1; } }) .toSortedList(new Func2<Contact, Contact, Integer>() { @Override public Integer call (Contact lhs, Contact rhs) { return lhs.displayName.compareTo(rhs.displayName); } }) .observeOn(Schedulers.io()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<Contact>>() { @Override public void onCompleted () {} @Override public void onError (Throwable e) {} @Override public void onNext (List<Contact> contacts) { ContactAdapter adapter = getContactAdapter(); adapter.setContacts(contacts); adapter.notifyDataSetChanged(); } }); } }
package org.kwstudios.play.ragemode.gameLogic; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.gmail.zahusek.tinyprotocolapi.api.tabapi.TabAPI; public class TabGuiUpdater { public static void setTabGui(List<String> playerUUIDs) { for (String playerUUID : playerUUIDs) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } } public static void setTabGui(String playerUUID) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } public static void updateTabGui(String gameName) { if (gameName != null) { List<PlayerPoints> playersPoints = new ArrayList<PlayerPoints>(); String[] playersInGame = PlayerList.getPlayersInGame(gameName); if (playersInGame != null) { for (String playerInGame : playersInGame) { if (playerInGame != null) { PlayerPoints playerPoints = RageScores.getPlayerPoints(playerInGame); if (playerPoints != null) { playersPoints.add(playerPoints); } } } } for (PlayerPoints playerPoints : playersPoints) { Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); TabAPI.setTabSlot(player, 0, 1, ChatColor.BLUE + Integer.toString(playersPoints.size()), 0); } Collections.sort(playersPoints); for (int i = 0; i < playersPoints.size(); i++) { PlayerPoints playerPoints = playersPoints.get(i); Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); int points = playerPoints.getPoints(); int kills = playerPoints.getKills(); int deaths = playerPoints.getDeaths(); for (PlayerPoints innerPlayerPoints : playersPoints) { Player innerPlayer = Bukkit.getPlayer(UUID.fromString(innerPlayerPoints.getPlayerUUID())); TabAPI.setTabSlot(innerPlayer, 0, i + 5, ChatColor.YELLOW + Integer.toString(points), 0); TabAPI.setTabSlot(innerPlayer, 1, i + 5, ChatColor.YELLOW + player.getName(), 0); TabAPI.setTabSlot(innerPlayer, 2, i + 5, ChatColor.YELLOW + Integer.toString(kills) + " - " + Integer.toString(deaths), 0); } } for (PlayerPoints playerPoints : playersPoints) { TabAPI.modifyTab(Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID()))); } } } public static void removeTabForPlayer(Player player){ TabAPI.defaultTab(player); } private static void setTitles(Player player) { TabAPI.setTabHnF(player, ChatColor.DARK_RED + "RageMode", ChatColor.translateAlternateColorCodes('&', "&eKWStudios.org ") + ChatColor.translateAlternateColorCodes('&', "&3Network")); TabAPI.setTabSlot(player, 0, 0, ChatColor.translateAlternateColorCodes('&', "&9Player"), 100); TabAPI.setTabSlot(player, 1, 0, ChatColor.translateAlternateColorCodes('&', "&9Time"), 100); TabAPI.setTabSlot(player, 2, 0, ChatColor.translateAlternateColorCodes('&', "&9Map"), 100); TabAPI.setTabSlot(player, 0, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPoints"), 100); TabAPI.setTabSlot(player, 1, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPlayer"), 100); TabAPI.setTabSlot(player, 2, 4, ChatColor.translateAlternateColorCodes('&', "&6&lKills - Deaths"), 100); } }
package jp.ne.hatena.hackugyo.procon; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.AppBarLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.util.Pair; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.beardedhen.androidbootstrap.BootstrapButton; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxTextView; import com.jakewharton.rxbinding.widget.TextViewEditorActionEvent; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import jp.ne.hatena.hackugyo.procon.adapter.AutoCompleteSuggestionArrayAdapter; import jp.ne.hatena.hackugyo.procon.adapter.ChatLikeListAdapter; import jp.ne.hatena.hackugyo.procon.adapter.SummaryListAdapter; import jp.ne.hatena.hackugyo.procon.event.DataDeletedEvent; import jp.ne.hatena.hackugyo.procon.event.DataSavedEvent; import jp.ne.hatena.hackugyo.procon.event.RequestDataDeleteEvent; import jp.ne.hatena.hackugyo.procon.event.RequestDataSaveEvent; import jp.ne.hatena.hackugyo.procon.event.RxBusProvider; import jp.ne.hatena.hackugyo.procon.io.ImprovedTextCrawler; import jp.ne.hatena.hackugyo.procon.model.ChatTheme; import jp.ne.hatena.hackugyo.procon.model.ChatThemeRepository; import jp.ne.hatena.hackugyo.procon.model.CitationResource; import jp.ne.hatena.hackugyo.procon.model.CitationResourceRepository; import jp.ne.hatena.hackugyo.procon.model.Memo; import jp.ne.hatena.hackugyo.procon.model.MemoRepository; import jp.ne.hatena.hackugyo.procon.ui.AbsBaseActivity; import jp.ne.hatena.hackugyo.procon.ui.RecyclerClickable; import jp.ne.hatena.hackugyo.procon.ui.fragment.AbsCustomDialogFragment; import jp.ne.hatena.hackugyo.procon.ui.fragment.ChoiceDialogFragment; import jp.ne.hatena.hackugyo.procon.ui.fragment.ConfirmDialogFragment; import jp.ne.hatena.hackugyo.procon.ui.fragment.ImageDialogFragment; import jp.ne.hatena.hackugyo.procon.ui.fragment.InputDialogFragment; import jp.ne.hatena.hackugyo.procon.ui.widget.CustomBootStrapBrand; import jp.ne.hatena.hackugyo.procon.ui.widget.KeyboardClosingDrawerListener; import jp.ne.hatena.hackugyo.procon.ui.widget.RecyclerViewEmptySupport; import jp.ne.hatena.hackugyo.procon.util.ArrayUtils; import jp.ne.hatena.hackugyo.procon.util.EditTextUtils; import jp.ne.hatena.hackugyo.procon.util.LogUtils; import jp.ne.hatena.hackugyo.procon.util.StringUtils; import jp.ne.hatena.hackugyo.procon.util.UrlUtils; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; public class MainActivity extends AbsBaseActivity implements AbsCustomDialogFragment.Callbacks { public static final String TAG_INPUT_NEW_THEME = "MainActivity.TAG_INPUT_NEW_THEME"; private static final String TAG_CONFIRM_DELETE_THEME = "MainActivity.TAG_CONFIRM_DELETE_THEME"; private static final String TAG_CHOOSE_EDIT_MODE = "MainActivity.TAG_CHOOSE_EDIT_MODE"; private static final String TAG_EDIT_CONTENT = "MainActivity.TAG_EDIT_CONTENT"; private static final String TAG_EDIT_CITATION_RESOURCE = "MainActivity.TAG_EDIT_CITATION_RESOURCE"; private static final String TAG_SHOW_IMAGE = "MainActivity.TAG_SHOW_IMAGE"; public static final String ITEM_ID = "MainActivity.ITEM_ID"; public static final String CHOICE_IDS = "MainActivity.CHOICE_IDS"; private static final int REQUEST_CAMERA_CHOOSER = 1000; private static final int REQUEST_GALLERY_CHOOSER = 1001; private static final String SHARED_PREFERENCE_LAST_THEME_ID = "MainActivity.SHARED_PREFERENCE_LAST_THEME_ID"; private static final String SHARED_PREFERENCE_SHOW_REORDERING_HINT = "MainActivity.SHARED_PREFERENCE_SHOW_REORDERING_HINT"; public enum EditModeEnum { DELETE_THIS_ITEM(0, ""), FORCE_RELOAD(1, "Web"), SHARE_THIS_ITEM(2, ""), OPEN_URL(3, "URL"), EDIT_THIS_ITEM(4, ""), EDIT_CITATION(5, ""),; public final int id; public final String title; EditModeEnum(final int id, final String title) { this.id = id; this.title = title; } static ArrayList<String> titlesFrom(List<EditModeEnum> enums) { return new ArrayList<String>( Observable.from(enums).map(new Func1<EditModeEnum, String>() { @Override public String call(EditModeEnum editModeEnum) { return editModeEnum.title; } }).toList().toBlocking().single() ); } static ArrayList<Integer> idsFrom(List<EditModeEnum> enums) { return new ArrayList<Integer>( Observable.from(enums).map(new Func1<EditModeEnum, Integer>() { @Override public Integer call(EditModeEnum editModeEnum) { return editModeEnum.id; } }).toList().toBlocking().single() ); } } private final MainActivity self = this; Toolbar toolbar; AppBarLayout appBar; // View MainActivityViewProvider viewProvider; private ArrayAdapter citationResourceSuggestionAdapter; // DrawerView private NavigationView drawerLeft; private DrawerLayout drawerManager; private NavigationView drawerRight; private EditText themeEditText; private BootstrapButton themeDeleteButton; private BootstrapButton themeExportButton; private BootstrapButton reorderMemosButton; private RecyclerClickable imageOnClickRecyclerListener; private ImageView imageThumbnailView; /** * RecylerView{@link #mainRecyclerView} */ private boolean isInReorderMode = false; RecyclerViewEmptySupport mainRecyclerView, summaryRecyclerView; ChatLikeListAdapter mainListAdapter; SummaryListAdapter summaryListAdapter; Snackbar snackbar; private ChatTheme chatTheme; final ArrayList<Memo> memos = new ArrayList<Memo>(); private final List<ChatTheme> chatThemeList = new ArrayList<>(); private final List<String> citationResources = new ArrayList<>(); private MemoRepository memoRepository; private ChatThemeRepository chatThemeRepository; private CitationResourceRepository citationResourceRepository; private MainActivityHelper mainActivityHelper; private NavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; private RecyclerClickable mainOnClickRecyclerListener, summaryOnClickRecyclerListener; private CompositeSubscription compositeSubscription; /** * IntentUri */ private Uri tempUriForRequestChooser; private BootstrapButton photoButton; private BootstrapButton cameraButton; private ArrayList<Memo> stashedMemosForReordering; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); chatThemeRepository = new ChatThemeRepository(this); memoRepository = new MemoRepository(this); citationResourceRepository = new CitationResourceRepository(this); //toolbar setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); if (toolbar != null) { setSupportActionBar(toolbar); toolbar.setNavigationIcon(R.drawable.ic_home); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isInReorderMode) getDrawerManager().openDrawer(Gravity.LEFT); } }); } appBar = (AppBarLayout) findViewById(R.id.main_appbar); setupViews(); reloadChatThemeList(); final long latestChatThemeId = AppApplication.getSharedPreferences().getLong(SHARED_PREFERENCE_LAST_THEME_ID, 0); chatTheme = Observable.from(chatThemeList).firstOrDefault(ArrayUtils.last(chatThemeList), new Func1<ChatTheme, Boolean>() { @Override public Boolean call(ChatTheme chatTheme) { return chatTheme.getId() == latestChatThemeId; } }).toBlocking().single(); reloadChatThemeMenu(); //memo getLoadMemoObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Action1<List<Memo>>() { @Override public void call(List<Memo> memos) { renewCitationResources(); mainActivityHelper = new MainActivityHelper( new ImprovedTextCrawler(AppApplication.provideOkHttpClient(self)), mainListAdapter, self.memos, memoRepository); mainActivityHelper.loadPreviewAsync(); } } ); } @Override public boolean onCreateOptionsMenu(Menu menu) { //menu MenuInflater inflater = getMenuInflater(); if (isInReorderMode) { inflater.inflate(R.menu.menu_main_reorder, menu); } else { inflater.inflate(R.menu.menu_main, menu); } return super.onCreateOptionsMenu(menu); } @Override protected void onResume() { super.onResume(); compositeSubscription = new CompositeSubscription(); compositeSubscription.add( RxBusProvider.getInstance() .subscribe(DataSavedEvent.class, new Action1<DataSavedEvent>() { @Override public void call(DataSavedEvent dataSavedEvent) { onMemoSaved(dataSavedEvent); } }, AndroidSchedulers.mainThread()) ); compositeSubscription.add( RxBusProvider.getInstance() .subscribe(DataDeletedEvent.class, new Action1<DataDeletedEvent>() { @Override public void call(DataDeletedEvent dataDeletedEvent) { onMemoDeleted(dataDeletedEvent); } }, AndroidSchedulers.mainThread()) ); memoRepository.onResume(this); chatThemeRepository.onResume(this); citationResourceRepository.onResume(this); } @Override protected void onPause() { super.onPause(); if (compositeSubscription != null) compositeSubscription.unsubscribe(); if (memoRepository != null) memoRepository.onPause(); if (chatThemeRepository != null) chatThemeRepository.onPause(); if (citationResourceRepository != null) citationResourceRepository.onPause(); AppApplication.getSharedPreferences().edit().putLong(SHARED_PREFERENCE_LAST_THEME_ID, chatTheme.getId()).apply(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //icon if (id == R.id.menu_edit_this_theme) { NavigationView drawer = provideRightDrawer(); if (getDrawerManager().isDrawerOpen(drawer)) { getDrawerManager().closeDrawer(drawer); } else { if (!isInReorderMode) getDrawerManager().openDrawer(drawer); } return true; } else if (id == R.id.menu_done_reorder) { if (Memo.setPositions(Observable.from(memos))) { showProgressDialog(); updateMemoAsync(memos); } isInReorderMode = false; setToolbarScrollable(true); invalidateOptionsMenu(); } else if (id == R.id.menu_cancel_reorder) { if (stashedMemosForReordering != null) { memos.clear(); memos.addAll(stashedMemosForReordering); stashedMemosForReordering.clear(); stashedMemosForReordering = null; mainListAdapter.notifyDataSetChanged(); } isInReorderMode = false; setToolbarScrollable(true); invalidateOptionsMenu(); } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == REQUEST_CAMERA_CHOOSER) { getPhotoButton().setVisibility(View.GONE); getCameraButton().setVisibility(View.GONE); if(resultCode != RESULT_OK) { tempUriForRequestChooser = null; return ; } Uri resultUri = (data != null ? data.getData() : tempUriForRequestChooser); // dataUri LogUtils.d("data: " + resultUri); tempUriForRequestChooser = null; if(resultUri == null) { return; } MediaScannerConnection.scanFile( this, new String[]{resultUri.getPath()}, new String[]{"image/jpeg"}, null ); viewProvider.setImage(resultUri); } else if (requestCode == REQUEST_GALLERY_CHOOSER) { getPhotoButton().setVisibility(View.GONE); getCameraButton().setVisibility(View.GONE); if(resultCode != RESULT_OK) { return ; } Uri resultUri = (data != null ? data.getData() : tempUriForRequestChooser); LogUtils.v("data: " + resultUri); if(resultUri == null) { return; } viewProvider.setImage(resultUri); } } private void setupViews() { viewProvider = new MainActivityViewProvider(this, getCitationResourceSuggestionAdapter(), setupAddAsProButton(), setupAddAsConButton(), setupOthersButton()); viewProvider.setImageView(provideImageThumbnailView()); provideRightDrawer(); provideRightDrawerTitle(); setupRightDrawerButtons(); provideRightDrawerRecyclerView(); getDrawerManager().addDrawerListener(new KeyboardClosingDrawerListener()); mainRecyclerView = (RecyclerViewEmptySupport) findViewById(R.id.listView); { itemTouchHelper.attachToRecyclerView(mainRecyclerView); mainRecyclerView.addItemDecoration(itemTouchHelper); } mainListAdapter = new ChatLikeListAdapter(this, memos, getMainOnClickRecyclerListener()); mainListAdapter.setOnImageClickListener(getImageOnClickRecyclerListener()); mainRecyclerView.setAdapter(mainListAdapter); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); llm.setSmoothScrollbarEnabled(true); mainRecyclerView.setLayoutManager(llm); } private BootstrapButton setupAddAsProButton() { //Button View.OnClickListener listener = new View. OnClickListener() { @Override public void onClick(View v) { saveMemoAndUpdate(v, true); } }; BootstrapButton viewById = (BootstrapButton) findViewById(R.id.button_save_as_pro); viewById.setBootstrapBrand(CustomBootStrapBrand.PRO); viewById.setOnClickListener(listener); return viewById; } private BootstrapButton setupAddAsConButton() { //Button View.OnClickListener listener = new View. OnClickListener() { @Override public void onClick(View v) { saveMemoAndUpdate(v, false); } }; BootstrapButton viewById = (BootstrapButton) findViewById(R.id.button_save_as_con); viewById.setBootstrapBrand(CustomBootStrapBrand.CON); viewById.setOnClickListener(listener); return viewById; } private BootstrapButton setupOthersButton() { //Button View.OnClickListener listener = new View. OnClickListener() { @Override public void onClick(View v) { getPhotoButton().setVisibility(getPhotoButton().getVisibility() == View.GONE ? View.VISIBLE : View.GONE); getCameraButton().setVisibility(getCameraButton().getVisibility() == View.GONE ? View.VISIBLE : View.GONE); } }; BootstrapButton viewById = (BootstrapButton) findViewById(R.id.button_save_as_other); if (viewById != null) { viewById.setBootstrapBrand(CustomBootStrapBrand.OTHER); viewById.setOnClickListener(listener); } return viewById; } private BootstrapButton getCameraButton() { if (cameraButton == null) { //Button View.OnClickListener listener = new View. OnClickListener() { @Override public void onClick(View v) { showCamera(); } }; cameraButton = (BootstrapButton) findViewById(R.id.button_load_from_camera); if (cameraButton != null) { cameraButton.setBootstrapBrand(CustomBootStrapBrand.OTHER); cameraButton.setOnClickListener(listener); } } return cameraButton; } private BootstrapButton getPhotoButton() { if (photoButton == null) { //Button View.OnClickListener listener = new View. OnClickListener() { @Override public void onClick(View v) { showGallery(); } }; photoButton = (BootstrapButton) findViewById(R.id.button_load_from_gallery); if (photoButton != null) { photoButton.setBootstrapBrand(CustomBootStrapBrand.OTHER); photoButton.setOnClickListener(listener); } } return photoButton; } private ImageView provideImageThumbnailView() { if (imageThumbnailView == null) { imageThumbnailView = (ImageView)findViewById(R.id.imageView); imageThumbnailView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (viewProvider.getImageUri() == null) { showGallery(); } else { showImageEnlarge(viewProvider.getImageUri().toString()); } } }); } return imageThumbnailView; } private NavigationView provideRightDrawer() { if (drawerRight == null) { drawerRight = (NavigationView) findViewById(R.id.drawer_right); } return drawerRight; } private TextView provideRightDrawerTitle() { if (themeEditText == null) { themeEditText = (EditText) provideRightDrawer().findViewById(R.id.navigation_header_right_title); Observable<TextViewEditorActionEvent> textViewEditorActionEventObservable = RxTextView.editorActionEvents(themeEditText); textViewEditorActionEventObservable.subscribe( new Action1<TextViewEditorActionEvent>() { @Override public void call(TextViewEditorActionEvent event) { if (EditTextUtils.isDone(event.actionId(), event.keyEvent())) { EditTextUtils.closeKeyboard(MainActivity.this, event.view()); if (editChatTheme(event.view().getText().toString(), false)) { showSingleToast(R.string.toast_theme_name_edited, Toast.LENGTH_SHORT); } } } } ); Observable<Boolean> booleanObservable = RxView.focusChanges(themeEditText); booleanObservable.subscribe(new Action1<Boolean>() { @Override public void call(Boolean hasFocus) { if (!hasFocus) { editChatTheme(themeEditText.getText().toString()); } } }); } return themeEditText; } private void setupRightDrawerButtons() { provideThemeDeleteButton(); provideReorderMemosButton(); provideThemeExportButton(); } private BootstrapButton provideThemeDeleteButton() { if (themeDeleteButton == null) { themeDeleteButton = (BootstrapButton) provideRightDrawer().findViewById(R.id.button_delete_this_theme); themeDeleteButton.setBootstrapBrand(CustomBootStrapBrand.OTHER); themeDeleteButton.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL); themeDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ConfirmDialogFragment confirmDialogFragment = ConfirmDialogFragment.newInstance(MainActivity.this, null, "", ""); showDialogFragment(confirmDialogFragment, TAG_CONFIRM_DELETE_THEME); } }); } return themeDeleteButton; } /** * * @return */ private BootstrapButton provideReorderMemosButton() { if (reorderMemosButton == null) { reorderMemosButton = (BootstrapButton) provideRightDrawer().findViewById(R.id.button_reorder_memos); reorderMemosButton.setBootstrapBrand(CustomBootStrapBrand.OTHER); reorderMemosButton.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL); reorderMemosButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setToolbarScrollable(false); stashedMemosForReordering = ArrayUtils.copy(memos); isInReorderMode = true; invalidateOptionsMenu(); getDrawerManager().closeDrawers(); } }); } return reorderMemosButton; } private void setToolbarScrollable(boolean isScrollable) { AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams(); params.setScrollFlags(isScrollable ? (AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL) : (AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS) ); if (!isScrollable) appBar.setExpanded(true); } private BootstrapButton provideThemeExportButton() { if (themeExportButton == null) { themeExportButton = (BootstrapButton) provideRightDrawer().findViewById(R.id.button_export_whole_memo); themeExportButton.setBootstrapBrand(CustomBootStrapBrand.OTHER); themeExportButton.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL); themeExportButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProgressDialog(); // mainActivityHelper. MainActivityHelper.createExportationObservable( chatTheme.getId(), Observable.from(memos) .observeOn(Schedulers.computation()) ) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Pair<Long, StringBuilder>>() { @Override public void call(Pair<Long, StringBuilder> result) { hideProgressDialog(); if (result.first != chatTheme.getId()) { return; } else { sendText(result.second.toString(), chatTheme.getTitle()); } } }); } }); } return themeExportButton; } private RecyclerView provideRightDrawerRecyclerView() { if (summaryRecyclerView == null) { View container = provideRightDrawer(); summaryRecyclerView = (RecyclerViewEmptySupport) container.findViewById(R.id.listView_summary); summaryListAdapter = new SummaryListAdapter(this, getSummaryOnClickRecyclerListener()); summaryRecyclerView.setAdapter(summaryListAdapter); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); summaryRecyclerView.setLayoutManager(llm); summaryRecyclerView.setEmptyView(container.findViewById(R.id.summary_empty)); } return summaryRecyclerView; } private DrawerLayout getDrawerManager() { if (drawerManager == null) drawerManager = (DrawerLayout) findViewById(R.id.drawer_layout); return drawerManager; } /** * * @return */ private Observable<List<Memo>> getLoadMemoObservable() { Observable<List<Memo>> listObservable = Observable.create( new Observable.OnSubscribe<List<Memo>>() { @Override public void call(Subscriber<? super List<Memo>> subscriber) { //database List<Memo> memos = memoRepository.loadFromChatTheme(MainActivity.this.chatTheme); if (memos == null) { subscriber.onNext(new ArrayList<Memo>()); } else { subscriber.onNext(memos); } subscriber.onCompleted(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(new Action1<List<Memo>>() { @Override public void call(List<Memo> memos) { self.memos.clear(); self.memos.addAll(memos); mainListAdapter.notifyDataSetChanged(); smoothScrollMainRecyclerView(mainRecyclerView, mainListAdapter); summaryListAdapter.reloadMemos(self.memos); } }); return listObservable; } private void saveMemoAndUpdate(View v, boolean asPro) { String content = viewProvider.contentEditText.getText().toString(); String citationResource = viewProvider.citationResourceEditText.getText().toString(); if (StringUtils.isPresent(content) || UrlUtils.isValidWebUrl(citationResource)) { Calendar cal = Calendar.getInstance(); Memo memo = createMemo(content, cal, citationResource, viewProvider.pagesEditText.getText().toString(), asPro); if (viewProvider.getImageUri() != null) { if (!ArrayUtils.any(memo.getCitationResources())) memo.addCitationResource(""); memo.addCitationResource(viewProvider.getImageUri().toString()); } insertMemoAsync(memo); //Keyboard EditText viewProvider.resetInputTexts(v); smoothScrollMainRecyclerView(mainRecyclerView, mainListAdapter); } } private void smoothScrollMainRecyclerView(RecyclerView recyclerView, RecyclerView.Adapter adapter) { appBar.setExpanded(false, true); // AppBarLayout recyclerView.smoothScrollToPosition(Math.max(0, adapter.getItemCount() - 1)); } private Memo createMemo(String text, Calendar cal, String resource, String pages, boolean isPro) { Memo memo = new Memo(cal, text, isPro); memo.addCitationResource(StringUtils.stripLast(resource)); memo.setPages(pages); memo.setChatTheme(chatTheme); return memo; } private void insertMemoAsync(Memo memo) { RxBusProvider.getInstance().post(new RequestDataSaveEvent(memo)); } private void deleteMemoAsync(Memo memo) { //memo RxBusProvider.getInstance().post(new RequestDataDeleteEvent(memo)); } private void updateMemoAsync(List<Memo> sortedMemos) { RxBusProvider.getInstance().post(new RequestDataSaveEvent(sortedMemos)); } private void onMemoSaved(DataSavedEvent event) { if (event.pairs.size() != 1) { onMemosUpdated(event.pairs); } else { Memo savedMemo = event.pairs.get(0).first; Memo inList = findById(memos, savedMemo.getId()); if (event.pairs.get(0).second) { if (inList == null) { memos.add(savedMemo); renewCitationResources(); //ListView mainListAdapter.notifyDataSetChanged(); summaryListAdapter.reloadMemos(self.memos); smoothScrollMainRecyclerView(mainRecyclerView, mainListAdapter); mainActivityHelper.loadPreviewAsync(savedMemo); } else { mainListAdapter.notifyItemChanged(memos.indexOf(inList)); } } else { LogUtils.w("something wrong"); viewProvider.resumeInputTexts((inList.isForUrl() ? "" : inList.getMemo()), inList.getCitationResource(), inList.getPages()); } } } private void onMemosUpdated(ArrayList<Pair<Memo, Boolean>> updatedResults) { LogUtils.d(""); Pair<Memo, Boolean> firstFailure = Observable.from(updatedResults) .firstOrDefault(null, new Func1<Pair<Memo,Boolean>, Boolean>() { @Override public Boolean call(Pair<Memo, Boolean> memoBooleanPair) { return !memoBooleanPair.second; } }).toBlocking().single(); if (firstFailure != null) { LogUtils.w(" " + firstFailure.first); } reloadChatThemeAsync(); hideProgressDialog(); } private void onMemoDeleted(DataDeletedEvent deleted) { for (Pair<Long, Boolean> result : deleted.pairs) { Memo inList = findById(memos, result.first); if (result.second) { memos.remove(inList); } else { LogUtils.w("something wrong"); if (inList != null) inList.setRemoved(false); } } renewCitationResources(); summaryListAdapter.reloadMemos(self.memos); mainListAdapter.notifyDataSetChanged(); } private static Memo findById(List<Memo> memo, final long memoId) { return Observable.from(memo).firstOrDefault(null, new Func1<Memo, Boolean>() { @Override public Boolean call(Memo memo) { return memo.getId() == memoId; } }).toBlocking().single(); } private RecyclerClickable getMainOnClickRecyclerListener() { if (mainOnClickRecyclerListener == null) { mainOnClickRecyclerListener = new RecyclerClickable() { @Override public void onRecyclerClicked(View v, int position) { //snackbar if (snackbar != null) snackbar.dismiss(); Memo memo = memos.get(position); if (memo.isForUrl()) { launchExternalBrowser(memo.getCitationResource()); } } @Override public void onRecyclerButtonClicked(View v, int position) { } @Override public boolean onRecyclerLongClicked(View v, final int position) { if (isInReorderMode) return false; if (memos.size() <= position) { LogUtils.w("" + memos.size() + " vs. " + position); return false; } //snackbar if (snackbar != null) snackbar.dismiss(); if (AppApplication.getSharedPreferences().getBoolean(SHARED_PREFERENCE_SHOW_REORDERING_HINT, true)) { showSingleToast("", Toast.LENGTH_LONG); AppApplication.getSharedPreferences().edit().putBoolean(SHARED_PREFERENCE_SHOW_REORDERING_HINT, false).apply(); } Memo memo = memos.get(position); ArrayList<EditModeEnum> items = new ArrayList<>(); { items.add(EditModeEnum.DELETE_THIS_ITEM); if (memo.isForUrl()) items.add(EditModeEnum.FORCE_RELOAD); items.add(EditModeEnum.SHARE_THIS_ITEM); if (memo.isForUrl()) items.add(EditModeEnum.OPEN_URL); if (!memo.isForUrl()) items.add(EditModeEnum.EDIT_THIS_ITEM); items.add(EditModeEnum.EDIT_CITATION); } Bundle args = new Bundle(); args.putLong(ITEM_ID, memo.getId()); args.putIntegerArrayList(CHOICE_IDS, EditModeEnum.idsFrom(items)); ChoiceDialogFragment choiceDialogFragment = ChoiceDialogFragment.newInstance(self, args, "", null,EditModeEnum.titlesFrom(items)); showDialogFragment(choiceDialogFragment, TAG_CHOOSE_EDIT_MODE); return true; } }; } return mainOnClickRecyclerListener; } private RecyclerClickable getSummaryOnClickRecyclerListener() { if (summaryOnClickRecyclerListener == null) { summaryOnClickRecyclerListener = new RecyclerClickable() { @Override public void onRecyclerClicked(View v, int position) { } @Override public void onRecyclerButtonClicked(View v, int position) { } @Override public boolean onRecyclerLongClicked(View v, int position) { return false; } }; } return summaryOnClickRecyclerListener; } private RecyclerClickable getImageOnClickRecyclerListener() { if (imageOnClickRecyclerListener == null) { imageOnClickRecyclerListener = new RecyclerClickable() { @Override public void onRecyclerClicked(View v, int position) { //snackbar if (snackbar != null) snackbar.dismiss(); Memo memo = memos.get(position); if (memo.isWithPhoto()) { showImageEnlarge(memo.getImageUrl()); } } @Override public void onRecyclerButtonClicked(View v, int position) { getMainOnClickRecyclerListener().onRecyclerButtonClicked(v, position); } @Override public boolean onRecyclerLongClicked(View v, int position) { return getMainOnClickRecyclerListener().onRecyclerLongClicked(v, position); } }; } return imageOnClickRecyclerListener; } void showImageEnlarge(String imageUrlString) { showDialogFragment( ImageDialogFragment.newInstance(self, null, imageUrlString), TAG_SHOW_IMAGE); } /** * <br> * Andorid4.0<br> * <br> * * @param url */ public void launchExternalBrowser(String url) { if (url == null) url = ""; Intent mainIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(mainIntent, PackageManager.MATCH_ALL); if (resolveInfos.size() == 0) { Toast.makeText(this, "", Toast.LENGTH_LONG).show(); LogUtils.e("browser activity cannot found."); } else { startActivity(mainIntent); } } public void launchExternalFileManager(Uri dirUri) { Intent mainIntent = new Intent(Intent.ACTION_VIEW); mainIntent.setDataAndType(dirUri, "resource/folder"); List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(mainIntent, PackageManager.MATCH_ALL); if (mainIntent.resolveActivityInfo(getPackageManager(), 0) == null) {// resolveInfos.size() == 0) { Toast.makeText(this, "", Toast.LENGTH_LONG).show(); } else { startActivity(mainIntent); } } private void showCamera() { // Intent */ File pathFilesDir = new File( StringUtils.build( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath(), File.separator, self.getPackageName(), File.separator, "Images" )); pathFilesDir.mkdirs(); String filename = StringUtils.build( StringUtils.padZeros(chatTheme.getId(), 8), "_", StringUtils.valueOf(System.currentTimeMillis()), ".jpg"); File capturedFile = new File(pathFilesDir, filename); tempUriForRequestChooser = Uri.fromFile(capturedFile); Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, tempUriForRequestChooser); Intent chooserIntent = Intent.createChooser(intentPhoto, ""); startActivityForResult(chooserIntent, REQUEST_CAMERA_CHOOSER); } private void showGallery() { // Intent Intent intentGallery; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { intentGallery = new Intent(Intent.ACTION_GET_CONTENT); private ChatTheme createInitialChatTheme() { return createInitialChatTheme(""); } private ChatTheme createInitialChatTheme(String title) { ChatTheme chatTheme = new ChatTheme(title); chatThemeRepository.save(chatTheme); chatThemeList.add(chatTheme); return chatTheme; } public ArrayAdapter getCitationResourceSuggestionAdapter() { if (citationResourceSuggestionAdapter == null) { citationResourceSuggestionAdapter = new AutoCompleteSuggestionArrayAdapter( this, android.R.layout.simple_dropdown_item_1line, citationResources ); } return citationResourceSuggestionAdapter; } public void renewCitationResources() { citationResources.clear(); citationResources.addAll(MainActivityHelper.createNewCitationResources(memos, citationResourceRepository)); viewProvider.resetCitationResourceSuggestionAdapterAsync(citationResources); } private void reloadChatThemeList() { chatThemeList.clear(); chatThemeList.addAll(chatThemeRepository.findAll()); } private void reloadChatThemeMenu() { if (drawerLeft == null) { drawerLeft = (NavigationView) findViewById(R.id.navigation_view); } final Menu menu = drawerLeft.getMenu(); final MenuItem item = menu.findItem(R.id.menu_group_sub); if (item != null) { SubMenu subMenu = item.getSubMenu(); if (subMenu != null) { subMenu.clear(); if (chatThemeList.size() == 0) chatTheme = createInitialChatTheme(); for (ChatTheme theme : chatThemeList) { MenuItem add = subMenu.add(R.id.menu_group_sub_child, theme.getId().intValue(), Menu.NONE, theme.getTitle()); add.setChecked(theme.getId() == chatTheme.getId()); } } } getSupportActionBar().setTitle(chatTheme.getTitle()); provideRightDrawerTitle().setText(chatTheme.getTitle()); drawerLeft.setNavigationItemSelectedListener(getOnNavigationItemSelectedListener()); } private NavigationView.OnNavigationItemSelectedListener getOnNavigationItemSelectedListener() { if (onNavigationItemSelectedListener == null ) { onNavigationItemSelectedListener = new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem item) { if (item.getGroupId() == R.id.menu_group_main) { switch (item.getItemId()) { case R.id.menu_home: // TODO 20160216 return true; case R.id.menu_settings: return true; case R.id.menu_help: // false shareToTwitter("@hackugyo%20%23Android%20"); return false; default: LogUtils.w("missing menu called. at " + item.getItemId()); return false; } } else if (item.getItemId() == R.id.menu_add_new_theme) { InputDialogFragment f = InputDialogFragment.newInstance(MainActivity.this, null, "", null); showDialogFragment(f, TAG_INPUT_NEW_THEME); return true; } else if (item.getGroupId() == R.id.menu_group_sub_child) { ChatTheme byId = chatThemeRepository.findById(item.getItemId()); LogUtils.d("id: " + item.getItemId() +", chatTheme: " + byId); if (byId != null) { chatTheme = byId; } else { chatTheme = new ChatTheme(item.getTitle().toString()); chatThemeRepository.save(chatTheme); chatThemeList.add(chatTheme); } reloadChatThemeAsync(); getDrawerManager().closeDrawers(); return true; } else { LogUtils.w("id: " + item.getItemId()); return false; } } }; } return onNavigationItemSelectedListener; } @Override public void onAlertDialogClicked(String tag, Bundle args, int which) { if (StringUtils.isSame(tag, TAG_INPUT_NEW_THEME)) { String newTheme = args.getString(InputDialogFragment.RESULT, ""); chatTheme = createInitialChatTheme(newTheme); reloadChatThemeAsync(); getDrawerManager().closeDrawers(); } else if (StringUtils.isSame(tag, TAG_CONFIRM_DELETE_THEME)) { deleteCurrentChatThemeAsync(); } else if (StringUtils.isSame(tag, TAG_CHOOSE_EDIT_MODE)) { processEditingResult(args.getLong(ITEM_ID), args.getIntegerArrayList(CHOICE_IDS), which); } else if (StringUtils.isSame(tag, TAG_EDIT_CONTENT)) { setContentAtAsync(args); } else if (StringUtils.isSame(tag, TAG_EDIT_CITATION_RESOURCE)) { setCitationResourceAt(args); } else if (StringUtils.isSame(tag, TAG_SHOW_IMAGE)) { } else { LogUtils.w("Something wrong. " + tag); } } @Override public void onAlertDialogCancelled(String tag, Bundle args) { if (StringUtils.isSame(tag, TAG_INPUT_NEW_THEME)) { // nothing to do. } else if (StringUtils.isSame(tag, TAG_CONFIRM_DELETE_THEME)) { // nothing to do. } else if (StringUtils.isSame(tag, TAG_CHOOSE_EDIT_MODE)) { // nothing to do. } else if (StringUtils.isSame(tag, TAG_EDIT_CONTENT)) { // nothing to do. } else if (StringUtils.isSame(tag, TAG_EDIT_CITATION_RESOURCE)) { // nothing to do. } else if (StringUtils.isSame(tag, TAG_SHOW_IMAGE)) { // nothing to do. } else { LogUtils.w("Something wrong. " + tag); } } private void processEditingResult(final long itemId, List<Integer> choiceIds, int which) { Memo single = findById(memos, itemId); if (single == null) { LogUtils.w("something wrong. " + itemId); return; } int index = memos.indexOf(single); switch (choiceIds.get(which)) { case 0: deleteMemoWithSomeStay(single, itemId); break; case 1: if (single.isForUrl()) { mainActivityHelper.forceReloadPreviewAsync(single); mainListAdapter.notifyItemChanged(index); } else { LogUtils.w("something wrong."); } break; case 2: shareContent(single); break; case 3: if (single.isForUrl()) { launchExternalBrowser(single.getCitationResource()); } case 4: if (!single.isForUrl()) { Bundle bundle = new Bundle(); bundle.putLong(ITEM_ID, itemId); bundle.putString(InputDialogFragment.DEFAULT_STRING, single.getMemo()); showDialogFragment(InputDialogFragment.newInstance(self, bundle, "", null), TAG_EDIT_CONTENT); } break; case 5: Bundle bundle = new Bundle(); bundle.putLong(ITEM_ID, itemId); bundle.putStringArrayList(InputDialogFragment.SUGGESTION_STRINGS, new ArrayList<String>(citationResources)); bundle.putString(InputDialogFragment.DEFAULT_STRING, single.getCitationResource()); showDialogFragment(InputDialogFragment.newInstance(self, bundle, "", null), TAG_EDIT_CITATION_RESOURCE); break; default: LogUtils.w("Something wrong. " + which); } } /** * * @param args * @return URL */ private void setContentAtAsync(Bundle args) { final long itemId = args.getLong(ITEM_ID); Memo single = findById(memos, itemId); if (single == null || single.isForUrl() || !args.containsKey(InputDialogFragment.RESULT)) { LogUtils.w("Something wrong. " + single); } else { single.setMemo(args.getString(InputDialogFragment.RESULT, "")); RxBusProvider.getInstance().post(new RequestDataSaveEvent(single)); } } /** * URLURL * @param args */ private void setCitationResourceAt(Bundle args) { final long itemId = args.getLong(ITEM_ID); Memo single = findById(memos, itemId); if (single != null && args.containsKey(InputDialogFragment.RESULT)) { boolean isForUrlCurrently = single.isForUrl(); List<CitationResource> citationResources = single.getCitationResources(); if (ArrayUtils.any(citationResources)) { citationResources.set(0, new CitationResource(args.getString(InputDialogFragment.RESULT, ""))); } else { single.addCitationResource(args.getString(InputDialogFragment.RESULT, "")); } single.setLoaded(true); if (memoRepository.save(single)) { mainListAdapter.notifyItemChanged(memos.indexOf(single)); renewCitationResources(); if (isForUrlCurrently) { mainActivityHelper.forceReloadPreviewAsync(single); } } } } /** * {@link #chatTheme} */ private void reloadChatThemeAsync() { reloadChatThemeList(); reloadChatThemeMenu(); getLoadMemoObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Action1<List<Memo>>() { @Override public void call(List<Memo> memos) { renewCitationResources(); mainActivityHelper.loadPreviewAsync(); } } ); } private void deleteCurrentChatThemeAsync() { Observable.from(memos) .subscribeOn(Schedulers.io()) // doOnNext .doOnNext(new Action1<Memo>() { @Override public void call(Memo memo) { memoRepository.delete(memo); } }) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted( new Action0() { @Override public void call() { chatThemeRepository.delete(chatTheme); getDrawerManager().closeDrawers(); ChatTheme first = chatThemeRepository.findFirst(); chatTheme = (first == null ? createInitialChatTheme() : first); reloadChatThemeAsync(); } }) .subscribe(); } private boolean editChatTheme(String newTitle) { return editChatTheme(newTitle, true); } private boolean editChatTheme(String newTitle, boolean isUndoable) { if (chatTheme == null) return false; final String currentTitle = chatTheme.getTitle(); if (StringUtils.isSame(currentTitle, newTitle)) { return false; } chatTheme.setTitle(newTitle); chatThemeRepository.save(chatTheme); reloadChatThemeList(); reloadChatThemeMenu(); if (isUndoable) { LinearLayout layout = (LinearLayout) findViewById(R.id.snackbar); Snackbar undoSnackbar = Snackbar.make(layout, R.string.toast_theme_name_edited, Snackbar.LENGTH_SHORT) .setAction(R.string.undo_theme_name_edited, new View.OnClickListener() { @Override public void onClick(View v) { editChatTheme(currentTitle, false); } }); undoSnackbar.show(); } return true; } /** * Snackbar * @param memo * @param itemId */ private void deleteMemoWithSomeStay(Memo memo, final long itemId) { memo.setRemoved(true); mainListAdapter.notifyItemChanged(memos.indexOf(memo)); final LinearLayout layout = (LinearLayout) findViewById(R.id.snackbar); //snackbar snackbar = Snackbar.make(layout, "", Snackbar.LENGTH_LONG) .setAction("", new View.OnClickListener() { @Override public void onClick(View v) { Memo single = findById(memos, itemId); if (single != null) { single.setRemoved(false); int index = memos.indexOf(single); mainListAdapter.notifyItemChanged(index); mainRecyclerView.smoothScrollToPosition(index); } } }) .setCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar snackbar, int event) { super.onDismissed(snackbar, event); Memo single = findById(memos, itemId); if (single != null) { if (single.isRemoved()) { deleteMemoAsync(single); } } } }); snackbar.show(); } private void shareContent(final Memo memo) { String content; if (memo.isForUrl() && !memo.isLoaded()) { content = memo.getCitationResource(); } else { content = StringUtils.build(memo.getMemo(), StringUtils.getCRLF(), memo.getCitationResource()); } Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, content); sendIntent.setType("text/plain"); startActivity(sendIntent); } /** * RecyclerView */ private ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() { @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (isInReorderMode) { final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; final int swipeFlags = 0; return makeMovementFlags(dragFlags, swipeFlags); } else { return makeMovementFlags(0, 0); } } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { final int fromPos = viewHolder.getAdapterPosition(); final int toPos = target.getAdapterPosition(); mainListAdapter.onItemMoved(fromPos, toPos); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) { ((ChatLikeListAdapter.ChatLikeViewHolder) viewHolder).setSelected(true); } } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); ((ChatLikeListAdapter.ChatLikeViewHolder) viewHolder).setSelected(false); } }); }
package org.objectweb.proactive.core.body; import org.objectweb.proactive.core.body.future.Future; import org.objectweb.proactive.core.body.future.FuturePool; import org.objectweb.proactive.core.body.request.BlockingRequestQueue; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.ext.security.RenegotiateSessionException; /** * <P> * An object implementing this interface is an implementation of one part * of the local view of the body of an active object. This interface define * only one part of the local view and is used to be able to change easily the * strategy of a body. Typically, after a body migrates, it is necessary to change * the its local implementation. * </P> * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 */ public interface LocalBodyStrategy { /** * Returns the future pool of this body * @return the future pool of this body */ public FuturePool getFuturePool(); /** * Returns the request queue associated to this body * @return the request queue associated to this body */ public BlockingRequestQueue getRequestQueue(); /** * Returns the reified object that body is for * The reified object is the object that has been turned active. * @return the reified object that body is for */ public Object getReifiedObject(); /** * Returns the name of this body that can be used for displaying information * @return the name of this body */ public String getName(); /** * Sends the request <code>request</code> with the future <code>future</code> to the local body * <code>body</code>. * @param methodCall the methodCall to send * @param future the future associated to the request * @param destinationBody the body the request is sent to * @exception java.io.IOException if the request cannot be sent to the destination body */ public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException, RenegotiateSessionException; ; /** * Serves the request <code>request</code> by the invoking the targeted method on the * reified object. Some specific type of request may involve special processing that * does not trigger a method on the reified object. * @param request the request to serve */ public void serve(Request request); }
package org.odk.collect.android.activities; import java.text.DecimalFormat; import java.util.List; import org.odk.collect.android.R; import org.odk.collect.android.widgets.GeoPointWidget; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Point; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; public class GeoPointActivity extends MapActivity implements LocationListener { private MapView mMapView; private TextView mLocationStatus; private MapController mMapController; private LocationManager mLocationManager; private Overlay mLocationOverlay; private GeoPoint mGeoPoint; private Location mLocation; private Button mAcceptLocation; private Button mCancelLocation; private boolean mCaptureLocation = true; private Button mShowLocation; private static double LOCATION_ACCURACY = 5; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geopoint_layout); Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION); mGeoPoint = new GeoPoint((int) (location[0] * 1E6), (int) (location[1] * 1E6)); mCaptureLocation = false; } mMapView = (MapView) findViewById(R.id.mapview); mMapController = mMapView.getController(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mMapView.setBuiltInZoomControls(true); mMapView.setSatellite(false); mMapController.setZoom(16); // make sure we have at least one non-passive gp provider before continuing List<String> providers = mLocationManager.getProviders(true); boolean gps = false; boolean network = false; for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { gps = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { network = true; } } if (!gps && !network) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT).show(); finish(); } if (mCaptureLocation) { mLocationStatus = (TextView) findViewById(R.id.location_status); mAcceptLocation = (Button) findViewById(R.id.accept_location); mAcceptLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { returnLocation(); } }); mCancelLocation = (Button) findViewById(R.id.cancel_location); mCancelLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); mLocationOverlay = new MyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mLocationOverlay); } else { mLocationOverlay = new Marker(mGeoPoint); mMapView.getOverlays().add(mLocationOverlay); ((Button) findViewById(R.id.accept_location)).setVisibility(View.GONE); ((Button) findViewById(R.id.cancel_location)).setVisibility(View.GONE); ((TextView) findViewById(R.id.location_status)).setVisibility(View.GONE); mShowLocation = ((Button) findViewById(R.id.show_location)); mShowLocation.setVisibility(View.VISIBLE); mShowLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMapController.animateTo(mGeoPoint); } }); } } private void returnLocation() { if (mLocation != null) { Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLocation.getLatitude() + " " + mLocation.getLongitude() + " " + mLocation.getAltitude() + " " + mLocation.getAccuracy()); setResult(RESULT_OK, i); } finish(); } private String truncateFloat(float f) { return new DecimalFormat("#.##").format(f); } @Override protected void onPause() { super.onPause(); mLocationManager.removeUpdates(this); if (mCaptureLocation) { ((MyLocationOverlay) mLocationOverlay).disableMyLocation(); } } @Override protected void onResume() { super.onResume(); if (mCaptureLocation) { ((MyLocationOverlay) mLocationOverlay).enableMyLocation(); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } else { // no need to update too quickly, so save batteries mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 1000, this); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 1000, this); } } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onLocationChanged(Location location) { if (mCaptureLocation) { mLocation = location; if (mLocation != null) { mLocationStatus.setText(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateFloat(mLocation.getAccuracy()))); mGeoPoint = new GeoPoint((int) (mLocation.getLatitude() * 1E6), (int) (mLocation.getLongitude() * 1E6)); mMapController.animateTo(mGeoPoint); if (mLocation.getAccuracy() <= LOCATION_ACCURACY) { returnLocation(); } } } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } class Marker extends Overlay { GeoPoint gp = null; public Marker(GeoPoint gp) { super(); this.gp = gp; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); Point screenPoint = new Point(); mMapView.getProjection().toPixels(gp, screenPoint); canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.blue_dot), screenPoint.x, screenPoint.y - 8, null); // -8 as image is 16px high } } }
import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * WXMLParser is a helper class for using JAXB to parse 1) a XML * record file into a Java object or 2) a Java object into a XML * record file. * * Here is an example of getting an object from a XML record file: * MyClass o = WXMLParser.PULL ( "MyXML.xml", MyClass.class ); * * And, this is an example of extracting a Java object onto a XML * file: * XMLParser.PUSH ( "MyNewRecord.xml", myObject ); * * @author Wonho Lim (wono@live.com) */ public class WXMLParser { // Prevents being initialized. private WXMLParser(){} /** * @return <T> any type of object holding record pulled from xml */ public static <T> T PULL ( String xmlPath, Class<T> c ) { try { return c.cast( JAXBContext.newInstance(c) .createUnmarshaller() .unmarshal(new File(RecordPath.GET(xmlPath)) ); } catch ( JAXBException e ) { e.printStackTrace(); } return null; } /** * @param <String> xml record file path including its extention * @param <T> any type of record object to push into a xml file */ public static <T> void PUSH ( String xmlPath, T o ) { try { Marshaller m = JAXBContext.newInstance(o.getClass()) .createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(o, new File(RecordPath.GET(xmlPath))); } catch ( JAXBException e ) { e.printStackTrace(); } } }
package me.devsaki.hentoid.database; import android.util.SparseIntArray; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.paging.PagedList; import com.annimon.stream.function.Consumer; import org.apache.commons.lang3.tuple.ImmutablePair; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import io.reactivex.Single; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ErrorRecord; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.GroupItem; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.database.domains.QueueRecord; import me.devsaki.hentoid.database.domains.SiteBookmark; import me.devsaki.hentoid.database.domains.SiteHistory; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.StatusContent; import me.devsaki.hentoid.util.ContentHelper; public interface CollectionDAO { // CONTENT // Low-level operations LiveData<PagedList<Content>> selectNoContent(); @Nullable Content selectContent(long id); List<Content> selectContent(long[] id); @Nullable Content selectContentByStorageUri(@NonNull final String folderUri, boolean onlyFlagged); @Nullable Content selectContentBySourceAndUrl(@NonNull Site site, @NonNull String contentUrl, @NonNull String coverUrl); List<Content> searchTitlesWith(@NonNull final String word, int[] contentStatusCodes); long insertContent(@NonNull final Content content); void updateContentStatus(@NonNull final StatusContent updateFrom, @NonNull final StatusContent updateTo); void deleteContent(@NonNull final Content content); List<ErrorRecord> selectErrorRecordByContentId(long contentId); void insertErrorRecord(@NonNull final ErrorRecord record); void deleteErrorRecords(long contentId); void clearDownloadParams(long contentId); void shuffleContent(); // MASS OPERATIONS // Internal library (i.e. managed in the Hentoid folder) long countAllInternalBooks(boolean favsOnly); List<Content> selectAllInternalBooks(boolean favsOnly); void flagAllInternalBooks(); void deleteAllInternalBooks(boolean resetRemainingImagesStatus); // Queued books void flagAllErrorBooksWithJson(); long countAllQueueBooks(); List<Content> selectAllQueueBooks(); void deleteAllQueuedBooks(); // Flagging void deleteAllFlaggedBooks(boolean resetRemainingImagesStatus); // External library long countAllExternalBooks(); void deleteAllExternalBooks(); // Groups List<Group> selectGroups(long[] groupIds); LiveData<List<Group>> selectGroups(int grouping, @Nullable String query, int orderField, boolean orderDesc, int artistGroupVisibility, boolean groupFavouritesOnly); List<Group> selectGroups(int grouping); @Nullable Group selectGroup(long groupId); @Nullable Group selectGroupByName(int grouping, @NonNull final String name); long countGroupsFor(Grouping grouping); LiveData<Integer> countLiveGroupsFor(@NonNull final Grouping grouping); long insertGroup(Group group); void deleteGroup(long groupId); void deleteAllGroups(Grouping grouping); void flagAllGroups(Grouping grouping); void deleteAllFlaggedGroups(); long insertGroupItem(GroupItem item); List<GroupItem> selectGroupItems(long contentId, Grouping grouping); void deleteGroupItems(List<Long> groupItemIds); // High-level queries (internal and external locations) List<Content> selectStoredContent(boolean nonFavouriteOnly, boolean includeQueued, int orderField, boolean orderDesc); long countStoredContent(boolean nonFavouriteOnly, boolean includeQueued); List<Content> selectContentWithUnhashedCovers(); long countContentWithUnhashedCovers(); void streamStoredContent(boolean nonFavouritesOnly, boolean includeQueued, int orderField, boolean orderDesc, Consumer<Content> consumer); Single<List<Long>> selectRecentBookIds(long groupId, int orderField, boolean orderDesc, boolean bookFavouritesOnly, boolean pageFavouritesOnly, boolean bookCompletedOnly, boolean bookNotCompletedOnly); Single<List<Long>> searchBookIds(String query, long groupId, List<Attribute> metadata, int orderField, boolean orderDesc, boolean bookFavouritesOnly, boolean pageFavouritesOnly, boolean bookCompletedOnly, boolean bookNotCompletedOnly); Single<List<Long>> searchBookIdsUniversal(String query, long groupId, int orderField, boolean orderDesc, boolean bookFavouritesOnly, boolean pageFavouritesOnly, boolean bookCompletedOnly, boolean bookNotCompletedOnly); LiveData<PagedList<Content>> selectRecentBooks(long groupId, int orderField, boolean orderDesc, boolean favouritesOnly, boolean loadAll, boolean bookCompletedOnly, boolean bookNotCompletedOnly); LiveData<PagedList<Content>> searchBooks(String query, long groupId, List<Attribute> metadata, int orderField, boolean orderDesc, boolean favouritesOnly, boolean loadAll, boolean bookCompletedOnly, boolean bookNotCompletedOnly); LiveData<PagedList<Content>> searchBooksUniversal(String query, long groupId, int orderField, boolean orderDesc, boolean favouritesOnly, boolean loadAll, boolean bookCompletedOnly, boolean bookNotCompletedOnly); LiveData<List<Content>> selectErrorContent(); List<Content> selectErrorContentList(); LiveData<Integer> countBooks(String query, long groupId, List<Attribute> metadata, boolean favouritesOnly, boolean bookCompletedOnly, boolean bookNotCompletedOnly); LiveData<Integer> countAllBooks(); // IMAGEFILES void insertImageFile(@NonNull ImageFile img); void insertImageFiles(@NonNull List<ImageFile> imgs); void replaceImageList(long contentId, @NonNull final List<ImageFile> newList); void updateImageContentStatus(long contentId, StatusContent updateFrom, @NonNull StatusContent updateTo); void updateImageFileStatusParamsMimeTypeUriSize(@NonNull ImageFile image); void deleteImageFiles(@NonNull List<ImageFile> imgs); ImageFile selectImageFile(long id); LiveData<List<ImageFile>> selectDownloadedImagesFromContent(long id); Map<StatusContent, ImmutablePair<Integer, Long>> countProcessedImagesById(long contentId); Map<Site, ImmutablePair<Integer, Long>> selectPrimaryMemoryUsagePerSource(); Map<Site, ImmutablePair<Integer, Long>> selectExternalMemoryUsagePerSource(); // QUEUE List<QueueRecord> selectQueue(); List<QueueRecord> selectQueue(String query); LiveData<List<QueueRecord>> selectQueueLive(); LiveData<List<QueueRecord>> selectQueueLive(String query); void addContentToQueue(@NonNull final Content content, StatusContent targetImageStatus, @ContentHelper.QueuePosition int position, boolean isQueueActive); void updateQueue(@NonNull List<QueueRecord> queue); void deleteQueue(@NonNull Content content); void deleteQueue(int index); // ATTRIBUTES Single<AttributeQueryResult> selectAttributeMasterDataPaged( @NonNull List<AttributeType> types, String filter, List<Attribute> attrs, boolean filterFavourites, boolean bookCompletedOnly, boolean bookNotCompletedOnly, int page, int booksPerPage, int orderStyle); Single<SparseIntArray> countAttributesPerType(List<Attribute> filter); // SITE HISTORY SiteHistory selectHistory(@NonNull Site s); void insertSiteHistory(@NonNull Site site, @NonNull String url); // BOOKMARKS long countAllBookmarks(); List<SiteBookmark> selectAllBookmarks(); List<SiteBookmark> selectBookmarks(@NonNull Site s); long insertBookmark(@NonNull SiteBookmark bookmark); void insertBookmarks(@NonNull List<SiteBookmark> bookmarks); void deleteBookmark(long bookmarkId); void deleteAllBookmarks(); // RESOURCES void cleanup(); long getDbSizeBytes(); // ONE-TIME USE QUERIES (MIGRATION & CLEANUP) Single<List<Long>> selectOldStoredBookIds(); long countOldStoredContent(); // RESULTS STRUCTURES // This is a dumb struct class, nothing more @SuppressWarnings("squid:S1104") class AttributeQueryResult { public List<Attribute> attributes = new ArrayList<>(); public long totalSelectedAttributes = 0; } }
package sopc2dts.parsers.sopcinfo; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import sopc2dts.Logger; import sopc2dts.Logger.LogLevel; import sopc2dts.lib.Connection; import sopc2dts.lib.AvalonSystem.SystemDataType; import sopc2dts.lib.components.Interface; public class SopcInfoConnection extends SopcInfoElementWithParams { String currTag; private String startModuleName; private Interface masterInterface; private String endModuleName; private Interface slaveInterface; private SopcInfoSystemLoader sys; private String kind; public SopcInfoConnection(ContentHandler p, XMLReader xr, String k, SopcInfoSystemLoader s) { super(p, xr, null); sys = s; kind = k; } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { currTag = localName; super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if(localName.equalsIgnoreCase(currTag)) { currTag = null; } else { if(localName.equalsIgnoreCase(getElementName()) && (kind!=null)) { Connection bc = null; if(kind.equalsIgnoreCase("avalon") || kind.equalsIgnoreCase("avalon_tristate")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.MEMORY_MAPPED); bc.setConnValue(Integer.decode(getParamValue("baseAddress"))); } else if(kind.equalsIgnoreCase("tristate_conduit")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.MEMORY_MAPPED); bc.setConnValue(0); } else if(kind.equalsIgnoreCase("clock")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.CLOCK); bc.setConnValue(bc.getMasterInterface().getInterfaceValue()); } else if(kind.equalsIgnoreCase("interrupt")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.INTERRUPT); bc.setConnValue(Integer.decode(getParamValue("irqNumber"))); } else if(kind.equalsIgnoreCase("avalon_streaming")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.STREAMING); } else if(kind.equalsIgnoreCase("conduit")) { bc = new Connection(masterInterface, slaveInterface, SystemDataType.CONDUIT); } else if(kind.equalsIgnoreCase("reset")) { //Explicitly ignore resets. bc = null; } else { Logger.logln("Unhandled connection of kind: " + kind,LogLevel.DEBUG); } //Ignore other connections for now... if(bc!=null) { sys.vConnections.add(bc); } } super.endElement(uri, localName, qName); } } public void characters(char[] ch, int start, int length) throws SAXException { if(currTag!=null) { if(currTag.equalsIgnoreCase("startModule")) { startModuleName = String.copyValueOf(ch, start, length); } else if(currTag.equalsIgnoreCase("startConnectionPoint")) { String startInterfaceName = String.copyValueOf(ch, start, length); masterInterface = sys.getCurrSystem().getComponentByName(startModuleName).getInterfaceByName(startInterfaceName); } else if(currTag.equalsIgnoreCase("endModule")) { endModuleName = String.copyValueOf(ch, start, length); } else if(currTag.equalsIgnoreCase("endConnectionPoint")) { String endInterfaceName = String.copyValueOf(ch, start, length); slaveInterface = sys.getCurrSystem().getComponentByName(endModuleName).getInterfaceByName(endInterfaceName); } } } @Override public String getElementName() { return "connection"; } }
package ru.furry.furview2.drivers.e621; import android.content.Context; import android.graphics.Bitmap; import android.os.AsyncTask; import android.util.Log; import android.view.View; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.imageaware.ImageAware; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import ru.furry.furview2.database.FurryDatabase; import ru.furry.furview2.drivers.Driver; import ru.furry.furview2.images.FurImage; import ru.furry.furview2.images.FurImageBuilder; import ru.furry.furview2.images.Rating; import ru.furry.furview2.images.RemoteFurImage; import ru.furry.furview2.system.AsyncHandlerUI; import ru.furry.furview2.system.Files; import ru.furry.furview2.system.ProxiedHTTPSLoader; import ru.furry.furview2.system.Utils; import static ru.furry.furview2.drivers.DriverUtils.checkPathStructureForImages; public class DriverE621 extends Driver { private static final String SEARCH_PATH = "https://e621.net/post/index.xml"; private static final String CHARSET = "UTF-8"; private static final int SEARCH_LIMIT = 95; private final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); private final DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd kk:mm:ss Z yyyy").withLocale(new Locale("en", "US")); private final static ImageLoader imageLoader = ImageLoader.getInstance(); private final static DisplayImageOptions displayOptions = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .build(); private final DisplayImageOptions downloadOptions = new DisplayImageOptions.Builder() .cacheOnDisk(true) .build(); private String permanentStorage; private boolean hasImages = true; private boolean isSfw; private int currentPage = 0; private String searchQuery; @Override public void init(String permanentStorage, Context context) { this.permanentStorage = permanentStorage; checkPathStructureForImages(permanentStorage); } // UTILITY private Rating makeRating(String sRating) { Rating rating; switch (sRating) { case "s": rating = Rating.SAFE; break; case "q": rating = Rating.QUESTIONABLE; break; case "e": rating = Rating.EXPLICIT; break; default: rating = Rating.NA; break; } return rating; } private URL makeURL(String searchURL, String searchQuery, int page, int limit) throws MalformedURLException { URL url = null; if (isSfw && !searchQuery.contains("rating:safe") && !searchQuery.contains("rating:s")) { searchQuery += " rating:s"; } try { String query = String.format("%s?tags=%s&page=%s&limit=%s", searchURL, URLEncoder.encode(searchQuery, CHARSET), page, limit); url = new URL(query); } catch (UnsupportedEncodingException e) { Utils.printError(e); } return url; } private static FurImage remoteFurImagetoFurImageE621(RemoteFurImageE621 remoteImage) { return new FurImageBuilder() .makeFromRemoteFurImage(remoteImage) .setScore(remoteImage.getScore()) .setAuthor(remoteImage.getAuthor()) .setCreatedAt(remoteImage.getCreatedAt()) .setSources(remoteImage.getSources()) .setTags(remoteImage.getTags()) .setArtists(remoteImage.getArtists()) .setMd5(remoteImage.getMd5()) .setFileSize(remoteImage.getFileSize()) .setFileWidth(remoteImage.getFileWidth()) .setFileHeight(remoteImage.getFileHeight()) .setDownloadedAt(new DateTime()) .setPageUrl("https://e621.net/post/show/" + remoteImage.getIdE621()) .setFilePath(remoteImage.getFileUrl()) .createFurImage(); } // LOGIC class ReadingImages extends AsyncTask<Utils.Tuple<URL, AsyncHandlerUI<RemoteFurImage>>, Void, List<RemoteFurImageE621>> { private AsyncHandlerUI<RemoteFurImage> handler; @Override protected List<RemoteFurImageE621> doInBackground(Utils.Tuple<URL, AsyncHandlerUI<RemoteFurImage>>... tuples) { Log.d("fgsfds", "Starting retrieving remote images..."); URL queryPage = tuples[0].x; HttpsURLConnection connection; try { connection = ProxiedHTTPSLoader.openPage(queryPage); } catch (IOException e) { Utils.printError(e); throw new RuntimeException(e); } handler = tuples[0].y; Document doc = null; try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(connection.getInputStream()); } catch (ParserConfigurationException | IOException | SAXException e) { Utils.printError(e); } doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("post"); ArrayList<RemoteFurImageE621> images = new ArrayList<>(SEARCH_LIMIT); for (int postNumber = 0; postNumber < nList.getLength(); postNumber++) { Node post = nList.item(postNumber); Element element = (Element) post; // Let's ignore swf and webm if (element.getAttribute("file_ext").equals("webm") || element.getAttribute("file_ext").equals("swf")) continue; else images.add(new RemoteFurImageE621Builder() .setSearchQuery(searchQuery) .setDescription(deleteTags(element.getAttribute("description"))) .setScore(Integer.parseInt(element.getAttribute("score"))) .setRating(makeRating(element.getAttribute("rating"))) .setFileUrl(element.getAttribute("file_url")) .setPreviewUrl(element.getAttribute("preview_url")) .setFileExt(element.getAttribute("file_ext")) .setPageUrl(null) .setIdE926(Integer.parseInt(element.getAttribute("id"))) .setAuthor(element.getAttribute("author")) .setCreatedAt(formatter.parseDateTime(element.getAttribute("created_at").replace(" 00", " 24").substring(4))) .setSources(Arrays.asList(element.getAttribute("sources").replace("[&quot;", "").replace("&quot;]", "").split("&quot;,&quot;"))) .setTags(Arrays.asList(element.getAttribute("tags").split(" "))) .setArtists(Arrays.asList(element.getAttribute("artist").replace("[&quot;", "").replace("&quot;]", "").split("&quot;,&quot;"))) .setMd5(new BigInteger(element.getAttribute("md5"), 36)) .setFileSize(Integer.parseInt(element.getAttribute("file_size"))) .setFileWidth(Integer.parseInt(element.getAttribute("width"))) .setFileHeight(Integer.parseInt(element.getAttribute("height"))) .createRemoteFurImageE926()); } return images; } @Override protected void onPostExecute(List<RemoteFurImageE621> images) { if (images.size() == 0) { hasImages = false; } handler.retrieve(images); handler.unblockUI(); } } protected String deleteTags(String incomingString){ Pattern pattern = Pattern.compile("\\[.*?\\]|<.*?>"); Matcher matcher = pattern.matcher(incomingString); return matcher.replaceAll(""); } private void startReadingRemoteImages(URL queryPage, AsyncHandlerUI<RemoteFurImage> remoteImagesHandler) { remoteImagesHandler.blockUI(); new ReadingImages().execute(new Utils.Tuple<URL, AsyncHandlerUI<RemoteFurImage>>(queryPage, remoteImagesHandler)); } @Override public void search(String searchQuery, AsyncHandlerUI<RemoteFurImage> remoteImagesHandler) { currentPage = 0; this.searchQuery = searchQuery; getNext(remoteImagesHandler); } @Override public void getNext(AsyncHandlerUI<RemoteFurImage> remoteImagesHandler) { currentPage += 1; URL query = null; try { query = makeURL(SEARCH_PATH, searchQuery, currentPage, SEARCH_LIMIT); } catch (IOException e) { Utils.printError(e); } startReadingRemoteImages(query, remoteImagesHandler); } @Override public boolean hasNext() { return hasImages; } @Override public void downloadFurImage(List<RemoteFurImage> images, List<AsyncHandlerUI<FurImage>> furImagesHandlers) { for (int i = 0; i < images.size(); i++) { furImagesHandlers.get(i).retrieve(new ArrayList<>(Arrays.asList(remoteFurImagetoFurImageE621((RemoteFurImageE621)images.get(i))))); } } @Override public void downloadImageFile(FurImage image, ImageAware listener, ImageLoadingListener loadingListener) { Log.d("fgsfds", "downloading image: " + image.getFileUrl()); imageLoader.displayImage(image.getFileUrl(), listener, displayOptions, loadingListener); } @Override public void downloadPreviewFile(List<? extends RemoteFurImage> images, List<? extends ImageAware> listeners, List<ImageLoadingListener> loadingListeners) { for (int i = 0; i < images.size(); i++) { imageLoader.displayImage(images.get(i).getPreviewUrl(), listeners.get(i), displayOptions, loadingListeners.get(i)); } } @Override public void saveToDBandStorage(FurImage image, FurryDatabase database) { image.setFilePath(String.format("%s/%s/", permanentStorage, Files.IMAGES) + image.getMd5() + "." + image.getFileExt()); database.create(image); final String imagePath = image.getFilePath(); Log.d("fgsfds", "saving image to " + imagePath); imageLoader.loadImage(image.getFileUrl(), downloadOptions, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { FileOutputStream out = null; try { out = new FileOutputStream(imagePath); loadedImage.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (Exception e) { Utils.printError(e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { Utils.printError(e); } } } }); } /** * Deletes image only from storage, not from database * * @param image * @param database */ @Override public void deleteFromDBandStorage(FurImage image, FurryDatabase database) { database.deleteByMd5(image.getMd5()); File file = new File(image.getFilePath()); file.delete(); } @Override public void setSfw(boolean sfw) { isSfw = sfw; } }
package de.m0ep.uni.ma; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.RDF2Go; import org.ontoware.rdf2go.Reasoning; import org.ontoware.rdf2go.model.Model; import org.ontoware.rdf2go.model.Statement; import org.ontoware.rdf2go.model.impl.NotifyingModelLayer; import org.ontoware.rdf2go.model.node.URI; import org.ontoware.rdf2go.model.node.Variable; import org.ontoware.rdf2go.util.RDFTool; import de.m0ep.uni.ma.rdf.sioc.Post; public class PostCRUD extends JFrame { private static final long serialVersionUID = 5598704821953402509L; private static final String NS = "http://m0ep.de/rdf/"; private NotifyingModelLayer model; private JButton newPost; private JButton deletePost; private JList<String> list; private ListModel<String> listModel; private JTree treePane; private DefaultTreeModel treeModel; public PostCRUD( final Model model ) { this.model = new NotifyingModelLayer( model ); setLayout( new BorderLayout() ); setSize( 500, 500 ); JPanel buttonGroup = new JPanel(); buttonGroup.setLayout( new FlowLayout( FlowLayout.CENTER ) ); newPost = new JButton( "Create Post" ); newPost.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { long id = new Date().getTime(); Post p = new Post( PostCRUD.this.model, NS + id, true ); p.setSIOCTitle( model.createPlainLiteral( "test titel" ) ); p.addSIOCDate( model.createPlainLiteral( RDFTool .dateTime2String( new Date() ) ) ); } }); buttonGroup.add( newPost ); deletePost = new JButton( "Delete Post" ); deletePost.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { int i = list.getSelectedIndex(); if( 0 <= i ) { String uri = listModel.getElementAt( i ); Post.deleteAllProperties( PostCRUD.this.model, PostCRUD.this.model.createURI( uri ) ); } } } ); buttonGroup.add( deletePost ); add( buttonGroup, BorderLayout.SOUTH ); listModel = new PostListModel( this.model ); list = new JList<String>( listModel ); list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); list.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged( ListSelectionEvent e ) { Model m = PostCRUD.this.model; String uri = list.getSelectedValue(); if( null == uri ) { treeModel.setRoot( null ); return; } TreeNode root = new DefaultMutableTreeNode( uri ); treeModel.setRoot( root ); ClosableIterator<Statement> iter = m.findStatements( m.createURI( uri ), Variable.ANY, Variable.ANY ); while ( iter.hasNext() ) { Statement statement = (Statement) iter.next(); TreeNode child = null; String childName = getLastElementOfUri( statement .getPredicate().toString() ); @SuppressWarnings( "unchecked" ) Enumeration<TreeNode> children = root.children(); while ( children.hasMoreElements() ) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) children .nextElement(); if( node.getUserObject().equals( childName ) ) { child = node; break; } } if( null == child ) { child = new DefaultMutableTreeNode( childName ); treeModel.insertNodeInto( (MutableTreeNode) child, (MutableTreeNode) root, root.getChildCount() ); } MutableTreeNode leaf = new DefaultMutableTreeNode( statement.getObject().toString() ); treeModel.insertNodeInto( leaf, (MutableTreeNode) child, child.getChildCount() ); } iter.close(); for ( int i = 0; i < treePane.getRowCount(); i++ ) { treePane.expandRow( i ); } } } ); treeModel = new DefaultTreeModel( null ); treePane = new JTree( treeModel ); treePane.setMinimumSize( new Dimension() ); JSplitPane split = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, new JScrollPane( list ), new JScrollPane( treePane ) ); add( split, BorderLayout.CENTER ); } /** * @param args */ public static void main( String[] args ) { Model model = RDF2Go.getModelFactory().createModel( Reasoning.rdfs ); model.open(); new PostCRUD( model ).setVisible( true ); } public String getLastElementOfUri( String uri ) { // search for fragment int index = uri.lastIndexOf( ' if( -1 == index ) { // get last element of the path if no fragment is present index = uri.lastIndexOf( '/' ); } return uri.substring( index + 1 ); } private List<URI> getAllManagedUris( List<URI> uris, Class<?> clazz ) { if( null == uris ) uris = new ArrayList<URI>(); if( null == clazz ) return uris; try { Field field = clazz.getField( "MANAGED_URIS" ); int modifier = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; if( 0 != ( field.getModifiers() & modifier ) ) { field.setAccessible( true ); URI[] managed_uris = (URI[]) field.get( null ); for ( URI uri : managed_uris ) { uris.add( uri ); } } } catch ( NoSuchFieldException e ) { // ignore it } catch ( SecurityException e ) { // ignore it } catch ( IllegalArgumentException e ) { // ignore it } catch ( IllegalAccessException e ) { // ignore it } // iterate over all superclasses Class<?> superClass = clazz.getSuperclass(); return getAllManagedUris( uris, superClass ); } }
package tw.idv.laiis.ezretrofitdemo; import android.app.Application; import java.net.CookieManager; import tw.idv.laiis.ezretrofit.EZRetrofit; import tw.idv.laiis.ezretrofit.RetrofitConf; public class EZRetrofitApp extends Application { private static volatile EZRetrofitApp sEZRetrofitApp; private static EZRetrofitApp getEZRetrofitApp() { return sEZRetrofitApp; } @Override public void onCreate() { super.onCreate(); sEZRetrofitApp = this; initialEZRetrofit(); } public static void initialEZRetrofit() { // I want to use this pattern to call api. EZRetrofit.initial(new RetrofitConf.Builder(getEZRetrofitApp()) .setCookieHandler(CookieManager.getDefault()) .timeout(15L) .baseUrls(JsonWebservice.class, "http://data.taipei/") .build()); } }
package org.commcare.dalvik.activities; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.adapters.EntityListAdapter; import org.commcare.android.fragments.ContainerFragment; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.SaveSessionCommCareActivity; import org.commcare.android.logic.DetailCalloutListenerDefaultImpl; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.models.Entity; import org.commcare.android.models.NodeEntityFactory; import org.commcare.android.tasks.EntityLoaderListener; import org.commcare.android.tasks.EntityLoaderTask; import org.commcare.android.util.AndroidInstanceInitializer; import org.commcare.android.util.DetailCalloutListener; import org.commcare.android.util.SerializationUtil; import org.commcare.android.view.EntityView; import org.commcare.android.view.TabbedDetailView; import org.commcare.android.view.ViewUtil; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.utils.EntityDetailUtils; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.DialogChoiceItem; import org.commcare.dalvik.dialogs.PaneledChoiceDialog; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.dalvik.preferences.DeveloperPreferences; import org.commcare.session.CommCareSession; import org.commcare.session.SessionFrame; import org.commcare.suite.model.Action; import org.commcare.suite.model.Callout; import org.commcare.suite.model.CalloutData; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.commcare.suite.model.SessionDatum; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.views.media.AudioController; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /** * @author ctsims */ public class EntitySelectActivity extends SaveSessionCommCareActivity implements TextWatcher, EntityLoaderListener, OnItemClickListener, DetailCalloutListener { private static final String TAG = EntitySelectActivity.class.getSimpleName(); private CommCareSession session; private AndroidSessionWrapper asw; public static final String EXTRA_ENTITY_KEY = "esa_entity_key"; private static final String EXTRA_IS_MAP = "is_map"; private static final int CONFIRM_SELECT = 0; private static final int MAP_SELECT = 2; private static final int BARCODE_FETCH = 1; private static final int CALLOUT = 3; private static final int MENU_SORT = Menu.FIRST + 1; private static final int MENU_MAP = Menu.FIRST + 2; private static final int MENU_ACTION = Menu.FIRST + 3; private EditText searchbox; private TextView searchResultStatus; private EntityListAdapter adapter; private LinearLayout header; private ImageButton barcodeButton; private SearchView searchView; private MenuItem searchItem; private SessionDatum selectDatum; private boolean mResultIsMap = false; private boolean mMappingEnabled = false; // Is the detail screen for showing entities, without option for moving // forward on to form manipulation? private boolean mViewMode = false; // No detail confirm screen is defined for this entity select private boolean mNoDetailMode = false; private EntityLoaderTask loader; private boolean inAwesomeMode = false; private FrameLayout rightFrame; private TabbedDetailView detailView; private Intent selectedIntent = null; private String filterString = ""; private Detail shortSelect; private DataSetObserver mListStateObserver; private OnClickListener barcodeScanOnClickListener; private boolean resuming = false; private boolean startOther = false; private boolean rightFrameSetup = false; private NodeEntityFactory factory; private Timer myTimer; private final Object timerLock = new Object(); private boolean cancelled; private ContainerFragment<EntityListAdapter> containerFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.createDataSetObserver(); if (savedInstanceState != null) { mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false); } asw = CommCareApplication._().getCurrentSessionWrapper(); session = asw.getSession(); if (session.getCommand() == null) { // session ended, avoid (session dependent) setup because session // management will exit the activity in onResume return; } selectDatum = session.getNeededDatum(); shortSelect = session.getDetail(selectDatum.getShortDetail()); mNoDetailMode = selectDatum.getLongDetail() == null; if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) { //See if we're on a big 'ol screen. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setupLandscapeDualPaneView(); } else { boolean isOrientationChange = savedInstanceState != null; setupPortraitDualPaneView(isOrientationChange); } } else { setContentView(R.layout.entity_select_layout); } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); view.setOnItemClickListener(this); setupDivider(view); setupToolbar(view); } private void setupLandscapeDualPaneView() { //Inflate and set up the normal view for now. setContentView(R.layout.screen_compound_select); View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane)); inAwesomeMode = true; rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane); TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt); //use the old method here because some Android versions don't like Spannables for titles message.setText(Localization.get("select.placeholder.message", new String[]{Localization.get("cchq.case")})); } private void setupPortraitDualPaneView(boolean isOrientationChange) { setContentView(R.layout.entity_select_layout); //So we're not in landscape mode anymore, but were before. If we had something selected, we //need to go to the detail screen instead. if (isOrientationChange) { Intent intent = this.getIntent(); TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (selectedRef != null) { // remove the reference from this intent, ensuring we // don't re-launch the detail for an entity even after // it being de-selected. intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE); // attach the selected entity to the new detail intent // we're launching Intent detailIntent = EntityDetailUtils.getDetailIntent(getApplicationContext(), selectedRef, null, selectDatum, asw); startOther = true; startActivityForResult(detailIntent, CONFIRM_SELECT); } } } private void setupToolbar(ListView view) { TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label); //use the old method here because some Android versions don't like Spannables for titles searchLabel.setText(Localization.get("select.search.label")); searchLabel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // get the focus on the edittext by performing click searchbox.performClick(); // then force the keyboard up since performClick() apparently isn't enough on some devices InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); // only will trigger it if no physical keyboard is open inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT); } }); searchbox = (EditText)findViewById(R.id.searchbox); searchbox.setMaxLines(3); searchbox.setHorizontallyScrolling(false); searchResultStatus = (TextView)findViewById(R.id.no_search_results); header = (LinearLayout)findViewById(R.id.entity_select_header); mViewMode = session.isViewCommand(session.getCommand()); barcodeButton = (ImageButton)findViewById(R.id.barcodeButton); Callout callout = shortSelect.getCallout(); if (callout == null) { barcodeScanOnClickListener = makeBarcodeClickListener(); } else { barcodeScanOnClickListener = makeCalloutClickListener(callout); } barcodeButton.setOnClickListener(barcodeScanOnClickListener); searchbox.addTextChangedListener(this); searchbox.requestFocus(); persistAdapterState(view); restoreLastQueryString(); if (!isUsingActionBar()) { searchbox.setText(lastQueryString); } } private void persistAdapterState(ListView view) { FragmentManager fm = this.getSupportFragmentManager(); containerFragment = (ContainerFragment)fm.findFragmentByTag("entity-adapter"); // stateHolder and its previous state aren't null if the activity is // being created due to an orientation change. if (containerFragment == null) { containerFragment = new ContainerFragment<>(); fm.beginTransaction().add(containerFragment, "entity-adapter").commit(); } else { adapter = containerFragment.getData(); // on orientation change if (adapter != null) { view.setAdapter(adapter); setupDivider(view); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); } } } /** * @return A click listener that launches QR code scanner */ private View.OnClickListener makeBarcodeClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent("com.google.zxing.client.android.SCAN"); try { EntitySelectActivity.this.startActivityForResult(i, BARCODE_FETCH); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No barcode reader available! You can install one " + "from the android market.", Toast.LENGTH_LONG).show(); } } }; } /** * Build click listener from callout: set button's image, get intent action, * and copy extras into intent. * * @param callout contains intent action and extras, and sometimes button image * @return click listener that launches the callout's activity with the * associated callout extras */ private View.OnClickListener makeCalloutClickListener(Callout callout) { final CalloutData calloutData = callout.getRawCalloutData(); if (calloutData.getImage() != null) { setupImageLayout(barcodeButton, calloutData.getImage()); } final Intent i = new Intent(calloutData.getActionName()); for (Map.Entry<String, String> keyValue : calloutData.getExtras().entrySet()) { i.putExtra(keyValue.getKey(), keyValue.getValue()); } return new View.OnClickListener() { @Override public void onClick(View v) { try { EntitySelectActivity.this.startActivityForResult(i, CALLOUT); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No application found for action: " + i.getAction(), Toast.LENGTH_LONG).show(); } } }; } /** * Updates the ImageView layout that is passed in, based on the * new id and source */ private void setupImageLayout(View layout, final String imagePath) { ImageView iv = (ImageView)layout; Bitmap b; if (!imagePath.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(imagePath).getStream()); if (b == null) { // Input stream could not be used to derive bitmap, so // showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException | InvalidReferenceException ex) { ex.printStackTrace(); // Error loading image, default to folder button iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { // no image passed in, draw a white background iv.setImageDrawable(getResources().getDrawable(R.color.white)); } } private void createDataSetObserver() { mListStateObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); //update the search results box String query = getSearchText().toString(); if (!"".equals(query)) { searchResultStatus.setText(Localization.get("select.search.status", new String[]{ "" + adapter.getCount(true, false), "" + adapter.getCount(true, true), query })); searchResultStatus.setVisibility(View.VISIBLE); } else { searchResultStatus.setVisibility(View.GONE); } } }; } @Override protected boolean isTopNavEnabled() { return true; } @Override public String getActivityTitle() { return null; } @Override protected void onResume() { super.onResume(); //Don't go through making the whole thing if we're finishing anyway. if (this.isFinishing() || startOther) { return; } if (adapter != null) { adapter.registerDataSetObserver(mListStateObserver); } if (!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) { TreeReference entity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY)); if (entity != null) { if (inAwesomeMode) { if (adapter != null) { displayReferenceAwesome(entity, adapter.getPosition(entity)); updateSelectedItem(entity, true); } } else { //Once we've done the initial dispatch, we don't want to end up triggering it later. this.getIntent().removeExtra(EXTRA_ENTITY_KEY); Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), entity, null, selectDatum, asw); if (adapter != null) { i.putExtra("entity_detail_index", adapter.getPosition(entity)); i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID, selectDatum.getShortDetail()); } startActivityForResult(i, CONFIRM_SELECT); return; } } } refreshView(); } /** * Get form list from database and insert into view. */ private void refreshView() { try { //TODO: Get ec into these text's String[] headers = new String[shortSelect.getFields().length]; for (int i = 0; i < headers.length; ++i) { headers[i] = shortSelect.getFields()[i].getHeader().evaluate(); if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) { this.mMappingEnabled = true; } } header.removeAllViews(); // only add headers if we're not using grid mode if (!shortSelect.usesGridView()) { //Hm, sadly we possibly need to rebuild this each time. EntityView v = EntityView.buildHeadersEntityView(this, shortSelect, headers); header.addView(v); } if (adapter == null && loader == null && !EntityLoaderTask.attachToActivity(this)) { EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext()); theloader.attachListener(this); theloader.execute(selectDatum.getNodeset()); } else { startTimer(); } } catch (RuntimeException re) { createErrorDialog(re.getMessage(), true); } } @Override protected void onPause() { super.onPause(); stopTimer(); if (adapter != null) { adapter.unregisterDataSetObserver(mListStateObserver); } } @Override protected void onStop() { super.onStop(); stopTimer(); saveLastQueryString(); } @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { if (id == EntityListAdapter.SPECIAL_ACTION) { triggerDetailAction(); return; } TreeReference selection = adapter.getItem(position); if (CommCarePreferences.isEntityDetailLoggingEnabled()) { Logger.log(EntityDetailActivity.class.getSimpleName(), selectDatum.getLongDetail()); } if (inAwesomeMode) { displayReferenceAwesome(selection, position); updateSelectedItem(selection, false); } else { Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), selection, null, selectDatum, asw); i.putExtra("entity_detail_index", position); if (mNoDetailMode) { // Not actually launching detail intent because there's no confirm detail available returnWithResult(i); } else { startActivityForResult(i, CONFIRM_SELECT); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case BARCODE_FETCH: processBarcodeFetch(resultCode, intent); break; case CALLOUT: processCalloutResult(resultCode, intent); break; case CONFIRM_SELECT: resuming = true; if (resultCode == RESULT_OK && !mViewMode) { // create intent for return and store path returnWithResult(intent); return; } else { //Did we enter the detail from mapping mode? If so, go back to that if (mResultIsMap) { mResultIsMap = false; Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return; } if (inAwesomeMode) { // Retain original element selection TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (r != null && adapter != null) { // TODO: added 'adapter != null' due to a // NullPointerException, we need to figure out how to // make sure adapter is never null -- PLM this.displayReferenceAwesome(r, adapter.getPosition(r)); updateSelectedItem(r, true); } AudioController.INSTANCE.releaseCurrentMediaEntity(); } return; } case MAP_SELECT: if (resultCode == RESULT_OK) { TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (inAwesomeMode) { this.displayReferenceAwesome(r, adapter.getPosition(r)); } else { Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), r, null, selectDatum, asw); if (mNoDetailMode) { returnWithResult(i); } else { //To go back to map mode if confirm is false mResultIsMap = true; i.putExtra("entity_detail_index", adapter.getPosition(r)); startActivityForResult(i, CONFIRM_SELECT); } return; } } else { refreshView(); return; } default: super.onActivityResult(requestCode, resultCode, intent); } } private void processBarcodeFetch(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("SCAN_RESULT"); if (result != null) { result = result.trim(); } setSearchText(result); } } private void processCalloutResult(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("odk_intent_data"); if (result != null){ setSearchText(result.trim()); } else { for (String key : shortSelect.getCallout().getResponses()) { result = intent.getExtras().getString(key); if (result != null) { setSearchText(result); return; } } } } } /** * Finish this activity, including all extras from the given intent in the finishing intent */ private void returnWithResult(Intent intent) { Intent i = new Intent(this.getIntent()); i.putExtras(intent.getExtras()); setResult(RESULT_OK, i); finish(); } @Override public void afterTextChanged(Editable incomingEditable) { final String incomingString = incomingEditable.toString(); final String currentSearchText = getSearchText().toString(); if (incomingString.equals(currentSearchText)) { filterString = currentSearchText; if (adapter != null) { adapter.applyFilter(filterString); } } if (!isUsingActionBar()) { lastQueryString = filterString; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //use the old method here because some Android versions don't like Spannables for titles menu.add(0, MENU_SORT, MENU_SORT, Localization.get("select.menu.sort")).setIcon( android.R.drawable.ic_menu_sort_alphabetically); if (mMappingEnabled) { menu.add(0, MENU_MAP, MENU_MAP, Localization.get("select.menu.map")).setIcon( android.R.drawable.ic_menu_mapmode); } if (shortSelect != null) { Action action = shortSelect.getCustomAction(); if (action != null) { ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION, action.getDisplay().evaluate()); } } tryToAddActionSearchBar(this, menu, new ActionBarInstantiator() { // again, this should be unnecessary... @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void onActionBarFound(MenuItem searchItem, SearchView searchView) { EntitySelectActivity.this.searchItem = searchItem; EntitySelectActivity.this.searchView = searchView; // restore last query string in the searchView if there is one if (lastQueryString != null && lastQueryString.length() > 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { searchItem.expandActionView(); } searchView.setQuery(lastQueryString, false); if (BuildConfig.DEBUG) { Log.v(TAG, "Setting lastQueryString in searchView: (" + lastQueryString + ")"); } if (adapter != null) { adapter.applyFilter(lastQueryString == null ? "" : lastQueryString); } } EntitySelectActivity.this.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { lastQueryString = newText; filterString = newText; if (adapter != null) { adapter.applyFilter(newText); } return false; } }); } }); return true; } /** * Checks if this activity uses the ActionBar */ private boolean isUsingActionBar() { return searchView != null; } @SuppressWarnings("NewApi") private CharSequence getSearchText() { if (isUsingActionBar()) { return searchView.getQuery(); } return searchbox.getText(); } @SuppressWarnings("NewApi") private void setSearchText(CharSequence text) { if (isUsingActionBar()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { searchItem.expandActionView(); } searchView.setQuery(text, false); } searchbox.setText(text); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only enable sorting once entity loading is complete menu.findItem(MENU_SORT).setEnabled(adapter != null); // hide sorting menu when using async loading strategy menu.findItem(MENU_SORT).setVisible((shortSelect == null || !shortSelect.useAsyncStrategy())); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SORT: createSortMenu(); return true; case MENU_MAP: Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return true; case MENU_ACTION: triggerDetailAction(); return true; // handling click on the barcode scanner's actionbar // trying to set the onclicklistener in its view in the onCreateOptionsMenu method does not work because it returns null case R.id.barcode_scan_action_bar: barcodeScanOnClickListener.onClick(null); return true; // this is needed because superclasses do not implement the menu_settings click case R.id.menu_settings: CommCareHomeActivity.createPreferencesMenu(this); return true; } return super.onOptionsItemSelected(item); } private void triggerDetailAction() { Action action = shortSelect.getCustomAction(); try { asw.executeStackActions(action.getStackOperations()); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), true); return; } this.setResult(CommCareHomeActivity.RESULT_RESTART); this.finish(); } private void createSortMenu() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("select.menu.sort")); dialog.setChoiceItems(getSortOptionsList(dialog)); dialog.show(); } private DialogChoiceItem[] getSortOptionsList(final PaneledChoiceDialog dialog) { SessionDatum datum = session.getNeededDatum(); DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields(); List<String> namesList = new ArrayList<>(); final int[] keyArray = new int[fields.length]; int[] sorts = adapter.getCurrentSort(); int currentSort = sorts.length == 1 ? sorts[0] : -1; boolean reversed = adapter.isCurrentSortReversed(); int added = 0; for (int i = 0; i < fields.length; ++i) { String result = fields[i].getHeader().evaluate(); if (!"".equals(result)) { String prepend = ""; if (currentSort == -1) { for (int j = 0; j < sorts.length; ++j) { if (sorts[j] == i) { prepend = (j + 1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "); } } } else if (currentSort == i) { prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "; } namesList.add(prepend + result); keyArray[added] = i; added++; } } DialogChoiceItem[] choiceItems = new DialogChoiceItem[namesList.size()]; for (int i = 0; i < namesList.size(); i++) { final int index = i; View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { adapter.sortEntities(new int[]{keyArray[index]}); adapter.applyFilter(getSearchText().toString()); dialog.dismiss(); } }; DialogChoiceItem item = new DialogChoiceItem(namesList.get(i), -1, listener); choiceItems[i] = item; } return choiceItems; } @Override protected void onDestroy() { super.onDestroy(); if (loader != null) { if (isFinishing()) { loader.cancel(false); } else { loader.detachActivity(); } } if (adapter != null) { adapter.signalKilled(); } } @Override public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references, NodeEntityFactory factory) { loader = null; Detail detail = session.getDetail(selectDatum.getShortDetail()); int[] order = detail.getSortOrder(); for (int i = 0; i < detail.getFields().length; ++i) { String header = detail.getFields()[i].getHeader().evaluate(); if (order.length == 0 && !"".equals(header)) { order = new int[]{i}; } } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); setupDivider(view); adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, null, factory); view.setAdapter(adapter); adapter.registerDataSetObserver(this.mListStateObserver); containerFragment.setData(adapter); // Pre-select entity if one was provided in original intent if (!resuming && !mNoDetailMode && inAwesomeMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) { TreeReference entity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY)); if (entity != null) { displayReferenceAwesome(entity, adapter.getPosition(entity)); updateSelectedItem(entity, true); } } findViewById(R.id.entity_select_loading).setVisibility(View.GONE); if (adapter != null && filterString != null && !"".equals(filterString)) { adapter.applyFilter(filterString); } //In landscape we want to select something now. Either the top item, or the most recently selected one if (inAwesomeMode) { updateSelectedItem(true); } this.startTimer(); } private void setupDivider(ListView view) { boolean useNewDivider = shortSelect.usesGridView(); if (useNewDivider) { int viewWidth = view.getWidth(); float density = getResources().getDisplayMetrics().density; int viewWidthDP = (int)(viewWidth / density); // sometimes viewWidth is 0, and in this case we default to a reasonable value taken from dimens.xml int dividerWidth = viewWidth == 0 ? (int)getResources().getDimension(R.dimen.entity_select_divider_left_inset) : (int)(viewWidth / 6.0); Drawable divider = getResources().getDrawable(R.drawable.divider_case_list_modern); if (BuildConfig.DEBUG) { Log.v(TAG, "ListView divider is: " + divider + ", estimated divider width is: " + dividerWidth + ", viewWidth (dp) is: " + viewWidthDP); } if (BuildConfig.DEBUG && (divider == null || !(divider instanceof LayerDrawable))) { throw new AssertionError("Divider should be a LayerDrawable!"); } LayerDrawable layerDrawable = (LayerDrawable)divider; dividerWidth += (int)getResources().getDimension(R.dimen.row_padding_horizontal); layerDrawable.setLayerInset(0, dividerWidth, 0, 0, 0); view.setDivider(layerDrawable); } else { view.setDivider(null); } view.setDividerHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); } private void updateSelectedItem(boolean forceMove) { TreeReference chosen = null; if (selectedIntent != null) { chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); } updateSelectedItem(chosen, forceMove); } private void updateSelectedItem(TreeReference selected, boolean forceMove) { if (adapter == null) { return; } if (selected != null) { adapter.notifyCurrentlyHighlighted(selected); if (forceMove) { ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); view.setSelection(adapter.getPosition(selected)); } } } @Override public void attach(EntityLoaderTask task) { findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE); this.loader = task; } private void select() { // create intent for return and store path Intent i = new Intent(EntitySelectActivity.this.getIntent()); i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); setResult(RESULT_OK, i); finish(); } @Override public void callRequested(String phoneNumber) { DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber); } @Override public void addressRequested(String address) { DetailCalloutListenerDefaultImpl.addressRequested(this, address); } @Override public void playVideo(String videoRef) { DetailCalloutListenerDefaultImpl.playVideo(this, videoRef); } @Override public void performCallout(CalloutData callout, int id) { DetailCalloutListenerDefaultImpl.performCallout(this, callout, id); } private void displayReferenceAwesome(final TreeReference selection, int detailIndex) { selectedIntent = EntityDetailUtils.getDetailIntent(getApplicationContext(), selection, getIntent(), selectDatum, asw); //this should be 100% "fragment" able if (!rightFrameSetup) { findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE); View.inflate(this, R.layout.entity_detail, rightFrame); Button next = (Button)findViewById(R.id.entity_select_button); //use the old method here because some Android versions don't like Spannables for titles next.setText(Localization.get("select.detail.confirm")); next.setOnClickListener(new OnClickListener() { public void onClick(View v) { select(); } }); if (mViewMode) { next.setVisibility(View.GONE); next.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID); if (passedCommand != null) { mViewMode = session.isViewCommand(passedCommand); } else { mViewMode = session.isViewCommand(session.getCommand()); } detailView = (TabbedDetailView)rightFrame.findViewById(R.id.entity_detail_tabs); detailView.setRoot(detailView); factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new AndroidInstanceInitializer(session))); Detail detail = factory.getDetail(); detailView.showMenu(); if (detail.isCompound()) { // border around right panel doesn't look right when there are tabs rightFrame.setBackgroundDrawable(null); } rightFrameSetup = true; } detailView.refresh(factory.getDetail(), selection, detailIndex); } @Override public void deliverError(Exception e) { displayException(e); } @Override protected boolean onForwardSwipe() { // If user has picked an entity, move along to form entry if (selectedIntent != null) { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() < detailView.getTabCount() - 1) { return false; } if (!mViewMode) { select(); } } return true; } @Override protected boolean onBackwardSwipe() { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) { return false; } finish(); return true; } //Below is helper code for the Refresh Feature. //this is a dev feature and should get restructured before release in prod. //If the devloper setting is turned off this code should do nothing. private void triggerRebuild() { if (loader == null && !EntityLoaderTask.attachToActivity(this)) { EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext()); theloader.attachListener(this); theloader.execute(selectDatum.getNodeset()); } } private void startTimer() { if (!DeveloperPreferences.isListRefreshEnabled()) { return; } synchronized (timerLock) { if (myTimer == null) { myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (!cancelled) { triggerRebuild(); } } }); } }, 15 * 1000, 15 * 1000); cancelled = false; } } } private void stopTimer() { synchronized (timerLock) { if (myTimer != null) { myTimer.cancel(); myTimer = null; cancelled = true; } } } }
package org.commcare.dalvik.application; import android.annotation.SuppressLint; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.provider.Settings.Secure; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.util.Log; import android.util.Pair; import android.widget.Toast; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteException; import org.acra.annotation.ReportsCrashes; import org.commcare.android.database.AndroidDbHelper; import org.commcare.android.database.MigrationException; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.UserStorageClosedException; import org.commcare.android.database.app.DatabaseAppOpenHelper; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.global.DatabaseGlobalOpenHelper; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.android.database.user.CommCareUserOpenHelper; import org.commcare.android.database.user.models.FormRecord; import org.javarosa.core.model.User; import org.commcare.android.db.legacy.LegacyInstallUtils; import org.commcare.android.framework.SessionActivityRegistration; import org.commcare.android.javarosa.AndroidLogEntry; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.javarosa.PreInitLogger; import org.commcare.android.logic.GlobalConstants; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.models.notifications.NotificationClearReceiver; import org.commcare.android.models.notifications.NotificationMessage; import org.commcare.android.references.ArchiveFileRoot; import org.commcare.android.references.AssetFileRoot; import org.commcare.android.references.JavaHttpRoot; import org.commcare.android.resource.ResourceInstallUtils; import org.commcare.android.storage.framework.Table; import org.commcare.android.tasks.DataSubmissionListener; import org.commcare.android.tasks.ExceptionReportTask; import org.commcare.android.tasks.LogSubmissionTask; import org.commcare.android.tasks.PurgeStaleArchivedFormsTask; import org.commcare.android.tasks.UpdateTask; import org.commcare.android.tasks.templates.ManagedAsyncTask; import org.commcare.android.util.ACRAUtil; import org.commcare.android.util.AndroidCommCarePlatform; import org.commcare.android.util.AndroidUtil; import org.commcare.android.util.CallInPhoneListener; import org.commcare.android.util.CommCareExceptionHandler; import org.commcare.android.util.FileUtil; import org.commcare.android.util.ODKPropertyManager; import org.commcare.android.util.SessionStateUninitException; import org.commcare.android.util.SessionUnavailableException; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.LoginActivity; import org.commcare.dalvik.activities.MessageActivity; import org.commcare.dalvik.activities.UnrecoverableErrorActivity; import org.commcare.dalvik.odk.provider.ProviderUtils; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.dalvik.services.CommCareSessionService; import org.commcare.session.CommCareSession; import org.commcare.suite.model.Profile; import org.commcare.util.externalizable.AndroidClassHasher; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.Logger; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.storage.EntityFilter; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.PropertyUtils; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.crypto.SecretKey; /** * @author ctsims */ @ReportsCrashes( formUri = "https://your/cloudant/report", formUriBasicAuthLogin="your_username", formUriBasicAuthPassword="your_password", reportType = org.acra.sender.HttpSender.Type.JSON, httpMethod = org.acra.sender.HttpSender.Method.PUT) public class CommCareApplication extends Application { private static final String TAG = CommCareApplication.class.getSimpleName(); public static final int STATE_UNINSTALLED = 0; public static final int STATE_UPGRADE = 1; public static final int STATE_READY = 2; public static final int STATE_CORRUPTED = 4; public static final int STATE_DELETE_REQUESTED = 8; public static final int STATE_MIGRATION_FAILED = 16; public static final int STATE_MIGRATION_QUESTIONABLE = 32; public static final String ACTION_PURGE_NOTIFICATIONS = "CommCareApplication_purge"; private int dbState; private static CommCareApplication app; private CommCareApp currentApp; private CommCareApp appBeingInstalled; // stores current state of application: the session, form private AndroidSessionWrapper sessionWrapper; private final Object globalDbHandleLock = new Object(); private SQLiteDatabase globalDatabase; private ArchiveFileRoot mArchiveFileRoot; // Fields for managing a connection to the CommCareSessionService // A bound service is created out of the CommCareSessionService to ensure // it stays in memory. private CommCareSessionService mBoundService; private ServiceConnection mConnection; private final Object serviceLock = new Object(); // Has the CommCareSessionService been bound? private boolean mIsBound = false; // Has CommCareSessionService initilization finished? // Important so we don't use the service before the db is initialized. private boolean mIsBinding = false; //Milliseconds to wait for bind private static final int MAX_BIND_TIMEOUT = 5000; private int mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; private CallInPhoneListener listener = null; /** * Handler to receive notifications and show them the user using toast. */ private final PopupHandler toaster = new PopupHandler(this); @Override public void onCreate() { super.onCreate(); //Sets the static strategy for the deserializtion code to be //based on an optimized md5 hasher. Major speed improvements. AndroidClassHasher.registerAndroidClassHashStrategy(); AndroidUtil.initializeStaticHandlers(); CommCareApplication.app = this; //TODO: Make this robust PreInitLogger pil = new PreInitLogger(); Logger.registerLogger(pil); //Workaround because android is written by 7 year olds. //(reuses http connection pool improperly, so the second https //request in a short time period will flop) System.setProperty("http.keepAlive", "false"); Thread.setDefaultUncaughtExceptionHandler(new CommCareExceptionHandler(Thread.getDefaultUncaughtExceptionHandler(), this)); PropertyManager.setPropertyManager(new ODKPropertyManager()); SQLiteDatabase.loadLibs(this); setRoots(); prepareTemporaryStorage(); //Init global storage (Just application records, logs, etc) dbState = initGlobalDb(); //This is where we go through and check for updates between major transitions. //Soon we should start doing this differently, and actually go to an activity //first which tells the user what's going on. //The rule about this transition is that if the user had logs pending, we still want them in order, so //we aren't going to dump our logs from the Pre-init logger until after this transition occurs. try { LegacyInstallUtils.checkForLegacyInstall(this, this.getGlobalStorage(ApplicationRecord.class)); } catch(SessionUnavailableException sfe) { throw new RuntimeException(sfe); } finally { //No matter what happens, set up our new logger, we want those logs! Logger.registerLogger(new AndroidLogger(this.getGlobalStorage(AndroidLogEntry.STORAGE_KEY, AndroidLogEntry.class))); pil.dumpToNewLogger(); } intializeDefaultLocalizerData(); if (dbState != STATE_MIGRATION_FAILED && dbState != STATE_MIGRATION_QUESTIONABLE) { initializeAnAppOnStartup(); } ACRAUtil.initACRA(this); } public void triggerHandledAppExit(Context c, String message) { triggerHandledAppExit(c, message, Localization.get("app.handled.error.title")); } public void triggerHandledAppExit(Context c, String message, String title) { triggerHandledAppExit(c, message, title, true); } public void triggerHandledAppExit(Context c, String message, String title, boolean useExtraMessage) { Intent i = new Intent(c, UnrecoverableErrorActivity.class); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_TITLE, title); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_MESSAGE, message); i.putExtra(UnrecoverableErrorActivity.EXTRA_USE_MESSAGE, useExtraMessage); // start a new stack and forget where we were (so we don't restart the // app from there) i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_CLEAR_TOP); c.startActivity(i); } public void startUserSession(byte[] symetricKey, UserKeyRecord record) { synchronized(serviceLock) { // if we already have a connection established to // CommCareSessionService, close it and open a new one if(this.mIsBound) { releaseUserResourcesAndServices(); } bindUserSessionService(symetricKey, record); } } /** * Closes down the user service, resources, and background tasks. Used for * manual user log-outs. */ public void closeUserSession() { synchronized(serviceLock) { // Cancel any running tasks before closing down the user databse. ManagedAsyncTask.cancelTasks(); releaseUserResourcesAndServices(); } } /** * Closes down the user service, resources, and background tasks, * broadcasting an intent to redirect the user to the login screen. Used * for session-expiration related user logouts. */ public void expireUserSession() { synchronized(serviceLock) { closeUserSession(); SessionActivityRegistration.registerSessionExpiration(); sendBroadcast(new Intent(SessionActivityRegistration.USER_SESSION_EXPIRED)); } } public void releaseUserResourcesAndServices() { try { CommCareApplication._().getSession().closeServiceResources(); } catch (SessionUnavailableException e) { Log.w(TAG, "User's session services have unexpectedly already " + "been closed down. Proceeding to close the session."); } unbindUserSessionService(); } public SecretKey createNewSymetricKey() throws SessionUnavailableException { return getSession().createNewSymetricKey(); } private void attachCallListener() { TelephonyManager tManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); listener = new CallInPhoneListener(this, this.getCommCarePlatform()); listener.startCache(); tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } public CallInPhoneListener getCallListener() { return listener; } public int[] getCommCareVersion() { return this.getResources().getIntArray(R.array.commcare_version); } public AndroidCommCarePlatform getCommCarePlatform() { if (this.currentApp == null) { throw new RuntimeException("No App installed!!!"); } else { return this.currentApp.getCommCarePlatform(); } } public CommCareApp getCurrentApp() { return this.currentApp; } /** * Get the current CommCare session that's being executed */ public CommCareSession getCurrentSession() { return getCurrentSessionWrapper().getSession(); } public AndroidSessionWrapper getCurrentSessionWrapper() { if (sessionWrapper == null) { throw new SessionStateUninitException("CommCare user session isn't available"); } return sessionWrapper; } public int getDatabaseState() { return dbState; } public void initializeGlobalResources(CommCareApp app) { if (dbState != STATE_UNINSTALLED) { initializeAppResources(app); } } public String getPhoneId() { TelephonyManager manager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); String imei = manager.getDeviceId(); if (imei == null) { imei = Secure.getString(getContentResolver(), Secure.ANDROID_ID); } return imei; } public void intializeDefaultLocalizerData() { Localization.init(true); Localization.registerLanguageReference("default", "jr://asset/locales/messages_ccodk_default.txt"); Localization.setDefaultLocale("default"); //For now. Possibly handle this better in the future Localization.setLocale("default"); } private void setRoots() { JavaHttpRoot http = new JavaHttpRoot(); AssetFileRoot afr = new AssetFileRoot(this); ArchiveFileRoot arfr = new ArchiveFileRoot(); mArchiveFileRoot = arfr; ReferenceManager._().addReferenceFactory(http); ReferenceManager._().addReferenceFactory(afr); ReferenceManager._().addReferenceFactory(arfr); ReferenceManager._().addRootTranslator(new RootTranslator("jr://media/", GlobalConstants.MEDIA_REF)); } /** * Performs the appropriate initialization of an application when this CommCareApplication is * first launched */ private void initializeAnAppOnStartup() { // Before we try to initialize a new app, check if any existing apps were left in a // partially deleted state, and finish uninstalling them if so for (ApplicationRecord record : getGlobalStorage(ApplicationRecord.class)) { if (record.getStatus() == ApplicationRecord.STATUS_DELETE_REQUESTED) { try { uninstall(record); } catch (RuntimeException e) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Unable to uninstall an app " + "during startup that was previously left partially-deleted"); } } } // There may now be multiple app records in storage, because of multiple apps support. We // want to initialize one of them to start, so that there will be currently-seated app when // the login screen starts up SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String lastAppId = prefs.getString(LoginActivity.KEY_LAST_APP, ""); if (!"".equals(lastAppId)) { // If there is a 'last app' set in shared preferences, try to initialize that application. ApplicationRecord lastApp = getAppById(lastAppId); if (lastApp == null || !lastApp.isUsable()) { // This app record could be null if it has since been uninstalled, or unusable if // it has since been archived, etc. In either case, just revert to picking the // first app initFirstUsableAppRecord(); } else { initializeAppResources(new CommCareApp(lastApp)); } } else { // Otherwise, just pick the first app in the list to initialize initFirstUsableAppRecord(); } } /** * Initializes the first "usable" application from the list of globally installed app records, * if there is one */ public void initFirstUsableAppRecord() { for (ApplicationRecord record : getUsableAppRecords()) { initializeAppResources(new CommCareApp(record)); break; } } /** * Initialize all of the given app's resources, and set the state of its resources accordingly * * @param app the CC app to initialize */ public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; if (currentApp.initializeApplication()) { resourceState = STATE_READY; this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform()); } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); } /** * @return all ApplicationRecords in storage, regardless of their status, in alphabetical order */ public ArrayList<ApplicationRecord> getInstalledAppRecords() { ArrayList<ApplicationRecord> records = new ArrayList<>(); for (ApplicationRecord r : getGlobalStorage(ApplicationRecord.class)) { records.add(r); } Collections.sort(records, new Comparator<ApplicationRecord>() { @Override public int compare(ApplicationRecord lhs, ApplicationRecord rhs) { return lhs.getDisplayName().compareTo(rhs.getDisplayName()); } }); return records; } /** * @return all ApplicationRecords that have status installed and are NOT archived */ public ArrayList<ApplicationRecord> getVisibleAppRecords() { ArrayList<ApplicationRecord> visible = new ArrayList<>(); for (ApplicationRecord r : getInstalledAppRecords()) { if (r.isVisible()) { visible.add(r); } } return visible; } /** * @return all ApplicationRecords that are installed AND are not archived AND have MM verified */ public ArrayList<ApplicationRecord> getUsableAppRecords() { ArrayList<ApplicationRecord> ready = new ArrayList<>(); for (ApplicationRecord r : getInstalledAppRecords()) { if (r.isUsable()) { ready.add(r); } } return ready; } /** * @return whether the user should be sent to CommCareVerificationActivity. Current logic is * that this should occur only if there is exactly one visible app and it is missing its MM * (because we are then assuming the user is not currently using multiple apps functionality) */ public boolean shouldSeeMMVerification() { return (CommCareApplication._().getVisibleAppRecords().size() == 1 && CommCareApplication._().getUsableAppRecords().size() == 0); } public boolean usableAppsPresent() { return getUsableAppRecords().size() > 0; } /** * @return the list of all installed apps as an array */ public ApplicationRecord[] appRecordArray() { ArrayList<ApplicationRecord> appList = CommCareApplication._().getInstalledAppRecords(); ApplicationRecord[] appArray = new ApplicationRecord[appList.size()]; int index = 0; for (ApplicationRecord r : appList) { appArray[index++] = r; } return appArray; } /** * @param uniqueId - the uniqueId of the ApplicationRecord being sought * @return the ApplicationRecord corresponding to the given id, if it exists. Otherwise, * return null */ public ApplicationRecord getAppById(String uniqueId) { for (ApplicationRecord r : getInstalledAppRecords()) { if (r.getUniqueId().equals(uniqueId)) { return r; } } return null; } /** * @return if the given ApplicationRecord is the currently seated one */ public boolean isSeated(ApplicationRecord record) { return currentApp != null && currentApp.getUniqueId().equals(record.getUniqueId()); } /** * If the given record is the currently seated app, unseat it */ public void unseat(ApplicationRecord record) { if (isSeated(record)) { this.currentApp.teardownSandbox(); this.currentApp = null; } } /** * Completes a full uninstall of the CC app that the given ApplicationRecord represents. * This method should be idempotent and should be capable of completing an uninstall * regardless of previous failures */ public void uninstall(ApplicationRecord record) { CommCareApp app = new CommCareApp(record); // 1) If the app we are uninstalling is the currently-seated app, tear down its sandbox if (isSeated(record)) { getCurrentApp().teardownSandbox(); } // 2) Set record's status to delete requested, so we know if we have left it in a bad // state later record.setStatus(ApplicationRecord.STATUS_DELETE_REQUESTED); getGlobalStorage(ApplicationRecord.class).write(record); // 3) Delete the directory containing all of this app's resources if (!FileUtil.deleteFileOrDir(app.storageRoot())) { Logger.log(AndroidLogger.TYPE_RESOURCES, "App storage root was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 4) Delete all the user databases associated with this app SqlStorage<UserKeyRecord> userDatabase = app.getStorage(UserKeyRecord.class); for (UserKeyRecord user : userDatabase) { File f = getDatabasePath(CommCareUserOpenHelper.getDbName(user.getUuid())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "A user database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); // If we failed to delete a file, it is likely because there is an open pointer // to that db still in use, so stop the uninstall for now, and rely on it to // complete the next time the app starts up return; } } // 5) Delete the forms database for this app File formsDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.FORMS, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(formsDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's forms database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 6) Delete the instances database for this app File instancesDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.INSTANCES, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(instancesDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's instances database was unable to" + " be deleted during app uninstall. Aborting uninstall process for now."); return; } // 7) Delete the app database File f = getDatabasePath(DatabaseAppOpenHelper.getDbName(app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app database was unable to be deleted" + "during app uninstall. Aborting uninstall process for now."); return; } // 8) Delete the ApplicationRecord getGlobalStorage(ApplicationRecord.class).remove(record.getID()); } private int initGlobalDb() { SQLiteDatabase database; try { database = new DatabaseGlobalOpenHelper(this).getWritableDatabase("null"); database.close(); return STATE_READY; } catch (SQLiteException e) { //Only thrown if DB isn't there return STATE_UNINSTALLED; } catch (MigrationException e) { if (e.isDefiniteFailure()) { return STATE_MIGRATION_FAILED; } else { return STATE_MIGRATION_QUESTIONABLE; } } } public SQLiteDatabase getUserDbHandle() throws SessionUnavailableException { return this.getSession().getUserDbHandle(); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(Class<T> c) { return getGlobalStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(String table, Class<T> c) { return new SqlStorage<T>(table, c, new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { synchronized (globalDbHandleLock) { if (globalDatabase == null || !globalDatabase.isOpen()) { globalDatabase = new DatabaseGlobalOpenHelper(this.c).getWritableDatabase("null"); } return globalDatabase; } } }); } public <T extends Persistable> SqlStorage<T> getAppStorage(Class<T> c) { return getAppStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getAppStorage(String name, Class<T> c) { return currentApp.getStorage(name, c); } public <T extends Persistable> SqlStorage<T> getUserStorage(Class<T> c) { return getUserStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getUserStorage(String storage, Class<T> c) { return new SqlStorage<T>(storage, c, new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() throws SessionUnavailableException { SQLiteDatabase database = getUserDbHandle(); if (database == null) { throw new SessionUnavailableException("The user database has been closed!"); } return database; } }); } public <T extends Persistable> SqlStorage<T> getRawStorage(String storage, Class<T> c, final SQLiteDatabase handle) { return new SqlStorage<T>(storage, c, new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { return handle; } }); } public static CommCareApplication _() { return app; } /** * This method wipes out all local user data (users, referrals, etc) but leaves * application resources in place. * * It makes no attempt to make sure this is a safe operation when called, so * it shouldn't be used lightly. */ public void clearUserData() { // //First clear anything that will require the user's key, since we're going to wipe it out! // getStorage(ACase.STORAGE_KEY, ACase.class).removeAll(); // //TODO: We should really be wiping out the _stored_ instances here, too // getStorage(FormRecord.STORAGE_KEY, FormRecord.class).removeAll(); // //Also, any of the sessions we've got saved // getStorage(SessionStateDescriptor.STORAGE_KEY, SessionStateDescriptor.class).removeAll(); // //Now we wipe out the user entirely // getStorage(User.STORAGE_KEY, User.class).removeAll(); // //Get rid of any user fixtures // getStorage("fixture", FormInstance.class).removeAll(); // getStorage(GeocodeCacheModel.STORAGE_KEY, GeocodeCacheModel.class).removeAll(); final String username; try { username = this.getSession().getLoggedInUser().getUsername(); } catch (SessionUnavailableException e) { return; } final Set<String> dbIdsToRemove = new HashSet<String>(); this.getAppStorage(UserKeyRecord.class).removeAll(new EntityFilter<UserKeyRecord>() { @Override public boolean matches(UserKeyRecord ukr) { if (ukr.getUsername().equalsIgnoreCase(username.toLowerCase())) { dbIdsToRemove.add(ukr.getUuid()); return true; } return false; } }); //TODO: We can just delete the db entirely. Editor sharedPreferencesEditor = CommCareApplication._().getCurrentApp().getAppPreferences().edit(); sharedPreferencesEditor.putString(CommCarePreferences.LAST_LOGGED_IN_USER, null); sharedPreferencesEditor.commit(); for (String id : dbIdsToRemove) { //TODO: We only wanna do this if the user is the _last_ one with a key to this id, actually. //(Eventually) this.getDatabasePath(CommCareUserOpenHelper.getDbName(id)).delete(); } CommCareApplication._().closeUserSession(); } public void prepareTemporaryStorage() { String tempRoot = this.getAndroidFsTemp(); FileUtil.deleteFileOrDir(tempRoot); boolean success = FileUtil.createFolder(tempRoot); if (!success) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Couldn't create temp folder"); } } public String getCurrentVersionString() { PackageManager pm = this.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); return "ERROR! Incorrect package version requested"; } int[] versions = this.getCommCareVersion(); String ccv = ""; for (int vn : versions) { if (!"".equals(ccv)) { ccv += "."; } ccv += vn; } String profileVersion = ""; Profile p = this.currentApp == null ? null : this.getCommCarePlatform().getCurrentProfile(); if (p != null) { profileVersion = String.valueOf(p.getVersion()); } String buildDate = BuildConfig.BUILD_DATE; String buildNumber = BuildConfig.BUILD_NUMBER; return Localization.get(getString(R.string.app_version_string), new String[]{pi.versionName, String.valueOf(pi.versionCode), ccv, buildNumber, buildDate, profileVersion}); } /** * Allows something within the current service binding to update the app to let it * know that the bind may take longer than the current timeout can allow */ public void setCustomServiceBindTimeout(int timeout) { synchronized (serviceLock) { this.mCurrentServiceBindTimeout = timeout; } } private void bindUserSessionService(final byte[] key, final UserKeyRecord record) { mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. User user = null; synchronized (serviceLock) { mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; mBoundService = ((CommCareSessionService.LocalBinder) service).getService(); //Don't let anyone touch this until it's logged in // Open user database mBoundService.prepareStorage(key, record); if (record != null) { //Ok, so we have a login that was successful, but do we have a user model in the DB? //We need to check before we're logged in, so we get the handle raw, here for (User u : getRawStorage("USER", User.class, mBoundService.getUserDbHandle())) { if (record.getUsername().equals(u.getUsername())) { user = u; } } } //service available mIsBound = true; //Don't signal bind completion until the db is initialized. mIsBinding = false; if (user != null) { mBoundService.startSession(user); attachCallListener(); CommCareApplication.this.sessionWrapper = new AndroidSessionWrapper(CommCareApplication.this.getCommCarePlatform()); if (shouldAutoUpdate()) { startAutoUpdate(); } syncPending = getPendingSyncStatus(); doReportMaintenance(false); //Register that this user was the last to successfully log in if it's a real user if (!User.TYPE_DEMO.equals(user.getUserType())) { getCurrentApp().getAppPreferences().edit().putString(CommCarePreferences.LAST_LOGGED_IN_USER, record.getUsername()).commit(); PurgeStaleArchivedFormsTask.launchPurgeTask(); } } } } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; } }; // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(this, CommCareSessionService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBinding = true; } public User getCurrentUserFromDB(String username){ for (User u : getRawStorage("USER", User.class, mBoundService.getUserDbHandle())) { if (username.equals(u.getUsername())) { return u; } } return null; } @SuppressLint("NewApi") protected void doReportMaintenance(boolean force) { //OK. So for now we're going to daily report sends and not bother with any of the frequency properties. //Create a new submission task no matter what. If nothing is pending, it'll see if there are unsent reports //and try to send them. Otherwise, it'll create the report SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); String url = settings.getString("PostURL", null); if (url == null) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "PostURL isn't set. This should never happen"); return; } DataSubmissionListener dataListener = null; try { dataListener = CommCareApplication.this.getSession().startDataSubmissionListener(R.string.submission_logs_title); } catch (SessionUnavailableException sue) { // abort since it looks like the session expired return; } LogSubmissionTask task = new LogSubmissionTask( force || isPending(settings.getLong(CommCarePreferences.LOG_LAST_DAILY_SUBMIT, 0), DateUtils.DAY_IN_MILLIS), dataListener, url); //Execute on a true multithreaded chain, since this is an asynchronous process if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { task.execute(); } } /** * @return True if we aren't a demo user and the time to check for an * update has elapsed or we logged out while an auto-update was downlaoding * or queued for retry. */ private boolean shouldAutoUpdate() { return (!areAutomatedActionsInvalid() && (ResourceInstallUtils.shouldAutoUpdateResume(getCurrentApp()) || isUpdatePending())); } private void startAutoUpdate() { Logger.log(AndroidLogger.TYPE_MAINTENANCE, "Auto-Update Triggered"); String ref = ResourceInstallUtils.getDefaultProfileRef(); try { UpdateTask updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(this); updateTask.setAsAutoUpdate(); updateTask.execute(ref); } catch(IllegalStateException e) { Log.w(TAG, "Trying trigger auto-update when it is already running. " + "Should only happen if the user triggered a manual update before this fired."); } } public boolean isUpdatePending() { SharedPreferences preferences = getCurrentApp().getAppPreferences(); //Establish whether or not an AutoUpdate is Pending String autoUpdateFreq = preferences.getString(CommCarePreferences.AUTO_UPDATE_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); //See if auto update is even turned on if (!autoUpdateFreq.equals(CommCarePreferences.FREQUENCY_NEVER)) { long lastUpdateCheck = preferences.getLong(CommCarePreferences.LAST_UPDATE_ATTEMPT, 0); return isTimeForAutoUpdateCheck(lastUpdateCheck, autoUpdateFreq); } return false; } public boolean isTimeForAutoUpdateCheck(long lastUpdateCheck, String autoUpdateFreq) { int checkEveryNDays; if (CommCarePreferences.FREQUENCY_DAILY.equals(autoUpdateFreq)) { checkEveryNDays = 1; } else { checkEveryNDays = 7; } long duration = DateUtils.DAY_IN_MILLIS * checkEveryNDays; return isPending(lastUpdateCheck, duration); } private boolean isPending(long last, long period) { long now = new Date().getTime(); //1) Straightforward - Time is greater than last + duration long diff = now - last; if (diff > period) { return true; } Calendar lastRestoreCalendar = Calendar.getInstance(); lastRestoreCalendar.setTimeInMillis(last); //2) For daily stuff, we want it to be the case that if the last time you synced was the day prior, //you still sync, so people can get into the cycle of doing it once in the morning, which //is more valuable than syncing mid-day. if (period == DateUtils.DAY_IN_MILLIS && (lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK))) { return true; } //3) Major time change - (Phone might have had its calendar day manipulated). //for now we'll simply say that if last was more than a day in the future (timezone blur) //we should also trigger return (now < (last - DateUtils.DAY_IN_MILLIS)); } /** * Whether automated stuff like auto-updates/syncing are valid and should * be triggered. */ private boolean areAutomatedActionsInvalid() { try { return User.TYPE_DEMO.equals(getSession().getLoggedInUser().getUserType()); } catch (SessionUnavailableException sue) { return true; } } private void unbindUserSessionService() { synchronized (serviceLock) { if (mIsBound) { if (sessionWrapper != null) { sessionWrapper.reset(); } mIsBound = false; // Detach our existing connection. unbindService(mConnection); } } } public CommCareSessionService getSession() throws SessionUnavailableException { long started = System.currentTimeMillis(); //If binding is currently in process, just wait for it. while (mIsBinding) { if (System.currentTimeMillis() - started > mCurrentServiceBindTimeout) { //Something bad happened unbindUserSessionService(); throw new SessionUnavailableException("Timeout binding to session service"); } } if (mIsBound) { synchronized (serviceLock) { return mBoundService; } } else { throw new SessionUnavailableException(); } } /** * @return A pair comprised of last sync time and an array with unsent and * incomplete form counts. If the user storage isn't open, return 0 vals * for unsent/incomplete forms. */ public Pair<Long, int[]> getSyncDisplayParameters() { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); long lastSync = prefs.getLong("last-succesful-sync", 0); SqlStorage<FormRecord> formsStorage = this.getUserStorage(FormRecord.class); try { int unsentForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_UNSENT).size(); int incompleteForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE).size(); return new Pair<>(lastSync, new int[]{unsentForms, incompleteForms}); } catch (UserStorageClosedException e) { return new Pair<>(lastSync, new int[]{0, 0}); } } // Start - Error message Hooks private final int MESSAGE_NOTIFICATION = org.commcare.dalvik.R.string.notification_message_title; private final ArrayList<NotificationMessage> pendingMessages = new ArrayList<NotificationMessage>(); public void reportNotificationMessage(NotificationMessage message) { reportNotificationMessage(message, false); } public void reportNotificationMessage(final NotificationMessage message, boolean notifyUser) { synchronized (pendingMessages) { //make sure there is no matching message pending for (NotificationMessage msg : pendingMessages) { if (msg.equals(message)) { //If so, bail. return; } } if (notifyUser) { Bundle b = new Bundle(); b.putParcelable("message", message); Message m = Message.obtain(toaster); m.setData(b); toaster.sendMessage(m); } //Otherwise, add it to the queue, and update the notification pendingMessages.add(message); updateMessageNotification(); } } public void updateMessageNotification() { NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); synchronized (pendingMessages) { if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); return; } String title = pendingMessages.get(0).getTitle(); Notification messageNotification = new Notification(org.commcare.dalvik.R.drawable.notification, title, System.currentTimeMillis()); messageNotification.number = pendingMessages.size(); // The PendingIntent to launch our activity if the user selects this notification Intent i = new Intent(this, MessageActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0); String additional = pendingMessages.size() > 1 ? Localization.get("notifications.prompt.more", new String[]{String.valueOf(pendingMessages.size() - 1)}) : ""; // Set the info for the views that show in the notification panel. messageNotification.setLatestEventInfo(this, title, Localization.get("notifications.prompt.details", new String[]{additional}), contentIntent); messageNotification.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, NotificationClearReceiver.class), 0); //Send the notification. mNM.notify(MESSAGE_NOTIFICATION, messageNotification); } } public ArrayList<NotificationMessage> purgeNotifications() { synchronized (pendingMessages) { this.sendBroadcast(new Intent(ACTION_PURGE_NOTIFICATIONS)); ArrayList<NotificationMessage> cloned = (ArrayList<NotificationMessage>) pendingMessages.clone(); clearNotifications(null); return cloned; } } public void clearNotifications(String category) { synchronized (pendingMessages) { NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Vector<NotificationMessage> toRemove = new Vector<NotificationMessage>(); for (NotificationMessage message : pendingMessages) { if (category == null || category.equals(message.getCategory())) { toRemove.add(message); } } for (NotificationMessage message : toRemove) { pendingMessages.remove(message); } if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); } else { updateMessageNotification(); } } } private boolean syncPending = false; /** * @return True if there is a sync action pending. */ private boolean getPendingSyncStatus() { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); long period = -1; //Old flag, use a day by default if ("true".equals(prefs.getString("cc-auto-update", "false"))) { period = DateUtils.DAY_IN_MILLIS; } //new flag, read what it is. String periodic = prefs.getString(CommCarePreferences.AUTO_SYNC_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); if (!periodic.equals(CommCarePreferences.FREQUENCY_NEVER)) { period = DateUtils.DAY_IN_MILLIS * (periodic.equals(CommCarePreferences.FREQUENCY_DAILY) ? 1 : 7); } //If we didn't find a period, bail if (period == -1) { return false; } long lastRestore = prefs.getLong(CommCarePreferences.LAST_SYNC_ATTEMPT, 0); return (isPending(lastRestore, period)); } public synchronized boolean isSyncPending(boolean clearFlag) { if (areAutomatedActionsInvalid()) { return false; } //We only set this to true occasionally, but in theory it could be set to false //from other factors, so turn it off if it is. if (!getPendingSyncStatus()) { syncPending = false; } if (!syncPending) { return false; } if (clearFlag) { syncPending = false; } return true; } public boolean isStorageAvailable() { try { File storageRoot = new File(getAndroidFsRoot()); return storageRoot.exists(); } catch (Exception e) { return false; } } /** * Notify the application that something has occurred which has been * logged, and which should cause log submission to occur as soon as * possible. */ public void notifyLogsPending() { doReportMaintenance(true); } public String getAndroidFsRoot() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/files/"; } public String getAndroidFsTemp() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/temp/"; } /** * @return a path to a file location that can be used to store a file * temporarily and will be cleaned up as part of CommCare's application * lifecycle */ public String getTempFilePath() { return getAndroidFsTemp() + PropertyUtils.genUUID(); } public ArchiveFileRoot getArchiveFileRoot() { return mArchiveFileRoot; } /** * Message handler that pops-up notifications to the user via toast. */ private static class PopupHandler extends Handler { /** * Reference to the context used to show pop-ups (the parent class). * Reference is weak to avoid memory leaks. */ private final WeakReference<CommCareApplication> mActivity; /** * @param activity Is the context used to pop-up the toast message. */ public PopupHandler(CommCareApplication activity) { mActivity = new WeakReference<CommCareApplication>(activity); } /** * Pops up the message to the user by way of toast * * @param m Has a 'message' parcel storing pop-up message text */ @Override public void handleMessage(Message m) { NotificationMessage message = m.getData().getParcelable("message"); CommCareApplication activity = mActivity.get(); if (activity != null) { Toast.makeText(activity, Localization.get("notification.for.details.wrapper", new String[]{message.getTitle()}), Toast.LENGTH_LONG).show(); } } } /** * Used for manually linking to a session service during tests */ public void setTestingService(CommCareSessionService service) { mIsBound = true; mBoundService = service; mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { } public void onServiceDisconnected(ComponentName className) { } }; } }
package <%=packageName%>.web.rest; import <%=packageName%>.security.AuthoritiesConstants; import <%=packageName%>.service.AuditEventService; import <%=packageName%>.web.propertyeditors.LocaleDateTimeEditor; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import java.util.List; /** * REST controller for getting the audit events. */ @RestController @RequestMapping("/app") public class AuditResource { @Inject private AuditEventService auditEventService; @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("MM/dd/yyyy hh:mm:ss a", false)); } @RequestMapping(value = "/rest/audits/all", method = RequestMethod.GET, produces = "application/json") @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findAll() { return auditEventService.findAll(); } @RequestMapping(value = "/rest/audits/byDates", method = RequestMethod.GET, produces = "application/json") @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate, @RequestParam(value = "toDate") LocalDateTime toDate) { return auditEventService.findBetweenDates(fromDate, toDate); } }
package com.jbooktrader.platform.backtest; import com.jbooktrader.platform.marketdepth.*; import com.jbooktrader.platform.startup.JBookTrader; import com.jbooktrader.platform.util.MessageDialog; import javax.swing.*; import java.io.*; import java.text.*; import java.util.*; /** * Writes historical market data to a file which is used for * backtesting and optimization of trading strategies. */ public final class BackTestFileWriter { private final static String FILE_SEP = System.getProperty("file.separator"); private static final String LINE_SEP = System.getProperty("line.separator"); private SimpleDateFormat dateFormat; private PrintWriter writer; public BackTestFileWriter(TimeZone timeZone) throws IOException { String dir = JBookTrader.getAppPath() + FILE_SEP + "marketData"; JFileChooser fileChooser = new JFileChooser(dir); fileChooser.setDialogTitle("Save historical market depth"); if (fileChooser.showDialog(null, "Save") == JFileChooser.APPROVE_OPTION) { dateFormat = new SimpleDateFormat("MMddyy,HH:mm:ss.SSS"); dateFormat.setTimeZone(timeZone); File file = fileChooser.getSelectedFile(); String fileName = file.getAbsolutePath(); writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false))); } } public void write(MarketBook marketBook) { if (writer != null) { DecimalFormatSymbols decimalFormatSeparator = new DecimalFormatSymbols(); decimalFormatSeparator.setDecimalSeparator('.'); DecimalFormat nf = (DecimalFormat) NumberFormat.getNumberInstance(); nf.setGroupingUsed(false); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(5); nf.setDecimalFormatSymbols( decimalFormatSeparator ); StringBuilder header = getHeader(); writer.println(header); // make a defensive copy to prevent concurrent modification List<MarketDepth> marketDepths = new ArrayList<MarketDepth>(); marketDepths.addAll(marketBook.getAll()); for (MarketDepth marketDepth : marketDepths) { StringBuilder sb = new StringBuilder(); sb.append(dateFormat.format(new Date(marketDepth.getTime()))); sb.append(";");// separator after data and time //double lowestBid = marketDepth.getBids().getLast().getPrice(); for (MarketDepthItem item : marketDepth.getBids()) { sb.append(item.getSize()).append(","); sb.append(nf.format(item.getPrice())).append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(";");// separator betweeb bids and asks for (MarketDepthItem item : marketDepth.getAsks()) { sb.append(item.getSize()).append(","); sb.append(nf.format(item.getPrice())).append(","); } sb.deleteCharAt(sb.length() - 1); writer.println(sb); } writer.flush(); writer.close(); MessageDialog.showMessage(null, "Historical market depth data has been saved."); } } private StringBuilder getHeader() { StringBuilder header = new StringBuilder(); header.append(" header.append("# Each line represents the order book at a particular time and contains 3 sections,:").append(LINE_SEP); header.append("# separated by semicolons as follows:").append(LINE_SEP); header.append("# {date, time}; {bids}; {asks}").append(LINE_SEP); header.append("# The date is in the MMddyy format, and the time in the HH:mm:ss.SSS format").append(LINE_SEP); header.append("# The {bids} section has a variable number of comma-separated columns").append(LINE_SEP); header.append("# and contains bids (each defined by bid size and bid price), starting from the highest bid price").append(LINE_SEP); header.append("# The {asks} section has a variable number of comma-separated columns").append(LINE_SEP); header.append("# and contains asks (each defined by ask size and ask price), starting from the lowest ask price").append(LINE_SEP); header.append(LINE_SEP); header.append("timeZone=").append(dateFormat.getTimeZone().getID()).append(LINE_SEP); return header; } }
package org.xdi.oxauth.service; import com.unboundid.ldap.sdk.Filter; import org.gluu.site.ldap.persistence.LdapEntryManager; import org.slf4j.Logger; import org.xdi.ldap.model.CustomAttribute; import org.xdi.ldap.model.GluuStatus; import org.xdi.oxauth.model.common.User; import org.xdi.oxauth.model.config.StaticConfiguration; import org.xdi.oxauth.model.configuration.AppConfiguration; import org.xdi.oxauth.model.token.PersistentJwt; import org.xdi.oxauth.model.util.Util; import org.xdi.util.StringHelper; import javax.annotation.Nullable; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; @Stateless @Named public class UserService { public static final String[] USER_OBJECT_CLASSES = new String[] { "gluuPerson" }; @Inject private Logger log; @Inject private LdapEntryManager ldapEntryManager; @Inject private InumService inumService; @Inject private StaticConfiguration staticConfiguration; @Inject private AppConfiguration appConfiguration; /** * returns User by Dn * * @return User */ @Nullable public User getUserByDn(String dn, String... returnAttributes) { if (Util.isNullOrEmpty(dn)) { return null; } return ldapEntryManager.find(User.class, dn, returnAttributes); } public User getUserByInum(String inum, String... returnAttributes) { if (StringHelper.isEmpty(inum)) { return null; } String userDn = getDnForUser(inum); User user = getUserByDn(userDn, returnAttributes); if (user == null) { return null; } return user; } public User getUser(String userId, String... returnAttributes) { log.debug("Getting user information from LDAP: userId = {}", userId); if (StringHelper.isEmpty(userId)) { return null; } Filter userUidFilter = Filter.createEqualityFilter("uid", userId); List<User> entries = ldapEntryManager.findEntries(staticConfiguration.getBaseDn().getPeople(), User.class, returnAttributes, userUidFilter); log.debug("Found {} entries for user id = {}", entries.size(), userId); if (entries.size() > 0) { return entries.get(0); } else { return null; } } public String getUserInum(User user) { if (user == null) { return null; } String inum = user.getAttribute("inum"); return inum; } public String getUserInum(String userId) { User user = getUser(userId, "inum"); return getUserInum(user); } public String getUserNameByInum(String inum) { if (StringHelper.isEmpty(inum)) { return null; } String userDn = getDnForUser(inum); User user = getUserByDn(userDn, "uid"); if (user == null) { return null; } return user.getUserId(); } public User updateUser(User user) { return ldapEntryManager.merge(user); } public User addDefaultUser(String uid) { String peopleBaseDN = staticConfiguration.getBaseDn().getPeople(); String inum = inumService.generatePeopleInum(); User user = new User(); user.setDn("inum=" + inum + "," + peopleBaseDN); user.setCustomAttributes(Arrays.asList( new CustomAttribute("inum", inum), new CustomAttribute("gluuStatus", GluuStatus.ACTIVE.getValue()), new CustomAttribute("displayName", "User " + uid + " added via oxAuth custom plugin"))); user.setUserId(uid); List<String> personCustomObjectClassList = appConfiguration.getPersonCustomObjectClassList(); if ((personCustomObjectClassList != null) && !personCustomObjectClassList.isEmpty()) { user.setCustomObjectClasses(personCustomObjectClassList.toArray(new String[personCustomObjectClassList.size()])); } ldapEntryManager.persist(user); return getUser(uid); } public User addUser(User user, boolean active) { String peopleBaseDN = staticConfiguration.getBaseDn().getPeople(); String inum = inumService.generatePeopleInum(); user.setDn("inum=" + inum + "," + peopleBaseDN); user.setAttribute("inum", inum); GluuStatus status = active ? GluuStatus.ACTIVE : GluuStatus.REGISTER; user.setAttribute("gluuStatus", status.getValue()); List<String> personCustomObjectClassList = appConfiguration.getPersonCustomObjectClassList(); if ((personCustomObjectClassList != null) && !personCustomObjectClassList.isEmpty()) { user.setCustomObjectClasses(personCustomObjectClassList.toArray(new String[personCustomObjectClassList.size()])); } ldapEntryManager.persist(user); return getUserByDn(user.getDn()); } public User getUserByAttribute(String attributeName, String attributeValue) { log.debug("Getting user information from LDAP: attributeName = '{}', attributeValue = '{}'", attributeName, attributeValue); User user = new User(); user.setDn(staticConfiguration.getBaseDn().getPeople()); List<CustomAttribute> customAttributes = new ArrayList<CustomAttribute>(); customAttributes.add(new CustomAttribute(attributeName, attributeValue)); user.setCustomAttributes(customAttributes); List<User> entries = ldapEntryManager.findEntries(user); log.debug("Found '{}' entries", entries.size()); if (entries.size() > 0) { return entries.get(0); } else { return null; } } public List<User> getUsersBySample(User user, int limit) { log.debug("Getting user by sample"); List<User> entries = ldapEntryManager.findEntries(user, limit, limit); log.debug("Found '{}' entries", entries.size()); return entries; } public User addUserAttributeByUserInum(String userInum, String attributeName, String attributeValue) { log.debug("Add user attribute by user inum to LDAP: attributeName = '{}', attributeValue = '{}'", attributeName, attributeValue); User user = getUserByInum(userInum); if (user == null) { return null; } boolean result = addUserAttribute(user, attributeName, attributeValue); if (!result) { // We uses this result in Person Authentication Scripts addUserAttribute(user, attributeName, attributeValue); } return updateUser(user); } public User addUserAttribute(String userId, String attributeName, String attributeValue) { log.debug("Add user attribute to LDAP: attributeName = '{}', attributeValue = '{}'", attributeName, attributeValue); User user = getUser(userId); if (user == null) { // We uses this result in Person Authentication Scripts return null; } boolean result = addUserAttribute(user, attributeName, attributeValue); if (!result) { // We uses this result in Person Authentication Scripts return null; } return updateUser(user); } public boolean addUserAttribute(User user, String attributeName, String attributeValue) { CustomAttribute customAttribute = getCustomAttribute(user, attributeName); if (customAttribute == null) { customAttribute = new CustomAttribute(attributeName, attributeValue); user.getCustomAttributes().add(customAttribute); } else { List<String> currentAttributeValues = customAttribute.getValues(); List<String> newAttributeValues = new ArrayList<String>(); newAttributeValues.addAll(currentAttributeValues); if (newAttributeValues.contains(attributeValue)) { return false; } else { newAttributeValues.add(attributeValue); } customAttribute.setValues(newAttributeValues); } return true; } public User removeUserAttribute(String userId, String attributeName, String attributeValue) { log.debug("Remove user attribute from LDAP: attributeName = '{}', attributeValue = '{}'", attributeName, attributeValue); User user = getUser(userId); if (user == null) { return null; } CustomAttribute customAttribute = getCustomAttribute(user, attributeName); if (customAttribute != null) { List<String> currentAttributeValues = customAttribute.getValues(); if (currentAttributeValues.contains(attributeValue)) { List<String> newAttributeValues = new ArrayList<String>(); newAttributeValues.addAll(currentAttributeValues); if (currentAttributeValues.contains(attributeValue)) { newAttributeValues.remove(attributeValue); } else { return null; } customAttribute.setValues(newAttributeValues); } } return updateUser(user); } public User replaceUserAttribute(String userId, String attributeName, String oldAttributeValue, String newAttributeValue) { log.debug("Replace user attribute in LDAP: attributeName = '{}', oldAttributeValue = '{}', newAttributeValue = '{}'", attributeName, oldAttributeValue, newAttributeValue); User user = getUser(userId); if (user == null) { return null; } CustomAttribute customAttribute = getCustomAttribute(user, attributeName); if (customAttribute != null) { List<String> currentAttributeValues = customAttribute.getValues(); List<String> newAttributeValues = new ArrayList<String>(); newAttributeValues.addAll(currentAttributeValues); if (currentAttributeValues.contains(oldAttributeValue)) { newAttributeValues.remove(oldAttributeValue); } if (!newAttributeValues.contains(newAttributeValue)) { newAttributeValues.add(newAttributeValue); } customAttribute.setValues(newAttributeValues); } return updateUser(user); } public CustomAttribute getCustomAttribute(User user, String attributeName) { for (CustomAttribute customAttribute : user.getCustomAttributes()) { if (StringHelper.equalsIgnoreCase(attributeName, customAttribute.getName())) { return customAttribute; } } return null; } public void setCustomAttribute(User user, String attributeName, String attributeValue) { CustomAttribute customAttribute = getCustomAttribute(user, attributeName); if (customAttribute == null) { customAttribute = new CustomAttribute(attributeName); user.getCustomAttributes().add(customAttribute); } customAttribute.setValue(attributeValue); } // this method must be called only if app mode = MEMORY, in ldap case it's anyway persisted in ldap. public boolean saveLongLivedToken(String userId, PersistentJwt longLivedToken) { log.debug("Saving long-lived access token: userId = {}", userId); boolean succeed = false; User user = getUser(userId); if (user != null) { int nTokens = 0; if (user.getOxAuthPersistentJwt() != null) { nTokens = user.getOxAuthPersistentJwt().length; } nTokens++; String[] persistentJwts = new String[nTokens]; if (user.getOxAuthPersistentJwt() != null) { for (int i = 0; i < user.getOxAuthPersistentJwt().length; i++) { persistentJwts[i] = user.getOxAuthPersistentJwt()[i]; } } persistentJwts[nTokens - 1] = longLivedToken.toString(); user.setOxAuthPersistentJwt(persistentJwts); ldapEntryManager.merge(user); succeed = true; } return succeed; } public List<User> getUsersWithPersistentJwts() { String baseDN = staticConfiguration.getBaseDn().getPeople(); Filter filter = Filter.createPresenceFilter("oxAuthPersistentJWT"); return ldapEntryManager.findEntries(baseDN, User.class, filter); } public String getDnForUser(String inum) { String peopleDn = staticConfiguration.getBaseDn().getPeople(); if (StringHelper.isEmpty(inum)) { return peopleDn; } return String.format("inum=%s,%s", inum, peopleDn); } public String getUserInumByDn(String dn) { if (StringHelper.isEmpty(dn)) { return null; } String peopleDn = staticConfiguration.getBaseDn().getPeople(); if (!dn.toLowerCase().endsWith(peopleDn.toLowerCase())) { return null; } String firstDnPart = dn.substring(0, dn.length() - peopleDn.length()); String[] dnParts = firstDnPart.split(","); if (dnParts.length == 0) { return null; } String userInumPart = dnParts[dnParts.length - 1]; String[] userInumParts = userInumPart.split("="); if ((userInumParts.length == 2) && StringHelper.equalsIgnoreCase(userInumParts[0], "inum")) { return userInumParts[1]; } return null; } public String encodeGeneralizedTime(Date date) { return ldapEntryManager.encodeGeneralizedTime(date); } public Date decodeGeneralizedTime(String date) { return ldapEntryManager.decodeGeneralizedTime(date); } }
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import processing.app.syntax.*; import processing.app.tools.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import com.oroinc.text.regex.*; import com.apple.mrj.*; import gnu.io.*; public class Editor extends JFrame implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler, MRJOpenDocumentHandler //, MRJOpenApplicationHandler { // yeah static final String WINDOW_TITLE = "Arduino" + " - " + Base.VERSION_NAME; // p5 icon for the window Image icon; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered static public final String EMPTY = " " + " " + " "; static public final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); static final int HANDLE_NEW = 1; static final int HANDLE_OPEN = 2; static final int HANDLE_QUIT = 3; int checkModifiedMode; String handleOpenPath; boolean handleNewShift; boolean handleNewLibrary; EditorButtons buttons; EditorHeader header; EditorStatus status; EditorConsole console; JSplitPane splitPane; JPanel consolePanel; JLabel lineNumberComponent; // currently opened program public Sketch sketch; EditorLineStatus lineStatus; public JEditTextArea textarea; EditorListener listener; // runtime information and window placement Point appletLocation; //Point presentLocation; //Window presentationWindow; RunButtonWatcher watcher; Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; JMenu serialSubMenu; JMenu serialRateSubMenu; boolean running; boolean presenting; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; UndoManager undo; //static public UndoManager undo = new UndoManager(); // editor needs this guy //SketchHistory history; // TODO re-enable history Sketchbook sketchbook; //Preferences preferences; FindReplace find; //static Properties keywords; // keyword -> reference html lookup public Editor() { super(WINDOW_TITLE); // #@$*(@#$ apple.. always gotta think different MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); MRJApplicationUtils.registerOpenDocumentHandler(this); // run static initialization that grabs all the prefs Preferences.init(); // set the window icon try { icon = Base.getImage("icon.gif", this); setIconImage(icon); } catch (Exception e) { } // fail silently, no big whup // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleQuit(); } }); PdeKeywords keywords = new PdeKeywords(); sketchbook = new Sketchbook(this); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); // what platform has their help menu way on the right? motif? //menubar.add(Box.createHorizontalGlue()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); // doesn't matter when this is created, just make it happen at some point find = new FindReplace(Editor.this); Container pain = getContentPane(); pain.setLayout(new BorderLayout()); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); buttons = new EditorButtons(this); upper.add(buttons); header = new EditorHeader(this); //header.setBorder(null); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); //textarea.setTokenMarker(new PdeKeywords()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); //textarea, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(600, 600)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); /* // set the undo stuff for this feller Document document = textarea.getDocument(); //document.addUndoableEditListener(new PdeUndoableEditListener()); document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (undo != null) { //System.out.println(e.getEdit()); undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); */ } /** * Hack for #@#)$(* Mac OS X. * This appears to only be required on OS X 10.2, and this code * isn't even being hit on OS X 10.3 or Windows. */ public Dimension getMinimumSize() { //System.out.println("getting minimum size"); return new Dimension(500, 550); } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ public void restorePreferences() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } } else { windowPositionValid = false; } if (!windowPositionValid) { //System.out.println("using default size"); int windowH = Preferences.getInteger("default.window.height"); int windowW = Preferences.getInteger("default.window.width"); setBounds((screen.width - windowW) / 2, (screen.height - windowH) / 2, windowW, windowH); // this will be invalid as well, so grab the new value Preferences.setInteger("last.divider.location", splitPane.getDividerLocation()); } else { setBounds(Preferences.getInteger("last.window.x"), Preferences.getInteger("last.window.y"), Preferences.getInteger("last.window.width"), Preferences.getInteger("last.window.height")); } // last sketch that was in use, or used to launch the app if (Base.openedAtStartup != null) { handleOpen2(Base.openedAtStartup); } else { //String sketchName = Preferences.get("last.sketch.name"); String sketchPath = Preferences.get("last.sketch.path"); //Sketch sketchTemp = new Sketch(sketchPath); if ((sketchPath != null) && (new File(sketchPath)).exists()) { // don't check modified because nothing is open yet handleOpen2(sketchPath); } else { handleNew2(true); } } // location for the console/editor area divider int location = Preferences.getInteger("last.divider.location"); splitPane.setDividerLocation(location); // read the preferences that are settable in the preferences window applyPreferences(); } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); //beautifyMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Preferences.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Preferences.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location sketchbook.rebuildMenus(); } /** * Store preferences about the editor's current state. * Called when the application is quitting. */ public void storePreferences() { //System.out.println("storing preferences"); // window location information Rectangle bounds = getBounds(); Preferences.setInteger("last.window.x", bounds.x); Preferences.setInteger("last.window.y", bounds.y); Preferences.setInteger("last.window.width", bounds.width); Preferences.setInteger("last.window.height", bounds.height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); // last sketch that was in use //Preferences.set("last.sketch.name", sketchName); //Preferences.set("last.sketch.name", sketch.name); Preferences.set("last.sketch.path", sketch.getMainFilePath()); // location for the console/editor area divider int location = splitPane.getDividerLocation(); Preferences.setInteger("last.divider.location", location); } protected JMenu buildFileMenu() { JMenuItem item; JMenu menu = new JMenu("File"); /* menu.add(item = new JMenuItem("do the editor thing")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); } }); */ if (!Preferences.getBoolean("export.library")) { item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); } else { item = newJMenuItem("New Sketch", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); item = new JMenuItem("New Library"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNewLibrary(); } }); menu.add(item); } menu.add(sketchbook.getOpenMenu()); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(); } }); menu.add(saveMenuItem); saveAsMenuItem = newJMenuItem("Save As...", 'S', true); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); menu.add(saveAsMenuItem); item = newJMenuItem("Export", 'E'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(); } }); menu.add(item); exportAppItem = newJMenuItem("Export Application", 'E', true); exportAppItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExportApp(); } }); menu.add(exportAppItem); menu.addSeparator(); item = newJMenuItem("Page Setup", 'P', true); item.setEnabled(false); menu.add(item); item = newJMenuItem("Print", 'P'); item.setEnabled(false); menu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { menu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleQuit(); } }); menu.add(item); } return menu; } protected JMenu buildSketchMenu() { JMenuItem item; JMenu menu = new JMenu("Sketch"); item = newJMenuItem("Run", 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false); } }); menu.add(item); item = newJMenuItem("Present", 'R', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(true); } }); menu.add(item); item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.addFile(); } }); menu.add(item); menu.add(sketchbook.getImportMenu()); if (Base.isWindows() || Base.isMacOS()) { // no way to do an 'open in file browser' on other platforms // since there isn't any sort of standard item = new JMenuItem("Show Sketch Folder"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openFolder(sketchDir); Base.openFolder(sketch.folder); } }); menu.add(item); } // TODO re-enable history //history.attachMenu(menu); return menu; } // taken from an ancient version of processing class SerialMenuListener implements ActionListener { SerialMenuListener() {} public void actionPerformed(ActionEvent actionevent) { int count = serialSubMenu.getItemCount(); Object to; for (int i = 0; i < count; i++) { to = serialSubMenu.getItem(i); if ( to instanceof JCheckBoxMenuItem) ((JCheckBoxMenuItem)serialSubMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem)actionevent.getSource(); item.setState(true); String name = item.getLabel(); Preferences.set("serial.port", name); System.out.println("port set to " + name); } } // manages the serial port speed menu class SerialRateMenuListener implements ActionListener { SerialRateMenuListener() {} public void actionPerformed(ActionEvent actionevent) { int count = serialRateSubMenu.getItemCount(); Object to; for (int i = 0; i < count; i++) { to = serialRateSubMenu.getItem(i); if ( to instanceof JCheckBoxMenuItem) ((JCheckBoxMenuItem)serialRateSubMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem)actionevent.getSource(); item.setState(true); String name = item.getLabel(); Preferences.set("serial.download_rate", name); System.out.println("serial port speed set to " + name); } } protected JMenu buildToolsMenu() { JMenuItem item; JMenuItem rbMenuItem; JMenuItem cbMenuItem; SerialMenuListener sml = new SerialMenuListener(); SerialRateMenuListener srml = new SerialRateMenuListener(); // Enumeration portRates = {"9600","19200","38400","57600","115200"}; JMenu menu = new JMenu("Tools"); item = newJMenuItem("Auto Format", 'T', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new AutoFormat(Editor.this).show(); } }); menu.add(item); menu.addSeparator(); // The serial options serialSubMenu = new JMenu("Serial port"); item = newJMenuItem("Update List", 'E', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // if (debug) displayResult("Serial Port List Updated"); //updateSerial(); } }); ButtonGroup group = new ButtonGroup(); // getting list of ports try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(sml); group.add(rbMenuItem); serialSubMenu.add(rbMenuItem); } } } catch (Exception exception) { System.out.println("error retrieving port list"); exception.printStackTrace(); } if (serialSubMenu.getItemCount() == 0) { serialSubMenu.setEnabled(false); } serialSubMenu.addSeparator(); serialSubMenu.add(item); menu.add(serialSubMenu); // End of The serial options // menu.addSeparator(); // add the serial speed submenu serialRateSubMenu = new JMenu("Serial port speed"); serialSubMenu.add(item); //serialSubMenu.addSeparator(); group = new ButtonGroup(); int curr_rate = Preferences.getInteger("serial.download_rate"); rbMenuItem = new JCheckBoxMenuItem("9600", 9600 == curr_rate); rbMenuItem.addActionListener(srml); group.add(rbMenuItem); serialRateSubMenu.add(rbMenuItem); rbMenuItem = new JCheckBoxMenuItem("19200", 19200 == curr_rate); rbMenuItem.addActionListener(srml); group.add(rbMenuItem); serialRateSubMenu.add(rbMenuItem); rbMenuItem = new JCheckBoxMenuItem("115200", 115200 == curr_rate); rbMenuItem.addActionListener(srml); group.add(rbMenuItem); serialRateSubMenu.add(rbMenuItem); menu.add(serialRateSubMenu); return menu; } protected JMenu buildHelpMenu() { JMenu menu = new JMenu("Help"); JMenuItem item; item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "environment" + File.separator + "index.html"); } }); menu.add(item); item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "index.html"); } }); menu.add(item); item = newJMenuItem("Find in Reference", 'F', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { String text = textarea.getSelectedText(); if (text.length() == 0) { message("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile); } } } } }); menu.add(item); item = newJMenuItem("Visit arduino.berlios.de", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://arduino.berlios.de/"); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Arduino"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAbout(); } }); menu.add(item); } return menu; } public JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { find.show(); } }); menu.add(item); item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO find next should only be enabled after a // search has actually taken place find.find(true); } }); menu.add(item); return menu; } /** * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail people for writing the * sort of crappy api that would require a four line helper function * to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if (shift) modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { this.setEnabled(true); redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // interfaces for MRJ Handlers, but naming is fine // so used internally for everything else public void handleAbout() { final Image image = Base.getImage("about.jpg", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(this) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.show(); } /** * Show the preferences window. */ public void handlePrefs() { Preferences preferences = new Preferences(); preferences.showFrame(this); // since this can't actually block, it'll hide // the editor window while the prefs are open //preferences.showFrame(this); // and then call applyPreferences if 'ok' is hit // and then unhide // may need to rebuild sketch and other menus //applyPreferences(); // next have editor do its thing //editor.appyPreferences(); } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Called to update the text but not switch to a different * set of code (which would affect the undo manager). */ //public void setText(String what) { //, boolean discardUndo) { //setText(what, 0, 0); /** * Called to update the text but not switch to a different * set of code (which would affect the undo manager). */ public void setText(String what, int selectionStart, int selectionEnd) { textarea.setText(what); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking } /** * Called by Sketch when the tab is changed or a new set of files are opened. */ /* public void setText(String currentProgram, int selectionStart, int selectionEnd, UndoManager currentUndo) { //System.out.println("setting text, changing undo"); this.undo = null; //if (discardUndo) undo.discardAllEdits(); // don't set the undo object yet otherwise gets hokey textarea.setText(currentProgram); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking this.undo = currentUndo; undoAction.updateUndoState(); redoAction.updateRedoState(); } */ /* public void setDocument(SyntaxDocument document, int selectionStart, int selectionStop, int scrollPosition, UndoManager undo) { textarea.setDocument(document, selectionStart, selectionStop, scrollPosition); textarea.requestFocus(); // get the caret blinking this.undo = undo; undoAction.updateUndoState(); redoAction.updateRedoState(); } */ /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ public void setCode(SketchCode code) { if (code.document == null) { // this document not yet inited code.document = new SyntaxDocument(); // turn on syntax highlighting code.document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { code.document.insertString(0, code.program, null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager code.undo = new UndoManager(); // connect the undo listener to the editor code.document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } // update the document object that's in use textarea.setDocument(code.document, code.selectionStart, code.selectionStop, code.scrollPosition); textarea.requestFocus(); // get the caret blinking this.undo = code.undo; undoAction.updateUndoState(); redoAction.updateRedoState(); } public void handleRun(boolean present) { doClose(); running = true; buttons.run(); message("Compiling..."); // do this for the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to //if (Base.getBoolean("console.auto_clear", true)) { //if (Preferences.getBoolean("console.auto_clear", true)) { if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } presenting = present; if (presenting && Base.isMacOS()) { // check to see if osx 10.2, if so, show a warning String osver = System.getProperty("os.version").substring(0, 4); if (osver.equals("10.2")) { Base.showWarning("Time for an OS Upgrade", "The \"Present\" feature may not be available on\n" + "Mac OS X 10.2, because of what appears to be\n" + "a bug in the Java 1.4 implementation on 10.2.\n" + "In case it works on your machine, present mode\n" + "will start, but if you get a flickering white\n" + "window, using Command-Q to quit the sketch", null); } } try { if (!sketch.handleRun(new Target( System.getProperty("user.dir") + File.separator + "lib" + File.separator + "targets", Preferences.get("build.target")))) return; //runtime = new Runner(sketch, Editor.this); //runtime.start(appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); if(watcher != null) watcher.stop(); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } // this doesn't seem to help much or at all /* final SwingWorker worker = new SwingWorker() { public Object construct() { try { if (!sketch.handleRun()) return null; runtime = new Runner(sketch, Editor.this); runtime.start(presenting ? presentLocation : appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } return null; // needn't return anything } }; worker.start(); */ //sketch.cleanup(); // where does this go? buttons.clear(); } class RunButtonWatcher implements Runnable { Thread thread; public RunButtonWatcher() { thread = new Thread(this, "run button watcher"); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } public void run() { /* while (Thread.currentThread() == thread) { if (runtime == null) { stop(); } else { // FIXME remove dependance from core libs //if (runtime.applet != null) { // if (runtime.applet.finished) { // stop(); //} //buttons.running(!runtime.applet.finished); } else if (runtime.process != null) { //buttons.running(true); // ?? } else { stop(); } } try { Thread.sleep(250); } catch (InterruptedException e) { } //System.out.println("still inside runner thread"); } */ } public void stop() { buttons.running(false); thread = null; } } public void handleStop() { // called by menu or buttons if (presenting) { doClose(); } else { doStop(); } } /** * Stop the applet but don't kill its window. */ public void doStop() { if (runtime != null) runtime.stop(); if (watcher != null) watcher.stop(); message(EMPTY); // the buttons are sometimes still null during the constructor // is this still true? are people still hitting this error? /*if (buttons != null)*/ buttons.clear(); running = false; } /** * Stop the applet and kill its window. When running in presentation * mode, this will always be called instead of doStop(). */ public void doClose() { /* //if (presenting) { //presentationWindow.hide(); //} else { try { // the window will also be null the process was running // externally. so don't even try setting if window is null // since Runner will set the appletLocation when an // external process is in use. //if (runtime.window != null) { appletLocation = runtime.window.getLocation(); } } catch (NullPointerException e) { } //} //if (running) doStop(); doStop(); // need to stop if runtime error try { if (runtime != null) { runtime.close(); // kills the window runtime = null; // will this help? } } catch (Exception e) { } //buttons.clear(); // done by doStop */ sketch.cleanup(); // [toxi 030903] // focus the PDE again after quitting presentation mode toFront(); } /** * Check to see if there have been changes. If so, prompt user * whether or not to save first. If the user cancels, just ignore. * Otherwise, one of the other methods will handle calling * checkModified2() which will get on with business. */ protected void checkModified(int checkModifiedMode) { this.checkModifiedMode = checkModifiedMode; if (!sketch.modified) { checkModified2(); return; } String prompt = "Save changes to " + sketch.name + "? "; if (checkModifiedMode != HANDLE_QUIT) { // if the user is not quitting, then use the nicer // dialog that's actually inside the p5 window. status.prompt(prompt); } else { // if the user selected quit, then this has to be done with // a JOptionPane instead of internally in the editor. // TODO this is actually just a bug to be fixed. // macosx java kills the app even though cancel might get hit // so the cancel button is (temporarily) left off // this may be treated differently in macosx java 1.4, // but 1.4 isn't currently stable enough to use. // turns out windows has the same problem (sometimes) // disable cancel for now until a fix can be found. Object[] options = { "Yes", "No" }; int result = JOptionPane.showOptionDialog(this, prompt, "Quit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { handleSave(); checkModified2(); } else if (result == JOptionPane.NO_OPTION) { checkModified2(); // though this may just quit } else if (result == JOptionPane.CANCEL_OPTION) { // ignored } } } /** * Called by EditorStatus to complete the job and re-dispatch * to handleNew, handleOpen, handleQuit. */ public void checkModified2() { switch (checkModifiedMode) { case HANDLE_NEW: handleNew2(false); break; case HANDLE_OPEN: handleOpen2(handleOpenPath); break; case HANDLE_QUIT: handleQuit2(); break; } checkModifiedMode = 0; } /** * New was called (by buttons or by menu), first check modified * and if things work out ok, handleNew2() will be called. * * If shift is pressed when clicking the toolbar button, then * force the opposite behavior from sketchbook.prompt's setting */ public void handleNew(boolean shift) { doStop(); handleNewShift = shift; handleNewLibrary = false; checkModified(HANDLE_NEW); } /** * Extra public method so that Sketch can call this when a sketch * is selected to be deleted, and it won't call checkModified() * to prompt for save as. */ public void handleNewUnchecked() { doStop(); handleNewShift = false; handleNewLibrary = false; handleNew2(true); } /** * User selected "New Library", this will act just like handleNew * but internally set a flag that the new guy is a library, * meaning that a "library" subfolder will be added. */ public void handleNewLibrary() { doStop(); handleNewShift = false; handleNewLibrary = true; checkModified(HANDLE_NEW); } /** * Does all the plumbing to create a new project * then calls handleOpen to load it up. * * @param noPrompt true to disable prompting for the sketch * name, used when the app is starting (auto-create a sketch) */ protected void handleNew2(boolean noPrompt) { try { String pdePath = sketchbook.handleNew(noPrompt, handleNewShift, handleNewLibrary); if (pdePath != null) handleOpen2(pdePath); } catch (IOException e) { // not sure why this would happen, but since there's no way to // recover (outside of creating another new setkch, which might // just cause more trouble), then they've gotta quit. Base.showError("Problem creating a new sketch", "An error occurred while creating\n" + "a new sketch. Arduino must now quit.", e); } } /** * This is the implementation of the MRJ open document event, * and the Windows XP open document will be routed through this too. */ public void handleOpenFile(File file) { //System.out.println("handling open file: " + file); handleOpen(file.getAbsolutePath()); } /** * Open a sketch given the full path to the .pde file. * Pass in 'null' to prompt the user for the name of the sketch. */ public void handleOpen(String path) { if (path == null) { // "open..." selected from the menu path = sketchbook.handleOpen(); if (path == null) return; } doClose(); //doStop(); handleOpenPath = path; checkModified(HANDLE_OPEN); } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ public void handleOpenUnchecked(String path) { doClose(); handleOpen2(path); } /** * Second stage of open, occurs after having checked to * see if the modifications (if any) to the previous sketch * need to be saved. */ protected void handleOpen2(String path) { if (sketch != null) { // if leaving an empty sketch (i.e. the default) do an // auto-clean right away try { // don't clean if we're re-opening the same file String oldPath = sketch.code[0].file.getCanonicalPath(); String newPath = new File(path).getCanonicalPath(); if (!oldPath.equals(newPath)) { if (Base.calcFolderSize(sketch.folder) == 0) { Base.removeDir(sketch.folder); sketchbook.rebuildMenus(); } } } catch (Exception e) { } // oh well } try { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); File parentFile = new File(file.getParent()); String parentName = parentFile.getName(); String pdeName = parentName + ".pde"; File altFile = new File(file.getParent(), pdeName); //System.out.println("path = " + file.getParent()); //System.out.println("name = " + file.getName()); //System.out.println("pname = " + parentName); if (pdeName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // user selected a .java from the same sketch, // but open the .pde instead path = altFile.getAbsolutePath(); //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { Base.showWarning("Bad file selected", "Arduino can only open its own sketches\n" + "and other files ending in .pde", null); return; } else { String properParent = file.getName().substring(0, file.getName().length() - 4); Object[] options = { "OK", "Cancel" }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return; } if (!properFolder.mkdirs()) { throw new IOException("Couldn't create sketch folder"); } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); Base.copyFile(origPdeFile, properPdeFile); // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return; } } sketch = new Sketch(this, path); // TODO re-enable this once export application works exportAppItem.setEnabled(false); //exportAppItem.setEnabled(false && !sketch.isLibrary()); //buttons.disableRun(sketch.isLibrary()); header.rebuild(); if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } } catch (Exception e) { error(e); } } // there is no handleSave1 since there's never a need to prompt public void handleSave() { message("Saving..."); try { if (sketch.save()) { message("Done Saving."); } else { message(EMPTY); } // rebuild sketch menu in case a save-as was forced sketchbook.rebuildMenus(); } catch (Exception e) { // show the error as a message in the window error(e); // zero out the current action, // so that checkModified2 will just do nothing checkModifiedMode = 0; // this is used when another operation calls a save } buttons.clear(); } public void handleSaveAs() { doStop(); message("Saving..."); try { if (sketch.saveAs()) { message("Done Saving."); sketchbook.rebuildMenus(); } else { message("Save Cancelled."); } } catch (Exception e) { // show the error as a message in the window error(e); } buttons.clear(); } /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport() { //if(debugging) //doStop(); console.clear(); //String what = sketch.isLibrary() ? "Applet" : "Library"; //message("Exporting " + what + "..."); message("Uploading to I/O Board..."); try { //boolean success = sketch.isLibrary() ? //sketch.exportLibrary() : sketch.exportApplet(); boolean success = sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "lib" + File.separator + "targets", Preferences.get("build.target"))); if (success) { message("Done uploading."); } else { // error message will already be visible } } catch (RunnerException e) { message("Error during upload."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); } synchronized public void handleExportApp() { message("Arduino - Export - app"); } /** * Quit, but first ask user if it's ok. Also store preferences * to disk just in case they want to quit. Final exit() happens * in Editor since it has the callback from EditorStatus. */ public void handleQuit() { // doStop() isn't sufficient with external vm & quit // instead use doClose() which will kill the external vm doClose(); checkModified(HANDLE_QUIT); } /** * Actually do the quit action. */ protected void handleQuit2() { storePreferences(); Preferences.save(); sketchbook.clean(); //System.out.println("exiting here"); System.exit(0); } public void highlightLine(int lnum) { if (lnum < 0) { textarea.select(0, 0); return; } //System.out.println(lnum); String s = textarea.getText(); int len = s.length(); int st = -1; int ii = 0; int end = -1; int lc = 0; if (lnum == 0) st = 0; for (int i = 0; i < len; i++) { ii++; //if ((s.charAt(i) == '\n') || (s.charAt(i) == '\r')) { boolean newline = false; if (s.charAt(i) == '\r') { if ((i != len-1) && (s.charAt(i+1) == '\n')) { i++; } lc++; newline = true; } else if (s.charAt(i) == '\n') { lc++; newline = true; } if (newline) { if (lc == lnum) st = ii; else if (lc == lnum+1) { //end = ii; // to avoid selecting entire, because doing so puts the // cursor on the next line [0090] end = ii - 1; break; } } } if (end == -1) end = len; // sometimes KJC claims that the line it found an error in is // the last line in the file + 1. Just highlight the last line // in this case. [dmose] if (st == -1) st = len; textarea.select(st, end); } public void error(Exception e) { if (e == null) { System.err.println("Editor.error() was passed a null exception."); return; } // not sure if any RuntimeExceptions will actually arrive // through here, but gonna check for em just in case. String mess = e.getMessage(); if (mess != null) { String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } status.error(mess); } e.printStackTrace(); } public void error(RunnerException e) { //System.out.println("ERORROOROROR 2"); if (e.file >= 0) sketch.setCurrent(e.file); if (e.line >= 0) highlightLine(e.line); // remove the RuntimeException: message since it's not // really all that useful to the user //status.error(e.getMessage()); String mess = e.getMessage(); String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } status.error(mess); buttons.clearRun(); } /* public void finished() { running = false; buttons.clearRun(); message("Done."); } */ public void message(String msg) { status.notice(msg); } /* public void messageClear(String msg) { status.unnotice(msg); } */ /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //protected ReferenceKeys referenceItems = new ReferenceKeys(); String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem, copyItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); this.add(copyItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(referenceFile); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); referenceFile = PdeKeywords.getReference(textarea.getSelectedText()); if (referenceFile != null) { referenceItem.setEnabled(true); } } else { cutItem.setEnabled(false); copyItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } }
package de.hfu.studiportal; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import de.hfu.funfpunktnull.R; /** * Empty Activity to hold the {@link PreferencesFragment} * @author preussjan * @since 1.0 * @version 1.0 */ public class MainActivity extends DialogHostActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesFragment()).commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onResume() { super.onResume(); this.cancelProgressDialog(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_refresh) { new RefreshTask(this).execute(); return true; } return super.onOptionsItemSelected(item); } @Override public void showErrorDialog(final Exception e) { if(e instanceof NoChangeException) { //No change Toast.makeText(MainActivity.this, getResources().getString(R.string.text_no_change), Toast.LENGTH_SHORT).show(); }else { super.showErrorDialog(e); } } }
package com.examples.customtouch; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; public class MainActivity extends ListActivity implements OnItemClickListener { private static final String[] ITEMS = { "Move Logger Example", "Touch Listener Example", "Touch Delegate Example", "Touch Forward Example", "Pan Example", "Pan Gesture Example", "Multi-Touch Example", "Disable Touch Intercept"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ITEMS); getListView().setAdapter(adapter); getListView().setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: //Move Logger View startActivity(new Intent(this, MoveLoggerActivity.class)); break; case 1: //Touch Listener startActivity(new Intent(this, TouchListenerActivity.class)); break; case 2: //Touch Delegate startActivity(new Intent(this, TouchDelegateActivity.class)); break; case 3: //Touch Forwarding startActivity(new Intent(this, TouchForwardActivity.class)); break; case 4: //2D Scrolling startActivity(new Intent(this, TwoDimensionScrollActivity.class)); break; case 5: //2D GestureDetector Scrolling startActivity(new Intent(this, TwoDimensionGestureScrollActivity.class)); break; case 6: //Multi-Touch Image View startActivity(new Intent(this, MultitouchActivity.class)); break; case 7: //Disable Touch Intercept startActivity(new Intent(this, TouchInterceptActivity.class)); default: break; } } }
// $Id: Log.java,v 1.6 2002/04/09 05:13:28 mdb Exp $ // samskivert library - useful routines for java programs // 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.samskivert.util; /** * The log services provide debug, info and warning message logging * capabilities for a set of modules. These log services are designed to * provide the basic functionality needed by the samskivert codebase. It * is expected that the {@link LogProvider} interface will be used to * map these log services onto whatever more general purpose logging * framework is in use by the user of the samskivert codebase. * * <p> The log provider can be set via a system property to ensure that it * is in effect as soon as the log services are used. When invoking your * JVM, specify <code>-Dlog_provider=classname</code> and it will * automatically be instantiated and put into effect by the log services. * If your log provider needs more sophisticated configuration, you'll * have to instantiate it yourself and set it using {@link * #setLogProvider}. */ public final class Log { /** Log level constant for debug entries. */ public static final int DEBUG = 0; /** Log level constant for info entries. */ public static final int INFO = 1; /** Log level constant for warning entries. */ public static final int WARNING = 2; /** * Constructs a new log object with the supplied module name. */ public Log (String moduleName) { _moduleName = moduleName; } /** * Logs the specified message at the debug level if such messages are * enabled. */ public void debug (String message) { _provider.log(DEBUG, _moduleName, message); } /** * Logs the specified message at the info level if such messages are * enabled. */ public void info (String message) { _provider.log(INFO, _moduleName, message); } /** * Logs the specified message at the warning level if such messages * are enabled. */ public void warning (String message) { _provider.log(WARNING, _moduleName, message); } /** * Logs the stack trace of the supplied throwable at the specified * level (if the current log level for this module is at or below the * specified level). */ public void logStackTrace (int level, Throwable t) { _provider.logStackTrace(level, _moduleName, t); } /** * Sets the log level of the specified module to the specified * value. The log level indicates which messages are logged and which * are not. For example, if the level was set to warning, then only * warning and error messages would be logged because info and debug * messages have a 'lower' log level. * * <p/> Note: the log provider implementation may choose to propagate * the supplied level to all modules that are contained by this module * in the module hierarchy. For example, setting the "swing.util" * module to debug could also set the "swing.util.TaskMaster" level to * debug because it is contained by the specified module. */ public static void setLevel (String moduleName, int level) { _provider.setLevel(moduleName, level); } /** * Sets the log level for all modules to the specified level. */ public static void setLevel (int level) { _provider.setLevel(level); } /** * Instructs the logging services to use the specified log provider to * perform the actual logging. */ public static void setLogProvider (LogProvider provider) { _provider = provider; } /** * Checks the <code>log_provider</code> system property to see if a * log provider has been specified. Installs it if so. Checks the * <code>log_level</code> system property to see if a default log * level has been specified. Sets it if so. */ protected static void inferConfiguration () { // first set up our provider String provider = null; try { provider = System.getProperty("log_provider"); if (provider != null) { Class lpclass = Class.forName(provider); _provider = (LogProvider)lpclass.newInstance(); } } catch (SecurityException se) { // ignore security exceptions; we're just running in a JVM // that won't let us read system properties } catch (Exception e) { _provider.log(WARNING, "samskivert", "Error instantating log provider " + "[class=" + provider + ", error=" + e + "]."); } // now set our log level try { String level = System.getProperty("log_level"); if (level != null) { if (level.equalsIgnoreCase("debug")) { _provider.setLevel(DEBUG); } else if (level.equalsIgnoreCase("info")) { _provider.setLevel(INFO); } else if (level.equalsIgnoreCase("warning")) { _provider.setLevel(WARNING); } else { _provider.log(WARNING, "samskivert", "Unknown log level requested " + "[level=" + level + "]."); } } } catch (SecurityException se) { // ignore security exceptions; we're just running in a JVM // that won't let us read system properties } } /** The name of the module to which this log instance is associated. */ protected String _moduleName; /** The log provider currently in use by the log services. */ protected static LogProvider _provider = new DefaultLogProvider(); // read our configuration when the class is loaded static { inferConfiguration(); } }
package group3; import group2.Blob; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import global.Constant; public class MovingBlobDetection implements IMovingBlobDetection { Constant c = new Constant(); //list of all moving blobs that have been recently tracked private List<MovingBlob> movingBlobs; //maximum time before unmatched MovingBlob is deleted int maxTimeOffScreen = c.MAX_TIME_OFF_SCREEN; //maximum distance in pixels between blobs that can be matched int distanceLimitX = c.DISTANCE_LIMIT_X; int distanceLimitY = c.DISTANCE_LIMIT_Y; int widthChangeLimit = c.MAX_CHANGE_WIDTH; int heightChangeLimit = c.MAX_CHANGE_HEIGHT; //maximum distance between edges to unify int xEdgeDistanceLimit = c.X_EDGE_DISTANCE_LIMIT; int yEdgeDistanceLimit = c.Y_EDGE_DISTANCE_LIMIT; float xOverlapPercent = c.X_OVERLAP_PERCENT; float yOverlapPercent = c.Y_OVERLAP_PERCENT; //maximum difference in velocity to unify int unifyVelocityLimitX = c.UNIFY_VELOCITY_LIMIT_X; int unifyVelocityLimitY = c.UNIFY_VELOCITY_LIMIT_Y; float velocityLimitIncreaseX = c.VELOCITY_LIMIT_INCREASE_X; float velocityLimitIncreaseY = c.VELOCITY_LIMIT_INCREASE_Y; public MovingBlobDetection() { movingBlobs = new LinkedList<>(); } private float distBetweenBlobs(MovingBlob blob1,MovingBlob blob2){ float distanceX; float distanceY; if(blob1.x>blob2.x){ distanceX = blob1.x-(blob2.x+blob2.width); } else { distanceX = blob2.x-(blob1.x+blob1.width); } if(blob1.y>blob2.y){ distanceY = blob1.y-(blob2.y+blob2.height); } else { distanceY = blob2.y-(blob1.y+blob1.height); } distanceX = Math.max(0,distanceX); distanceY = Math.max(0,distanceY); float distanceVX = Math.abs(blob1.velocityX-blob2.velocityX); float distanceVY = Math.abs(blob1.velocityX-blob2.velocityY); return (float) Math.sqrt(distanceX*distanceX + distanceY*distanceY + distanceVX*distanceVX + distanceVY*distanceVY); } /* public List<MovingBlob> getUnifiedBlobs(List<MovingBlob> movingBlobs){ //pairs that should be unified HashSet<MovingBlob[]> pairs = new HashSet<>(); for(MovingBlob movingBlob1:movingBlobs){ for(MovingBlob movingBlob2:movingBlobs){ float distanceX; float distanceY; if(movingBlob1.x>movingBlob2.x){ distanceX = movingBlob1.x-(movingBlob2.x+movingBlob2.width); } else { distanceX = movingBlob2.x-(movingBlob1.x+movingBlob1.width); } if(movingBlob1.y>movingBlob2.y){ distanceY = movingBlob1.y-(movingBlob2.y+movingBlob2.height); } else { distanceY = movingBlob2.y-(movingBlob1.y+movingBlob1.height); } float velocityDifferenceX = Math.abs(movingBlob1.velocityX-movingBlob2.velocityX); float velocityDifferenceY = Math.abs(movingBlob1.velocityY-movingBlob2.velocityY); //checks if distance and velocity differences are under thresholds if(((distanceX<xEdgeDistanceLimit && distanceY<-yOverlapPercent*Math.min(movingBlob1.height, movingBlob2.height)) || (distanceY<yEdgeDistanceLimit && distanceX<-xOverlapPercent*Math.min(movingBlob1.width, movingBlob2.width)))&& velocityDifferenceX<unifyVelocityLimitX+ velocityLimitIncreaseX*Math.max(movingBlob1.velocityX, movingBlob2.velocityX) && velocityDifferenceY<unifyVelocityLimitY+ velocityLimitIncreaseY*Math.max(movingBlob1.velocityY, movingBlob2.velocityY)){ MovingBlob[] pair = {movingBlob1,movingBlob2}; pairs.add(pair); } } } HashMap<MovingBlob, HashSet<MovingBlob>> map = new HashMap<>(); for(MovingBlob[] pair:pairs){ MovingBlob blob1 = pair[0]; MovingBlob blob2 = pair[1]; HashSet<MovingBlob> set1 = map.get(blob1); HashSet<MovingBlob> set2 = map.get(blob2); if(set1==null&&set2==null){ HashSet<MovingBlob> newSet = new HashSet<>(); newSet.add(blob1); newSet.add(blob2); map.put(blob1, newSet); map.put(blob2, newSet); } else if(set1==null){ set2.add(blob1); map.put(blob1,set2); } else if(set2==null){ set1.add(blob2); map.put(blob2,set1); } else { set1.addAll(set2); map.put(blob2,set1); } } HashSet<MovingBlob> unifiedBlobSet = new HashSet<>(); for(HashSet<MovingBlob> blobSet:map.values()){ unifiedBlobSet.add(new UnifiedBlob(blobSet)); } for(MovingBlob blob:movingBlobs){ if(map.get(blob)==null) unifiedBlobSet.add(blob); } return new LinkedList<>(unifiedBlobSet); }*/ public List<MovingBlob> getUnifiedBlobs(List<MovingBlob> movingBlobs){ float[][] points = new float[movingBlobs.size()][4]; int index = 0; for(MovingBlob movingBlob:movingBlobs){ float[] point = {movingBlob.x, movingBlob.y, movingBlob.velocityX, movingBlob.velocityY}; while(distanceMoved > someValue){ point = shift(point, movingBlobs); } points[index] = point; index++; } } public float[] shift(float[] point, List<MovingBlob> movingBlobs){ float[] shift = {0,0,0,0}; } public List<MovingBlob> getMovingBlobs(List<Blob> blobList){ updateMovingBlobs(blobList); return movingBlobs; } private void updateMovingBlobs(List<Blob> blobList){ //set of unmatched movingblobs (all are unmatched at start of frame) HashSet<MovingBlob> movingBlobSet = new HashSet<>(getMovingBlobs()); //set of unmatched blobs HashSet<Blob> blobSet = new HashSet<>(blobList); //queue with shortest distance pairs of movingblobs and blobs in front PriorityQueue<BlobPair> queue = new PriorityQueue<>(); for(Blob blob:blobList){ for(MovingBlob movingBlob:getMovingBlobs()){ //creates pairs in queue of blobs & moving blobs with same color within 100 pixels if(blob.color.getColor()==movingBlob.color.getColor()){ float distanceX = Math.abs(movingBlob.predictedX-(blob.x+blob.width/2)); float distanceY = Math.abs(movingBlob.predictedY-(blob.y+blob.height/2)); float distance = (float)Math.sqrt(distanceX*distanceX+distanceY*distanceY); float widthChange = Math.abs(movingBlob.width-blob.width); float heightChange = Math.abs(movingBlob.height-blob.height); if(distanceX<=distanceLimitX && distanceY<=distanceLimitY && widthChange<=widthChangeLimit && heightChange<=heightChangeLimit){ queue.add(new BlobPair(distance, blob, movingBlob)); } } } } //matches closest pairs until it runs out of movingBlobs, blobs, or pairs while(!movingBlobSet.isEmpty()&&!blobSet.isEmpty()&&!queue.isEmpty()){ //finds shortest pair in queue BlobPair pair = queue.peek(); //checks if neither blobs are matched already if(movingBlobSet.contains(pair.oldBlob)&&blobSet.contains(pair.newBlob)){ //matches blobs and updates sets and queue matchBlob(pair.oldBlob, pair.newBlob); movingBlobSet.remove(pair.oldBlob); blobSet.remove(pair.newBlob); queue.remove(); } else { //if either blob is matched, removes pair from queue queue.remove(); } } //updates unmatched MovingBlobs for(MovingBlob movingBlob:movingBlobSet){ updateUnmatched(movingBlob); } //creates new MovingBlobs for unmatched blobs for(Blob blob:blobSet){ getMovingBlobs().add(new MovingBlob(blob)); } } private void matchBlob(MovingBlob movingBlob, Blob newBlob){ //update information based on new position calculateVelocity(movingBlob, newBlob); movingBlob.x = newBlob.x; movingBlob.y = newBlob.y; movingBlob.width = newBlob.width; movingBlob.height = newBlob.height; movingBlob.age++; movingBlob.ageOffScreen=0; movingBlob.updatePredictedPosition(); } private void updateUnmatched(MovingBlob movingBlob){ if(movingBlob.ageOffScreen>=maxTimeOffScreen){ //removes blob if it has been gone too long getMovingBlobs().remove(movingBlob); } else { //update position based on most recent velocity movingBlob.x += movingBlob.velocityX; movingBlob.y += movingBlob.velocityY; movingBlob.age++; movingBlob.ageOffScreen++; movingBlob.updatePredictedPosition(); } } private void calculateVelocity(MovingBlob movingBlob, Blob newBlob){ float centerXOld = movingBlob.x + movingBlob.width/2; float centerYOld = movingBlob.y + movingBlob.height/2; float centerXNew = newBlob.x + newBlob.width/2; float centerYNew = newBlob.y + newBlob.width/2; float movementX = centerXNew - centerXOld; float movementY = centerYNew - centerYOld; float tempVelX = movingBlob.velocityX; float tempVelY = movingBlob.velocityY; //finds average of previous velocity and velocity between last and current frame movingBlob.velocityX += movementX; movingBlob.velocityX /= 2; movingBlob.velocityChangeX = Math.abs(tempVelX-movingBlob.velocityX); //System.out.println("Velocity change x: " + movingBlob.velocityChangeX); movingBlob.velocityY += movementY; movingBlob.velocityY /= 2; movingBlob.velocityChangeY = Math.abs(tempVelY-movingBlob.velocityY); //System.out.println("Velocity change y: " + movingBlob.velocityChangeY); //System.out.println("new velY: " + movingBlob.velocityY); } public List<MovingBlob> getMovingBlobs() { return movingBlobs; } public void setMovingBlobs(List<MovingBlob> movingBlobs) { this.movingBlobs = movingBlobs; } }
package de.lmu.ifi.dbs.algorithm.clustering; import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.algorithm.Algorithm; import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.database.AssociationID; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.distance.DoubleDistance; import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction; import de.lmu.ifi.dbs.logging.ProgressLogRecord; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.preprocessing.ProjectedDBSCANPreprocessor; import de.lmu.ifi.dbs.utilities.Progress; import de.lmu.ifi.dbs.utilities.QueryResult; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Provides an abstract algorithm requiring a VarianceAnalysisPreprocessor. * * @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public abstract class ProjectedDBSCAN<P extends ProjectedDBSCANPreprocessor> extends AbstractAlgorithm<RealVector> implements Clustering<RealVector> { /** * Holds the class specific debug status. */ @SuppressWarnings({"UNUSED_SYMBOL"}) private static final boolean DEBUG = LoggingConfiguration.DEBUG; // private static final boolean DEBUG = true; /** * The logger of this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * Parameter for epsilon. */ public static final String EPSILON_P = DBSCAN.EPSILON_P; /** * Description for parameter epsilon. */ public static final String EPSILON_D = "<epsilon>the maximum radius of the neighborhood to be considered, must be suitable to " + LocallyWeightedDistanceFunction.class.getName(); /** * Parameter minimum points. */ public static final String MINPTS_P = DBSCAN.MINPTS_P; /** * Description for parameter minimum points. */ public static final String MINPTS_D = DBSCAN.MINPTS_D; /** * Epsilon. */ protected String epsilon; /** * Minimum points. */ protected int minpts; /** * Parameter lambda. */ public static final String LAMBDA_P = "lambda"; /** * Description for parameter lambda. */ public static final String LAMBDA_D = "<int>a positive integer specifiying the intrinsic dimensionality of clusters to be found."; /** * Keeps lambda. */ private int lambda; /** * Holds a list of clusters found. */ private List<List<Integer>> resultList; /** * Provides the result of the algorithm. */ private ClustersPlusNoise<RealVector> result; /** * Holds a set of noise. */ private Set<Integer> noise; /** * Holds a set of processed ids. */ private Set<Integer> processedIDs; /** * The distance function. */ private LocallyWeightedDistanceFunction distanceFunction = new LocallyWeightedDistanceFunction(); /** * Provides the abstract algorithm for variance analysis based DBSCAN. */ protected ProjectedDBSCAN() { super(); parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D); parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D); parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D); optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName()); } /** * @see AbstractAlgorithm#runInTime(Database) */ protected void runInTime(Database<RealVector> database) throws IllegalStateException { if (isVerbose()) { logger.info("\n"); } try { Progress progress = new Progress("Clustering", database.size()); resultList = new ArrayList<List<Integer>>(); noise = new HashSet<Integer>(); processedIDs = new HashSet<Integer>(database.size()); distanceFunction.setDatabase(database, isVerbose(), isTime()); if (isVerbose()) { logger.info("\nClustering:\n"); } if (database.size() >= minpts) { for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); if (!processedIDs.contains(id)) { expandCluster(database, id, progress); if (processedIDs.size() == database.size() && noise.size() == 0) { break; } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } } } else { for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); noise.add(id); if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } Integer[][] resultArray = new Integer[resultList.size() + 1][]; int i = 0; for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) { resultArray[i] = resultListIter.next().toArray(new Integer[0]); } resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]); result = new ClustersPlusNoise<RealVector>(resultArray, database); if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } } catch (Exception e) { throw new IllegalStateException(e); } } /** * ExpandCluster function of DBSCAN. */ protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) { List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction); if (DEBUG) { logger.fine("\nseeds of " + startObjectID + " " + database.getAssociation(AssociationID.LABEL, startObjectID) + " " + seeds.size()); } // neighbors < minPts OR local dimensionality > lambda -> noise if (seeds.size() < minpts || (Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) { noise.add(startObjectID); processedIDs.add(startObjectID); if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } return; } // try to expand the cluster List<Integer> currentCluster = new ArrayList<Integer>(); for (QueryResult<DoubleDistance> nextSeed : seeds) { Integer nextID = nextSeed.getID(); if (!processedIDs.contains(nextID)) { currentCluster.add(nextID); processedIDs.add(nextID); } else if (noise.contains(nextID)) { currentCluster.add(nextID); noise.remove(nextID); } if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } } seeds.remove(0); processedIDs.add(startObjectID); if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } while (seeds.size() > 0) { Integer o = seeds.remove(0).getID(); List<QueryResult<DoubleDistance>> neighborhood = database.rangeQuery(o, epsilon, distanceFunction); if (neighborhood.size() >= minpts && (Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, o) <= lambda) { for (QueryResult<DoubleDistance> neighbor : neighborhood) { Integer p = neighbor.getID(); boolean inNoise = noise.contains(p); boolean unclassified = !processedIDs.contains(p); if (inNoise || unclassified) { if (unclassified) { seeds.add(neighbor); } currentCluster.add(p); processedIDs.add(p); if (inNoise) { noise.remove(p); } } } } if (isVerbose()) { progress.setProcessed(processedIDs.size()); int numClusters = currentCluster.size() > minpts ? resultList.size() + 1 : resultList.size(); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, numClusters), progress.getTask(), progress.status())); } if (processedIDs.size() == database.size() && noise.size() == 0) { break; } } if (currentCluster.size() >= minpts) { resultList.add(currentCluster); } else { for (Integer id : currentCluster) { noise.add(id); } noise.add(startObjectID); processedIDs.add(startObjectID); } if (isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status())); } } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ public String[] setParameters (String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); epsilon = optionHandler.getOptionValue(EPSILON_P); try { // test whether epsilon is compatible with distance function distanceFunction.valueOf(epsilon); } catch (IllegalArgumentException e) { throw new WrongParameterValueException(EPSILON_P, epsilon, EPSILON_D); } // minpts String minptsString = optionHandler.getOptionValue(MINPTS_P); try { minpts = Integer.parseInt(minptsString); if (minpts <= 0) { throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D); } } catch (NumberFormatException e) { throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D, e); } // lambda String lambdaString = optionHandler.getOptionValue(LAMBDA_P); try { lambda = Integer.parseInt(lambdaString); if (lambda <= 0) { throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D); } } catch (NumberFormatException e) { throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D, e); } // parameters for the distance function String[] distanceFunctionParameters = new String[remainingParameters.length + 5]; System.arraycopy(remainingParameters, 0, distanceFunctionParameters, 5, remainingParameters.length); // omit preprocessing flag distanceFunctionParameters[0] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F; // preprocessor distanceFunctionParameters[1] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P; distanceFunctionParameters[2] = preprocessorClass().getName(); // preprocessor epsilon distanceFunctionParameters[3] = OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P; distanceFunctionParameters[4] = epsilon; distanceFunction.setParameters(distanceFunctionParameters); setParameters(args, remainingParameters); return remainingParameters; } /** * @see Algorithm#getAttributeSettings() */ @Override public List<AttributeSettings> getAttributeSettings () { List<AttributeSettings> attributeSettings = super.getAttributeSettings(); AttributeSettings mySettings = attributeSettings.get(0); mySettings.addSetting(LAMBDA_P, Integer.toString(lambda)); mySettings.addSetting(EPSILON_P, epsilon); mySettings.addSetting(MINPTS_P, Integer.toString(minpts)); attributeSettings.addAll(distanceFunction.getAttributeSettings()); return attributeSettings; } /** * Returns the class actually used as * {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}. * * @return the class actually used as * {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor} */ public abstract Class<P> preprocessorClass (); /** * @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult() */ public ClustersPlusNoise<RealVector> getResult () { return result; } }
package de.tu_darmstadt.gdi1.gorillas.ui.entitys; import de.tu_darmstadt.gdi1.gorillas.main.Gorillas; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; public class Skyscraper extends Entity{ private int height; private Color color; Skyscraper(int position){ x = position * Gorillas.FRAME_WIDTH; height = (int) (Math.random() * 450 + 50); y = Gorillas.FRAME_HEIGHT - height; color = new Color((int)(Math.random()*65536)); } public int getHeigth(){ return height; } @Override public void render(Graphics graph) { graph.setColor(color); graph.drawRect(x, y, Gorillas.FRAME_WIDTH / 6, height); } @Override public void update(int delta) { //TODO: Explosionen } }
package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.templates.DisableNotifable; import edu.wpi.first.wpilibj.templates.RobotMain; import edu.wpi.first.wpilibj.templates.debugging.DebugInfo; import edu.wpi.first.wpilibj.templates.debugging.DebugInfoGroup; import edu.wpi.first.wpilibj.templates.debugging.DebugLevel; import edu.wpi.first.wpilibj.templates.debugging.DebugOutput; import edu.wpi.first.wpilibj.templates.debugging.DebugStatus; import edu.wpi.first.wpilibj.templates.debugging.Debuggable; import edu.wpi.first.wpilibj.templates.debugging.InfoState; import edu.wpi.first.wpilibj.templates.debugging.RobotDebugger; import edu.wpi.first.wpilibj.templates.variablestores.DashboardStore; import edu.wpi.first.wpilibj.templates.vstj.VstJ; /** * This Command runs the climber motors (The ones powering the "cart" that goes * up/down the ladder) according to a set speed, that is increased/decreased * with buttons. * * Same kind of drive as RunShooterMotors, but with different buttons. */ public class RunClimber extends CommandBase implements Debuggable, DisableNotifable { private boolean limitSwitchEnabled = false; private double speed = 0; private boolean lowerPressed; private boolean upperPressed; /** * False is going down, true is going up. */ private boolean lastAutoState = false; public RunClimber() { requires(climber); requires(climberLimitSwitch); DashboardStore.initIsClimberEnabled(); DashboardStore.initIsClimberAuto(); } protected void initialize() { RobotMain.addDisableNotifable(this); climber.stop(); } protected void execute() { checkLimitSwitch(); runClimber(); RobotDebugger.push(this); RobotDebugger.push(climber); RobotDebugger.push(climberLimitSwitch); } private void runClimber() { if (DashboardStore.getIsClimberEnabled()) { if (DashboardStore.getIsClimberAuto()) { if (upperPressed) { lastAutoState = false; } else if (lowerPressed) { lastAutoState = true; } speed = lastAutoState ? 0.8 : -0.8; } else { speed = VstJ.getLadderControlAxisValue() - 0.1; if (upperPressed && speed > 0) { speed = 0; } if (lowerPressed && speed < 0) { speed = 0; } } } else { speed = 0; } climber.runLadder(speed); } protected boolean isFinished() { return false; } protected void end() { climber.stop(); speed = 0; RobotDebugger.push(this); RobotDebugger.push(climber); RobotDebugger.push(climberLimitSwitch); } protected void interrupted() { this.end(); } private void checkLimitSwitch() { if (limitSwitchEnabled) { upperPressed = climberLimitSwitch.readUpper(); lowerPressed = climberLimitSwitch.readLower(); } else { upperPressed = false; lowerPressed = false; } } public DebugOutput getStatus() { DebugInfo[] infoList = new DebugInfo[3]; infoList[0] = new InfoState("Climber:Enabled", DashboardStore.getIsClimberEnabled() ? "Yes" : "No", DebugLevel.HIGHEST); infoList[0] = new InfoState("Climber:Mode", DashboardStore.getIsClimberAuto() ? "Auto" : "Manual", DebugLevel.HIGHEST); infoList[1] = new DebugStatus("Climber:SetSpeed", speed, DebugLevel.LOW); infoList[2] = new DebugStatus("ClimberLimitSwitch:Enabled", limitSwitchEnabled, DebugLevel.LOW); return new DebugInfoGroup(infoList); } public void disable() { speed = 0; RobotDebugger.push(this); RobotDebugger.push(climber); RobotDebugger.push(climberLimitSwitch); } }
package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.Color; import java.awt.Dimension; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.SwingUtilities; import es.ucm.fdi.tp.basecode.bgame.control.Controller; import es.ucm.fdi.tp.basecode.bgame.control.Player; import es.ucm.fdi.tp.basecode.bgame.model.Board; import es.ucm.fdi.tp.basecode.bgame.model.Game.State; import es.ucm.fdi.tp.basecode.bgame.model.GameObserver; import es.ucm.fdi.tp.basecode.bgame.model.Piece; import es.ucm.fdi.tp.views.swing.SwingView; import es.ucm.fdi.tp.views.swing.controlpanel.colorchooser.ColorChooserPane; import es.ucm.fdi.tp.views.swing.controlpanel.textbox.MessagesBox; public final class ControlPanel extends JPanel implements GameObserver { private static final long serialVersionUID = -5012854304785344947L; final private Controller cntrl; final private SwingView view; final private Map<Piece,SwingView.PlayerMode> playerModes; final private Map<Piece,Color> playerColors; private final Player randPlayer; private final Player aiPlayer; private final Piece WINDOW_OWNER; /** * Text area where messages eare shown. * Needed to add messages from the outside. */ private MessagesBox messagesBox; /** * Table where players information is displayed. * Needed to add it as observer to the color chooser. */ private PlayersInfoTable infoTable; /** * Enables the user to change players' colors. * Needed to add observers to it on color change. */ private ColorChooserPane colorChooser; /** * Enables the user to change players' modes. * Needed to add observers to it on mode change. */ private PlayerModesPane playerModesPanel; private LinkedList<GameObserver> internalObservers = new LinkedList<GameObserver>(); public ControlPanel(Controller c, SwingView v, Map<Piece,SwingView.PlayerMode> playerModes, Map<Piece, Color> playerColors, Player randPlayer, Player aiPlayer) { this.cntrl = c; this.view = v; this.playerModes = playerModes; this.playerColors = playerColors; this.WINDOW_OWNER = view.getWindowOwner(); this.randPlayer = randPlayer; this.aiPlayer = aiPlayer; initGUI(); } /** * show the message * @param m : text of the message */ public void showMessage(String m) { if(m != null) this.messagesBox.append(m); else this.messagesBox.setText(null); } /** * build right panel, the control panel, add modules */ private void initGUI() { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); addMessagesBox(); addPlayerInfoTable(); addColorChangePane(); addPlayerModesPane(); addAutoMovesPane(); addExitPane(); colorChooser.addObserver(this.infoTable); colorChooser.addObserver(this.view); playerModesPanel.addObserver(this.infoTable); playerModesPanel.addObserver(this.view); } private void addMessagesBox() { messagesBox = new MessagesBox(); this.add(messagesBox); } private void addPlayerInfoTable(){ this.infoTable = new PlayersInfoTable(playerColors, playerModes, WINDOW_OWNER); /*infoTable.setMaximumSize( new Dimension(Integer.MAX_VALUE, infoTable.getHeight()));*/ this.add(infoTable); this.internalObservers.add(infoTable); } private void addColorChangePane() { this.colorChooser = new ColorChooserPane(playerColors); colorChooser.setMaximumSize( new Dimension(Integer.MAX_VALUE, colorChooser.getHeight())); this.add(colorChooser); this.internalObservers.add(colorChooser); } private void addPlayerModesPane() { byte mode = PlayerModesPane.MANUAL_ONLY; if(randPlayer != null && aiPlayer != null) mode = PlayerModesPane.MANUAL_RANDOM_AI; else if(randPlayer != null) mode = PlayerModesPane.MANUAL_RANDOM; else if(aiPlayer != null) mode = PlayerModesPane.MANUAL_AI; this.playerModesPanel = new PlayerModesPane(playerModes, mode, WINDOW_OWNER); playerModesPanel.setMaximumSize( new Dimension(Integer.MAX_VALUE, playerModesPanel.getHeight())); if(randPlayer != null || aiPlayer != null) { this.add(playerModesPanel); this.internalObservers.add(playerModesPanel); } } private void addAutoMovesPane() { AutomaticMoves autoMovesPane = new AutomaticMoves(cntrl, randPlayer, aiPlayer, WINDOW_OWNER); if(randPlayer != null || aiPlayer != null) { autoMovesPane.setMaximumSize( new Dimension(Integer.MAX_VALUE, autoMovesPane.getHeight())); this.add(autoMovesPane); this.internalObservers.add(autoMovesPane); } } private void addExitPane() { ExitPanel exit = new ExitPanel(this.view); exit.setMaximumSize( new Dimension(Integer.MAX_VALUE, exit.getHeight())); this.add(exit); this.internalObservers.add(exit); } @Override public void onGameStart(final Board board, final String gameDesc, final List<Piece> pieces, final Piece turn) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleGameStart(board, gameDesc, pieces, turn); } }); } private void handleGameStart(Board board, String gameDesc, List<Piece> pieces, Piece turn) { messagesBox.setText("Game started: " + gameDesc); messagesBox.append(buildTurnString(turn)); notifyGameStart(board, gameDesc, pieces, turn); } private void notifyGameStart(Board board, String gameDesc, List<Piece> pieces, Piece turn) { for(GameObserver o : internalObservers) { o.onGameStart(board, gameDesc, pieces, turn); } } @Override public void onGameOver(final Board board, final State state, final Piece winner) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleGameOver(board, state, winner); } }); } private void handleGameOver(Board board, State state, Piece winner) { messagesBox.append("Game over: " + state); if(state == State.Draw) { messagesBox.append("Draw"); } else if(state == State.Won) { if(winner.equals(WINDOW_OWNER)) { messagesBox.append("You won"); } else { messagesBox.append("The winner is: " + winner); } } notifyGameOver(board, state, winner); } private void notifyGameOver(Board board, State state, Piece winner) { for(GameObserver o : internalObservers) { o.onGameOver(board, state, winner); } } @Override public void onMoveStart(final Board board, final Piece turn) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleMoveStart(board, turn); } }); } private void handleMoveStart(Board board, Piece turn) { notifyMoveStart(board, turn); } private void notifyMoveStart(Board board, Piece turn) { for(GameObserver o : internalObservers) { o.onMoveStart(board, turn); } } @Override public void onMoveEnd(final Board board, final Piece turn, final boolean success) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleMoveEnd(board, turn, success); } }); } private void handleMoveEnd(Board board, Piece turn, boolean success) { notifyMoveEnd(board, turn, success); } private void notifyMoveEnd(Board board, Piece turn, boolean success) { for(GameObserver o : internalObservers) { o.onMoveEnd(board, turn, success); } } @Override public void onChangeTurn(final Board board, final Piece turn) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleChangeTurn(board, turn); } }); } private void handleChangeTurn(Board board, Piece turn) { messagesBox.append(buildTurnString(turn)); notifyChangeTurn(board, turn); } private void notifyChangeTurn(Board board, Piece turn) { for(GameObserver o : internalObservers) { o.onChangeTurn(board, turn); } } @Override public void onError(String msg) { //Errors are not welcome here! } /** * Builds a String with the turn. */ private String buildTurnString(Piece turn) { if(turn.equals(WINDOW_OWNER)) { return "Your turn!"; } else { return "Turn for " + turn; } } }
package eu.livotov.labs.android.robotools.net; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import eu.livotov.labs.android.robotools.crypt.RTBase64; import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.impl.cookie.BasicClientCookie; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RTCookieStore implements CookieStore { private static final String CS_KEY = "robotools.net.cstore"; private List<Cookie> cookies = new ArrayList<Cookie>(); public RTCookieStore() { } public void addCookie(final Cookie cookie) { cookies.add(cookie); } public List<Cookie> getCookies() { return cookies; } public Cookie getCookie(final String key) { clearExpired(new Date(System.currentTimeMillis())); for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase(key)) { return cookie; } } return null; } public boolean clearExpired(final Date date) { List<Cookie> toExpire = new ArrayList<Cookie>(); for (Cookie cookie : cookies) { if (cookie.isExpired(date)) { toExpire.add(cookie); } } if (toExpire.size() > 0) { cookies.removeAll(toExpire); toExpire.clear(); return true; } return false; } public void clear() { cookies.clear(); } public void saveCookieStore(final Context ctx) throws IOException { final List<Cookie> serialisableCookies = new ArrayList<Cookie>(cookies.size()); for (Cookie cookie : cookies) { serialisableCookies.add(new SerializableCookie(cookie)); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(serialisableCookies); oos.flush(); oos.close(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); SharedPreferences.Editor editor = preferences.edit(); editor.putString(CS_KEY, RTBase64.encodeToString(bos.toByteArray(), RTBase64.DEFAULT)); editor.commit(); } public void readCookieStore(final Context ctx) { try { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); ByteArrayInputStream bis = new ByteArrayInputStream(RTBase64.decode(preferences.getString(CS_KEY, ""), RTBase64.DEFAULT)); ObjectInputStream ois = new ObjectInputStream(bis); List<Cookie> restoredCookies = (ArrayList<Cookie>) ois.readObject(); ois.close(); cookies.clear(); cookies.addAll(restoredCookies); } catch (Throwable err) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); SharedPreferences.Editor editor = preferences.edit(); editor.remove(CS_KEY); editor.commit(); err.printStackTrace(); } } public class SerializableCookie implements Cookie, Externalizable { private static final int NAME = 0x01; private static final int VALUE = 0x02; private static final int COMMENT = 0x04; private static final int COMMENT_URL = 0x08; private static final int EXPIRY_DATE = 0x10; private static final int DOMAIN = 0x20; private static final int PATH = 0x40; private static final int PORTS = 0x80; private transient int nullMask = 0; private transient Cookie cookie; public SerializableCookie() { super(); } public SerializableCookie(final Cookie cookie) { super(); this.cookie = cookie; } public String getName() { return cookie.getName(); } public String getValue() { return cookie.getValue(); } public String getComment() { return cookie.getComment(); } public String getCommentURL() { return cookie.getCommentURL(); } public Date getExpiryDate() { return cookie.getExpiryDate(); } public boolean isPersistent() { return cookie.isPersistent(); } public String getDomain() { return cookie.getDomain(); } public String getPath() { return cookie.getPath(); } public int[] getPorts() { return cookie.getPorts(); } public boolean isSecure() { return cookie.isSecure(); } public int getVersion() { return cookie.getVersion(); } public boolean isExpired(final Date date) { return cookie.isExpired(date); } public void writeExternal(final ObjectOutput out) throws IOException { nullMask |= (getName() == null) ? NAME : 0; nullMask |= (getValue() == null) ? VALUE : 0; nullMask |= (getComment() == null) ? COMMENT : 0; nullMask |= (getCommentURL() == null) ? COMMENT_URL : 0; nullMask |= (getExpiryDate() == null) ? EXPIRY_DATE : 0; nullMask |= (getDomain() == null) ? DOMAIN : 0; nullMask |= (getPath() == null) ? PATH : 0; nullMask |= (getPorts() == null) ? PORTS : 0; out.writeInt(nullMask); if ((nullMask & NAME) == 0) { out.writeUTF(getName()); } if ((nullMask & VALUE) == 0) { out.writeUTF(getValue()); } if ((nullMask & COMMENT) == 0) { out.writeUTF(getComment()); } if ((nullMask & COMMENT_URL) == 0) { out.writeUTF(getCommentURL()); } if ((nullMask & EXPIRY_DATE) == 0) { out.writeLong(getExpiryDate().getTime()); } out.writeBoolean(isPersistent()); if ((nullMask & DOMAIN) == 0) { out.writeUTF(getDomain()); } if ((nullMask & PATH) == 0) { out.writeUTF(getPath()); } if ((nullMask & PORTS) == 0) { out.writeInt(getPorts().length); for (int p : getPorts()) { out.writeInt(p); } } out.writeBoolean(isSecure()); out.writeInt(getVersion()); } public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { nullMask = in.readInt(); String name = null; String value = null; String comment = null; String commentURL = null; Date expiryDate = null; boolean isPersistent = false; String domain = null; String path = null; int[] ports = null; boolean isSecure = false; int version = 0; if ((nullMask & NAME) == 0) { name = in.readUTF(); } if ((nullMask & VALUE) == 0) { value = in.readUTF(); } if ((nullMask & COMMENT) == 0) { comment = in.readUTF(); } if ((nullMask & COMMENT_URL) == 0) { commentURL = in.readUTF(); } if ((nullMask & EXPIRY_DATE) == 0) { expiryDate = new Date(in.readLong()); } isPersistent = in.readBoolean(); if ((nullMask & DOMAIN) == 0) { domain = in.readUTF(); } if ((nullMask & PATH) == 0) { path = in.readUTF(); } if ((nullMask & PORTS) == 0) { final int len = in.readInt(); ports = new int[len]; for (int i = 0; i < len; i++) { ports[i] = in.readInt(); } } isSecure = in.readBoolean(); version = in.readInt(); final BasicClientCookie bc = new BasicClientCookie(name, value); bc.setComment(comment); bc.setDomain(domain); bc.setExpiryDate(expiryDate); bc.setPath(path); bc.setSecure(isSecure); bc.setVersion(version); this.cookie = bc; } @Override public String toString() { if (cookie == null) { return "null"; } else { return cookie.toString(); } } } }
package fitnesse.responders.refactoring; import fitnesse.FitNesseContext; import fitnesse.Responder; import fitnesse.authentication.AlwaysSecureOperation; import fitnesse.authentication.SecureOperation; import fitnesse.components.PageReferenceRenamer; import fitnesse.html.HtmlUtil; import fitnesse.http.Request; import fitnesse.http.Response; import fitnesse.http.SimpleResponse; import fitnesse.responders.ErrorResponder; import fitnesse.responders.NotFoundResponder; import fitnesse.responders.SecureResponder; import fitnesse.wiki.*; import fitnesse.wikitext.widgets.WikiWordWidget; import java.util.Iterator; import java.util.List; public class RenamePageResponder implements SecureResponder { private String qualifiedName; private String newName; private boolean refactorReferences; private WikiPagePath pathToRename; private WikiPage pageToRename; private WikiPage root; private WikiPage parentOfPageToRename; public Response makeResponse(FitNesseContext context, Request request) throws Exception { root = context.root; qualifiedName = request.getResource(); newName = (String) request.getInput("newName"); refactorReferences = request.hasInput("refactorReferences"); Response response; if(newName != null && !qualifiedName.equals("FrontPage") && WikiWordWidget.isSingleWikiWord(newName)) { PageCrawler pageCrawler = context.root.getPageCrawler(); pathToRename = PathParser.parse(qualifiedName); pageToRename = pageCrawler.getPage(context.root, pathToRename); if(pageToRename == null) response = new NotFoundResponder().makeResponse(context, request); else { WikiPagePath parentPath = pathToRename.parentPath(); parentOfPageToRename = pageCrawler.getPage(context.root, parentPath); final boolean pageExists = pageCrawler.pageExists(parentOfPageToRename, PathParser.parse(newName)); if(!pageExists) { qualifiedName = renamePageAndMaybeAllReferences(); response = new SimpleResponse(); response.redirect(qualifiedName); } else // already exists { response = makeErrorMessageResponder(makeLink(newName) + " already exists").makeResponse(context, request); } } } else { response = makeErrorMessageResponder(newName + " is not a valid simple page name.").makeResponse(context, request); } return response; } private Responder makeErrorMessageResponder(String message) throws Exception { return new ErrorResponder("Cannot rename " + makeLink(qualifiedName) + " to " + newName + "<br>" + message); } private String makeLink(String page) throws Exception { return HtmlUtil.makeLink(page, page).html(); } private String renamePageAndMaybeAllReferences() throws Exception { if(refactorReferences) renameReferences(); renamePage(); pathToRename.removeNameFromEnd(); pathToRename.addNameToEnd(newName); return PathParser.render(pathToRename); } private void renameReferences() throws Exception { PageReferenceRenamer renamer = new PageReferenceRenamer(root); renamer.renameReferences(pageToRename, newName); } private boolean renamePage() throws Exception { String oldName = pageToRename.getName(); if(parentOfPageToRename.hasChildPage(oldName) && !parentOfPageToRename.hasChildPage(newName)) { WikiPage originalPage = parentOfPageToRename.getChildPage(oldName); PageCrawler crawler = originalPage.getPageCrawler(); PageData data = originalPage.getData(); WikiPage renamedPage = parentOfPageToRename.addChildPage(newName); renamedPage.commit(data); List children = originalPage.getChildren(); for(Iterator iterator = children.iterator(); iterator.hasNext();) { WikiPage child = (WikiPage) iterator.next(); MovePageResponder.movePage(root, crawler.getFullPath(child), crawler.getFullPath(renamedPage)); } parentOfPageToRename.removeChildPage(oldName); return true; } return false; } public SecureOperation getSecureOperation() { return new AlwaysSecureOperation(); } }
package org.teiid.jboss; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.ModelController; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.teiid.adminapi.AdminProcessingException; import org.teiid.adminapi.Model; import org.teiid.adminapi.Translator; import org.teiid.adminapi.VDB.Status; import org.teiid.adminapi.impl.ModelMetaData; import org.teiid.adminapi.impl.ModelMetaData.Message.Severity; import org.teiid.adminapi.impl.VDBMetaData; import org.teiid.adminapi.impl.VDBMetadataParser; import org.teiid.adminapi.impl.VDBTranslatorMetaData; import org.teiid.common.buffer.BufferManager; import org.teiid.core.TeiidException; import org.teiid.deployers.*; import org.teiid.dqp.internal.datamgr.ConnectorManager; import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository; import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository.ConnectorManagerException; import org.teiid.dqp.internal.datamgr.TranslatorRepository; import org.teiid.jboss.rest.ResteasyEnabler; import org.teiid.logging.LogConstants; import org.teiid.logging.LogManager; import org.teiid.metadata.Datatype; import org.teiid.metadata.MetadataFactory; import org.teiid.metadata.MetadataRepository; import org.teiid.metadata.MetadataStore; import org.teiid.metadata.index.IndexMetadataRepository; import org.teiid.query.ObjectReplicator; import org.teiid.query.QueryPlugin; import org.teiid.query.metadata.VDBResources; import org.teiid.query.tempdata.GlobalTableStore; import org.teiid.runtime.AbstractVDBDeployer; import org.teiid.translator.DelegatingExecutionFactory; import org.teiid.translator.ExecutionFactory; import org.teiid.translator.TranslatorException; class VDBService extends AbstractVDBDeployer implements Service<RuntimeVDB> { private VDBMetaData vdb; private RuntimeVDB runtimeVDB; protected final InjectedValue<VDBRepository> vdbRepositoryInjector = new InjectedValue<VDBRepository>(); protected final InjectedValue<TranslatorRepository> translatorRepositoryInjector = new InjectedValue<TranslatorRepository>(); protected final InjectedValue<Executor> executorInjector = new InjectedValue<Executor>(); protected final InjectedValue<ObjectSerializer> serializerInjector = new InjectedValue<ObjectSerializer>(); protected final InjectedValue<BufferManager> bufferManagerInjector = new InjectedValue<BufferManager>(); protected final InjectedValue<ObjectReplicator> objectReplicatorInjector = new InjectedValue<ObjectReplicator>(); protected final InjectedValue<VDBStatusChecker> vdbStatusCheckInjector = new InjectedValue<VDBStatusChecker>(); // for REST deployment protected final InjectedValue<ModelController> controllerValue = new InjectedValue<ModelController>(); private VDBLifeCycleListener vdbListener; private VDBLifeCycleListener restEasyListener; private VDBResources vdbResources; private ContainerLifeCycleListener shutdownListener; public VDBService(VDBMetaData metadata, VDBResources vdbResources, ContainerLifeCycleListener shutdownListener) { this.vdb = metadata; this.vdbResources = vdbResources; this.shutdownListener = shutdownListener; } @Override public void start(final StartContext context) throws StartException { ConnectorManagerRepository cmr = new ConnectorManagerRepository(); TranslatorRepository repo = new TranslatorRepository(); this.vdb.addAttchment(TranslatorRepository.class, repo); // check if this is a VDB with index files, if there are then build the TransformationMetadata UDFMetaData udf = this.vdb.getAttachment(UDFMetaData.class); // add required connector managers; if they are not already there for (Translator t: this.vdb.getOverrideTranslators()) { VDBTranslatorMetaData data = (VDBTranslatorMetaData)t; String type = data.getType(); VDBTranslatorMetaData parent = getTranslatorRepository().getTranslatorMetaData(type); data.setModuleName(parent.getModuleName()); data.addAttchment(ClassLoader.class, parent.getAttachment(ClassLoader.class)); data.setParent(parent); repo.addTranslatorMetadata(data.getName(), data); } createConnectorManagers(cmr, repo, this.vdb); final ServiceBuilder<Void> vdbService = addVDBFinishedService(context); this.vdbListener = new VDBLifeCycleListener() { @Override public void added(String name, int version, CompositeVDB cvdb, boolean reloading) { } @Override public void beforeRemove(String name, int version, CompositeVDB cvdb) { } @Override public void removed(String name, int version, CompositeVDB cvdb) { } @Override public void finishedDeployment(String name, int version, CompositeVDB cvdb, boolean reloading) { if (!name.equals(VDBService.this.vdb.getName()) || version != VDBService.this.vdb.getVersion()) { return; } //clear out the indexmetadatarepository as it holds state that is no longer necessary repositories.put("index", new IndexMetadataRepository()); //$NON-NLS-1$ VDBMetaData vdbInstance = cvdb.getVDB(); if (vdbInstance.getStatus().equals(Status.ACTIVE)) { // add object replication to temp/matview tables GlobalTableStore gts = CompositeGlobalTableStore.createInstance(cvdb, getBuffermanager(), objectReplicatorInjector.getValue()); vdbInstance.addAttchment(GlobalTableStore.class, gts); vdbService.install(); } } }; getVDBRepository().addListener(this.vdbListener); this.restEasyListener = new ResteasyEnabler(this.vdb.getName(), this.vdb.getVersion(), controllerValue.getValue(), executorInjector.getValue(), shutdownListener); getVDBRepository().addListener(this.restEasyListener); MetadataStore store = new MetadataStore(); try { //check to see if there is an index file. if there is then we assume //that index is the default metadata repo MetadataRepository<?, ?> defaultRepo = null; for (String s : this.vdbResources.getEntriesPlusVisibilities().keySet()) { if (s.endsWith(VDBResources.INDEX_EXT)) { defaultRepo = super.getMetadataRepository("index"); //$NON-NLS-1$ break; } } this.assignMetadataRepositories(vdb, defaultRepo); // add transformation metadata to the repository. getVDBRepository().addVDB(this.vdb, store, vdbResources.getEntriesPlusVisibilities(), udf, cmr, this.shutdownListener.isBootInProgress()); } catch (VirtualDatabaseException e) { throw new StartException(e); } this.vdb.removeAttachment(UDFMetaData.class); try { loadMetadata(this.vdb, cmr, store, this.vdbResources, this.shutdownListener.isBootInProgress()); } catch (TranslatorException e) { throw new StartException(e); } this.runtimeVDB = buildRuntimeVDB(this.vdb, context.getController().getServiceContainer()); } private RuntimeVDB buildRuntimeVDB(final VDBMetaData vdbMetadata, final ServiceContainer serviceContainer) { RuntimeVDB.VDBModificationListener modificationListener = new RuntimeVDB.VDBModificationListener() { @Override public void dataRoleChanged(String policyName) throws AdminProcessingException { save(); } @Override public void connectionTypeChanged() throws AdminProcessingException { save(); } @Override public void dataSourceChanged(String modelName, String sourceName,String translatorName, String dsName) throws AdminProcessingException { save(); } @Override public void onRestart(List<String> modelNames) { ServiceController<?> switchSvc = serviceContainer.getService(TeiidServiceNames.vdbSwitchServiceName(vdbMetadata.getName(), vdbMetadata.getVersion())); if (switchSvc != null) { if (!modelNames.isEmpty()) { for (String model:modelNames) { deleteModelCache(model); } } else { for (String model:vdbMetadata.getModelMetaDatas().keySet()) { deleteModelCache(model); } } switchSvc.setMode(ServiceController.Mode.REMOVE); } } }; return new RuntimeVDB(vdbMetadata, modificationListener) { @Override protected VDBStatusChecker getVDBStatusChecker() { return VDBService.this.vdbStatusCheckInjector.getValue(); } }; } Service<Void> createVoidService() { return new Service<Void>() { @Override public Void getValue() throws IllegalStateException, IllegalArgumentException { return null; } @Override public void start(StartContext sc)throws StartException {} @Override public void stop(StopContext sc) {} }; } private ServiceBuilder<Void> addVDBFinishedService(StartContext context) { ServiceContainer serviceContainer = context.getController().getServiceContainer(); final ServiceController<?> controller = serviceContainer.getService(TeiidServiceNames.vdbFinishedServiceName(vdb.getName(), vdb.getVersion())); if (controller != null) { controller.setMode(ServiceController.Mode.REMOVE); } return serviceContainer.addService(TeiidServiceNames.vdbFinishedServiceName(vdb.getName(), vdb.getVersion()), createVoidService()); } @Override public void stop(StopContext context) { ServiceController<?> switchSvc = context.getController().getServiceContainer().getService(TeiidServiceNames.vdbSwitchServiceName(vdb.getName(), vdb.getVersion())); if (switchSvc != null) { switchSvc.setMode(ServiceController.Mode.REMOVE); } // stop object replication if (this.objectReplicatorInjector.getValue() != null) { GlobalTableStore gts = vdb.getAttachment(GlobalTableStore.class); this.objectReplicatorInjector.getValue().stop(gts); } getVDBRepository().removeVDB(this.vdb.getName(), this.vdb.getVersion()); getVDBRepository().removeListener(this.vdbListener); getVDBRepository().removeListener(this.restEasyListener); final ServiceController<?> controller = context.getController().getServiceContainer().getService(TeiidServiceNames.vdbFinishedServiceName(vdb.getName(), vdb.getVersion())); if (controller != null) { controller.setMode(ServiceController.Mode.REMOVE); } LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50026, this.vdb)); } @Override public RuntimeVDB getValue() throws IllegalStateException,IllegalArgumentException { return this.runtimeVDB; } private void createConnectorManagers(ConnectorManagerRepository cmr, final TranslatorRepository repo, final VDBMetaData deployment) throws StartException { final IdentityHashMap<Translator, ExecutionFactory<Object, Object>> map = new IdentityHashMap<Translator, ExecutionFactory<Object, Object>>(); try { ConnectorManagerRepository.ExecutionFactoryProvider provider = new ConnectorManagerRepository.ExecutionFactoryProvider() { @Override public ExecutionFactory<Object, Object> getExecutionFactory(String name) throws ConnectorManagerException { return VDBService.getExecutionFactory(name, repo, getTranslatorRepository(), deployment, map, new HashSet<String>()); } }; cmr.setProvider(provider); cmr.createConnectorManagers(deployment, provider); } catch (ConnectorManagerException e) { if (e.getCause() != null) { throw new StartException(IntegrationPlugin.Event.TEIID50035.name()+" "+e.getMessage(), e.getCause()); //$NON-NLS-1$ } throw new StartException(e.getMessage()); } } @SuppressWarnings({"rawtypes","unchecked"}) static ExecutionFactory<Object, Object> getExecutionFactory(String name, TranslatorRepository vdbRepo, TranslatorRepository repo, VDBMetaData deployment, IdentityHashMap<Translator, ExecutionFactory<Object, Object>> map, HashSet<String> building) throws ConnectorManagerException { if (!building.add(name)) { throw new ConnectorManagerException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50076, deployment.getName(), deployment.getVersion(), building)); } VDBTranslatorMetaData translator = vdbRepo.getTranslatorMetaData(name); if (translator == null) { translator = repo.getTranslatorMetaData(name); } if (translator == null) { return null; } ExecutionFactory<Object, Object> ef = map.get(translator); if ( ef == null) { try { ef = TranslatorUtil.buildExecutionFactory(translator); } catch (TeiidException e) { throw new ConnectorManagerException(e); } if (ef instanceof DelegatingExecutionFactory) { DelegatingExecutionFactory delegator = (DelegatingExecutionFactory)ef; String delegateName = delegator.getDelegateName(); if (delegateName != null) { ExecutionFactory<Object, Object> delegate = getExecutionFactory(delegateName, vdbRepo, repo, deployment, map, building); if (delegate == null) { throw new ConnectorManagerException(QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31146, deployment.getName(), deployment.getVersion(), delegateName)); } ((DelegatingExecutionFactory<Object, Object>) ef).setDelegate(delegate); } } map.put(translator, ef); } return ef; } @Override @SuppressWarnings({"rawtypes","unchecked"}) protected void loadMetadata(final VDBMetaData vdb, final ModelMetaData model, final ConnectorManagerRepository cmr, final MetadataRepository metadataRepo, final MetadataStore vdbMetadataStore, final AtomicInteger loadCount, final VDBResources vdbResources) { String msg = IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50029,vdb.getName(), vdb.getVersion(), model.getName(), SimpleDateFormat.getInstance().format(new Date())); model.setMetadataStatus(Model.MetadataStatus.LOADING); model.addRuntimeMessage(Severity.INFO, msg); LogManager.logInfo(LogConstants.CTX_RUNTIME, msg); final Runnable job = new Runnable() { @Override public void run() { boolean cached = false; Exception ex = null; TranslatorException te = null; // if this is not the first time trying to load metadata if (model.getMetadataStatus() != Model.MetadataStatus.LOADING) { model.setMetadataStatus(Model.MetadataStatus.RETRYING); } // designer based models define data types based on their built in data types, which are system vdb data types Map<String, Datatype> datatypes = getVDBRepository().getRuntimeTypeMap(); Map<String, Datatype> builtin = getVDBRepository().getSystemStore().getDatatypes(); final File cachedFile = getSerializer().buildModelFile(vdb, model.getName()); MetadataFactory factory = getSerializer().loadSafe(cachedFile, MetadataFactory.class); if (factory != null) { factory.correctDatatypes(datatypes, builtin); cached = true; LogManager.logTrace(LogConstants.CTX_RUNTIME, "Model ", model.getName(), "in VDB ", vdb.getName(), " was loaded from cached metadata"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { factory = createMetadataFactory(vdb, model, vdbResources.getEntriesPlusVisibilities()); ExecutionFactory ef = null; Object cf = null; for (ConnectorManager cm : getConnectorManagers(model, cmr)) { if (ex != null) { LogManager.logDetail(LogConstants.CTX_RUNTIME, ex, "Failed to get metadata, trying next source."); //$NON-NLS-1$ ex = null; te = null; } try { if (cm != null) { ef = cm.getExecutionFactory(); cf = cm.getConnectionFactory(); } } catch (TranslatorException e) { LogManager.logDetail(LogConstants.CTX_RUNTIME, e, "Failed to get a connection factory for metadata load."); //$NON-NLS-1$ te = e; } try { metadataRepo.loadMetadata(factory, ef, cf); LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50030,vdb.getName(), vdb.getVersion(), model.getName(), SimpleDateFormat.getInstance().format(new Date()))); break; } catch (Exception e) { ex = e; } } } synchronized (vdb) { if (ex == null) { if (!cached) { // cache the schema to disk cacheMetadataStore(model, factory); } metadataLoaded(vdb, model, vdbMetadataStore, loadCount, factory, true, VDBService.this.shutdownListener.isBootInProgress()); } else { String errorMsg = ex.getMessage()==null?ex.getClass().getName():ex.getMessage(); if (te != null) { errorMsg += ": " + te.getMessage(); //$NON-NLS-1$ } model.addRuntimeError(errorMsg); model.setMetadataStatus(Model.MetadataStatus.FAILED); LogManager.logWarning(LogConstants.CTX_RUNTIME, ex, IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50036,vdb.getName(), vdb.getVersion(), model.getName(), errorMsg)); if (ex instanceof RuntimeException) { metadataLoaded(vdb, model, vdbMetadataStore, loadCount, factory, false, VDBService.this.shutdownListener.isBootInProgress()); } else { //defer the load to the status checker if/when a source is available/redeployed model.addAttchment(Runnable.class, this); } } } } }; Executor executor = getExecutor(); if (executor == null) { job.run(); } else { //wrap the runnable to trap exceptions that may be caused by an asynch deployment issue executor.execute(new Runnable() { @Override public void run() { try { job.run(); } catch (IllegalStateException e) { if (vdb.getStatus() != Status.FAILED && vdb.getStatus() != Status.REMOVED) { throw e; } LogManager.logDetail(LogConstants.CTX_RUNTIME, e, "Could not load metadata for a removed or failed deployment."); } } }); } } private void cacheMetadataStore(final ModelMetaData model, MetadataFactory schema) { boolean cache = true; if (vdb.isXmlDeployment()) { cache = "cached".equalsIgnoreCase(vdb.getPropertyValue("UseConnectorMetadata")); //$NON-NLS-1$ //$NON-NLS-2$ } String prop = vdb.getPropertyValue("cache-metadata"); //$NON-NLS-1$ if (prop != null) { cache = Boolean.valueOf(prop); } prop = model.getPropertyValue("cache-metadata"); //$NON-NLS-1$ if (prop != null) { cache = Boolean.valueOf(prop); } if (cache) { final File cachedFile = getSerializer().buildModelFile(vdb, model.getName()); try { getSerializer().saveAttachment(cachedFile, schema, false); } catch (IOException e) { LogManager.logWarning(LogConstants.CTX_RUNTIME, e, IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50044, vdb.getName(), vdb.getVersion(), model.getName())); } } } private void deleteModelCache(String modelName) { final File cachedFile = getSerializer().buildModelFile(vdb, modelName); getSerializer().removeAttachment(cachedFile); } @Override protected VDBRepository getVDBRepository() { return vdbRepositoryInjector.getValue(); } private TranslatorRepository getTranslatorRepository() { return this.translatorRepositoryInjector.getValue(); } private Executor getExecutor() { return this.executorInjector.getValue(); } private ObjectSerializer getSerializer() { return serializerInjector.getValue(); } private BufferManager getBuffermanager() { return bufferManagerInjector.getValue(); } private void save() throws AdminProcessingException{ try { ObjectSerializer os = getSerializer(); VDBMetadataParser.marshell(this.vdb, os.getVdbXmlOutputStream(this.vdb)); } catch (IOException e) { throw new AdminProcessingException(IntegrationPlugin.Event.TEIID50048, e); } catch (XMLStreamException e) { throw new AdminProcessingException(IntegrationPlugin.Event.TEIID50049, e); } } /** * Override for module based loading */ @SuppressWarnings("rawtypes") @Override protected MetadataRepository<?, ?> getMetadataRepository(String repoType) throws VirtualDatabaseException { MetadataRepository<?, ?> repo = super.getMetadataRepository(repoType); if (repo != null) { return repo; } final Module module; ClassLoader moduleLoader = this.getClass().getClassLoader(); ModuleLoader ml = Module.getCallerModuleLoader(); if (repoType != null && ml != null) { try { module = ml.loadModule(ModuleIdentifier.create(repoType)); moduleLoader = module.getClassLoader(); } catch (ModuleLoadException e) { throw new VirtualDatabaseException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50057, repoType)); } } final ServiceLoader<MetadataRepository> serviceLoader = ServiceLoader.load(MetadataRepository.class, moduleLoader); if (serviceLoader != null) { for (MetadataRepository loader:serviceLoader) { MetadataRepository old = this.repositories.putIfAbsent(repoType, loader); return old!=null?old:loader; } } return null; } }
package jme3tools.shadercheck; import com.jme3.asset.AssetManager; import com.jme3.asset.plugins.ClasspathLocator; import com.jme3.asset.plugins.FileLocator; import com.jme3.material.MaterialDef; import com.jme3.material.TechniqueDef; import com.jme3.material.plugins.J3MLoader; import com.jme3.shader.DefineList; import com.jme3.shader.Shader; import com.jme3.shader.ShaderKey; import com.jme3.shader.plugins.GLSLLoader; import com.jme3.system.JmeSystem; import java.util.logging.Level; import java.util.logging.Logger; public class ShaderCheck { private static final Logger logger = Logger.getLogger(ShaderCheck.class.getName()); private static AssetManager assetManager; private static Validator[] validators = new Validator[]{ new CgcValidator(), // new GpuAnalyzerValidator() }; private static void initAssetManager(){ assetManager = JmeSystem.newAssetManager(); assetManager.registerLocator(".", FileLocator.class); assetManager.registerLocator("/", ClasspathLocator.class); assetManager.registerLoader(J3MLoader.class, "j3m"); assetManager.registerLoader(J3MLoader.class, "j3md"); assetManager.registerLoader(GLSLLoader.class, "vert", "frag", "glsllib"); } private static void checkMatDef(String matdefName){ MaterialDef def = (MaterialDef) assetManager.loadAsset(matdefName); for (TechniqueDef techDef : def.getDefaultTechniques()){ DefineList dl = new DefineList(); dl.addFrom(techDef.getShaderPresetDefines()); ShaderKey shaderKey = new ShaderKey(techDef.getVertexShaderName(), techDef.getFragmentShaderName(), dl, techDef.getVertexShaderLanguage(), techDef.getFragmentShaderLanguage()); Shader shader = assetManager.loadShader(shaderKey); for (Validator validator : validators){ StringBuilder sb = new StringBuilder(); validator.validate(shader, sb); System.out.println("==== Validator: " + validator.getName() + " " + validator.getInstalledVersion() + " ===="); System.out.println(sb.toString()); } } } public static void main(String[] args){ Logger.getLogger(MaterialDef.class.getName()).setLevel(Level.OFF); initAssetManager(); checkMatDef("Common/MatDefs/Blur/HGaussianBlur.j3md"); checkMatDef("Common/MatDefs/Blur/RadialBlur.j3md"); checkMatDef("Common/MatDefs/Blur/VGaussianBlur.j3md"); checkMatDef("Common/MatDefs/Gui/Gui.j3md"); checkMatDef("Common/MatDefs/Hdr/LogLum.j3md"); checkMatDef("Common/MatDefs/Hdr/ToneMap.j3md"); checkMatDef("Common/MatDefs/Light/Lighting.j3md"); checkMatDef("Common/MatDefs/Misc/ColoredTextured.j3md"); checkMatDef("Common/MatDefs/Misc/Particle.j3md"); checkMatDef("Common/MatDefs/Misc/ShowNormals.j3md"); checkMatDef("Common/MatDefs/Misc/Sky.j3md"); checkMatDef("Common/MatDefs/Misc/Unshaded.j3md"); checkMatDef("Common/MatDefs/Post/BloomExtract.j3md"); checkMatDef("Common/MatDefs/Post/BloomFinal.j3md"); checkMatDef("Common/MatDefs/Post/CartoonEdge.j3md"); checkMatDef("Common/MatDefs/Post/CrossHatch.j3md"); checkMatDef("Common/MatDefs/Post/DepthOfField.j3md"); checkMatDef("Common/MatDefs/Post/FXAA.j3md"); checkMatDef("Common/MatDefs/Post/Fade.j3md"); checkMatDef("Common/MatDefs/Post/Fog.j3md"); checkMatDef("Common/MatDefs/Post/GammaCorrection.j3md"); checkMatDef("Common/MatDefs/Post/LightScattering.j3md"); checkMatDef("Common/MatDefs/Post/Overlay.j3md"); checkMatDef("Common/MatDefs/Post/Posterization.j3md"); checkMatDef("Common/MatDefs/SSAO/ssao.j3md"); checkMatDef("Common/MatDefs/SSAO/ssaoBlur.j3md"); checkMatDef("Common/MatDefs/Shadow/PostShadow.j3md"); checkMatDef("Common/MatDefs/Shadow/PostShadowPSSM.j3md"); checkMatDef("Common/MatDefs/Shadow/PreShadow.j3md"); checkMatDef("Common/MatDefs/Water/SimpleWater.j3md"); checkMatDef("Common/MatDefs/Water/Water.j3md"); } }
package org.jmxdatamart.Extractor; import java.io.IOException; import java.lang.management.ManagementFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Map; import java.util.Properties; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.ReflectionException; import org.jmxdatamart.JMXTestServer.TestBean; import org.jmxdatamart.common.*; public class Main { public static void main(String[] args) throws Exception { System.out.println("extract"); // values int expected = 42; //Create new test MBean TestBean tb = new TestBean(); tb.setA(new Integer(expected)); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); String mbName = "org.jmxdatamart.JMXTestServer:type=TestBean"; ObjectName mbeanName = new ObjectName(mbName); mbs.registerMBean(tb, mbeanName); //Create test MBean's MBeanData Attribute a = new Attribute("A", "Alpha", DataType.INT); MBeanData mbd = new MBeanData(mbName, "testMBean", Collections.singletonList(a), true); //Init MBeanExtract MBeanExtract instance = new MBeanExtract(mbd, mbs); Map result = instance.extract(); //test MBean to embbed DB Settings s = new Settings(); s.setBeans(Collections.singletonList(mbd)); s.setFolderLocation("HyperSQL/"); s.setPollingRate(2); s.setUrl("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi"); Properties props = new Properties(); props.put("username", "sa"); props.put("password", "whatever"); Bean2DB bd = new Bean2DB(); String dbname = bd.generateMBeanDB(s); HypersqlHandler hsql = new HypersqlHandler(); Connection conn= hsql.connectDatabase(dbname,props); bd.export2DB(conn,mbd,result); ResultSet rs = conn.createStatement().executeQuery("select count(*) from org_jmxdatamart_JMXTestServer__type___TestBean"); rs.next(); System.out.println(rs.getInt(1)); rs.close(); hsql.shutdownDatabase(conn); hsql.disconnectDatabase(rs,null,null,conn); // TODO review the generated test code and remove the default call to fail. //fail("The test case is a prototype."); } }
package edu.ucsf.lava.core.list.model; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import edu.ucsf.lava.core.dao.LavaDaoFilter; import edu.ucsf.lava.core.dao.LavaDaoParam; import edu.ucsf.lava.core.list.ListDefinitions; /** * @author jhesse * */ public class BaseListConfig { /** Logger for this class and subclasses */ protected static final Log logger = LogFactory.getLog(LavaList.class); protected static Map<String,String> emptyList; protected ListDefinitions listDefinitions; public static String LIST_CONFIG_BEAN_NAME_PREFIX = "list."; public static String GENERIC_LIST_VALUE_QUERY = "GenericListValueQuery"; public static String GENERIC_LIST_VALUE_QUERY_PARAM_NAME = "listName"; public static String GENERIC_LIST_VALUE_QUERY_NULL_DESC = "GenericListValueQueryNullDesc"; public static String GENERIC_LIST_VALUE_QUERY_DECIMAL = "GenericListValueQueryDecimal"; public static String LIST_VALUE_QUERY_DECIMAL_CDR_NO_POINT_5 = "ListValueQueryDecimalCDRScaleNoPoint5"; public static String FORMAT_LABEL = "label"; public static String FORMAT_LABEL_WITH_INITIAL = "labelWithInitial"; // e.g. 'l | label' : first char of the label is concatenated to the label separated by '|' (useful for multi-column select boxes public static String FORMAT_VALUE_IS_LABEL = "valueIsLabel"; // e.g. 'value' : use the value as the label (usually because the label is null in the database). this is redundant if using GenericListValueQueryNullDesc, since that query populates the label with the value (aka valueKey) public static String FORMAT_VALUE_CONCAT_LABEL = "valueConcatLabel"; // e.g. 'value | label' : the label is a concatenation of the value and the label public static String FORMAT_TWO_DECIMAL_PLACES = "twoDecimalPlaces"; // only applies to DecimalRange lists public static String FORMAT_SEPARATOR = " | "; public static String FORMAT_CONCATONATOR = " - "; public static String SORT_LABEL_STRING = "label"; public static String SORT_VALUE_STRING = "value"; public static String SORT_VALUE_NUMERIC = "valueNumeric"; public static String SORT_VALUE_DECIMAL = "valueDecimal"; public static String SORT_ORDER_INDEX = "orderIndex"; public static String SORT_ORDER_INDEX_VALUE = "orderIndexValue"; public static String SORT_ORDER_INDEX_LABEL = "orderIndexLabel"; public static String SORT_ORDER_INDEX_VALUE_NUMERIC = "orderIndexValueNumeric"; public static String SORT_ORDER_INDEX_VALUE_DECIMAL = "orderIndexValueDecimal"; public static String SORT_NONE = "none"; protected String name; //The name of the list -- as referenced in the metadata (this is distinct from dblistName defined above--the name of the list in the List database table) protected String query; //the query name protected String dbListName; //list name from the database List table protected Boolean dynamic; //static / dynamic flag protected List<LabelValueBean> data; // data list supplied in the xml configuration; protected List<BaseListConfig> staticReferenceLists; //static lists that are combined with the primary list definition to create the list protected List<BaseListConfig> dynamicReferenceLists; //dynamic lists that are combined with the primary list definition to create the list protected List<LabelValueBean> internalList; protected List<LabelValueBean> internalListWithCodes; protected Map<String,String> defaultExternalList; protected Map<String,String> defaultExternalListWithCodes; protected Map<String,Map<String,String>> cache = new HashMap<String,Map<String,String>>(); protected Date staticListRefreshed; protected String defaultFormat; //default presenation format protected String defaultSort; //default sort to use protected BaseListConfig defaultCodes; //default missing data codes to use if not specified protected List<LavaDaoParam> defaultParams; //default params to use for the query public BaseListConfig() { super(); this.dynamic = false; } /** * Override this method to introduce custom handling of the request paramters in * subclasses of ListConfig (e.g. convert String param values to Long instances) * @param request * @return */ protected ListRequest onGetList(ListRequest request){ return request; } /** * primary method used to get the list * @param ListRequest request */ public Map<String,String> getList(ListRequest requestIn){ //combine request passed in with the defaults ListRequest request = new ListRequest(requestIn,this); //if not a dynamic list, make sure the static list has been initialized if(!dynamic && staticListRefreshed==null){ refreshStaticList(); } request = onGetList(request); //look for the list in the cache (only static lists are cached), if found simply return String cacheKey = request.getListRequestId(); if(cached(cacheKey)){ return getCachedList(cacheKey); } //treat dynamic and parameterized static lists the same, except we cache the static lists for reuse and //always re-execute dynamic list requests. if(dynamic || request.hasParams()){ // load the primary list List<LabelValueBean> dynamicList = getDynamicInternalList(request); //if necessary, add codes if(request.hasCodes()){ dynamicList = merge(dynamicList,request.getCodes().getInternalList(),false); } Map<String,String> list = createExternalList(dynamicList,request.getFormat(),request.getSort()); if(!dynamic){ cacheList(cacheKey,list); } return list; } //handle static, non-default, not-yet-cached list requests //if no codes then use the "without codes" lists; if(!request.hasCodes()){ return cacheList(cacheKey,createExternalList(internalList,request.getFormat(),request.getSort())); //if the codes requested are the default codes for the configuration then use the pre-prepared internal list }else if(request.getCodes().getName().equals(defaultCodes.getName())){ return cacheList(cacheKey,createExternalList(internalListWithCodes,request.getFormat(),request.getSort())); //if the codes requested are not the default codes then create a new internal format list with the new codes }else{ List<LabelValueBean> listWithCodes = merge(copyList(internalList),request.getCodes().getInternalList(),false); return cacheList(cacheKey,createExternalList(listWithCodes,request.getFormat(),request.getSort())); } } /** * is the requested list in the listCache * @param cacheKey the key into the cache * */ protected boolean cached(String cacheKey){ return cache.containsKey(cacheKey); } /** * get a list from the cache * @param cacheKey the key into the cache * */ protected Map<String,String> getCachedList (String cacheKey){ if(!cached(cacheKey)){return getEmptyList();} return cache.get(cacheKey); } /** * put the list in the cache * @param cacheKey the key for the cache * @param list the static list to cache in external list format * @return returns the list passed in for convenient use */ protected Map<String,String> cacheList(String cacheKey, Map<String,String>list){ cache.put(cacheKey, list); return list; } protected void clearCache(){ cache.clear(); } /** * add the default static list with and without codes to the cache * */ protected void addDefaultsToCache(){ ListRequest request = new ListRequest(this); //get cache key using default codes String cacheKey = request.getListRequestId(); cacheList(cacheKey,defaultExternalListWithCodes); //if the defaultCodes for this config is the NoCodesListConfig, then we don't need to add a //without codes default to the cache because the default with codes = default without codes if(defaultCodes!=null && !defaultCodes.getName().equals(NoCodesListConfig.NO_CODES_CONFIG_NAME)){ //set request codes = no codes request.setCodes(new NoCodesListConfig()); cacheKey = request.getListRequestId(); cacheList(cacheKey,defaultExternalList); } } /** * Utility method to create a blank list. Used by this class as the first step * in generating an external list. Also used by other classes when a runtime * problem results in no list generation (e.g. listconfig name not found) and * we don't want to throw a runtime exception. * @param size * @return */ public static Map<String,String>getEmptyList(int size){ return addBlankListEntry(new LinkedHashMap<String,String>(size+1)); } public static Map<String,String>getEmptyList(){ return getEmptyList(0); } public static Map<String,String>addBlankListEntry(Map<String,String>list){ // every list should have a blank element that is the first element of the list. // this processing is done after the list is created to ensure that the blank is the first element // the blank element is a user interface feature, representing that nothing in the list has been selected // and allowing a user to select a blank element // note: it is much easier to do this here to the external lists than to the internal lists // because internal lists can reference other internal lists so there is complexity of // making sure there is only one blank // note: custom editors cause any field submitted with the empty string as the value to // result in a null being assigned to the property associated with the field list.put("",""); return list; } public List<LabelValueBean> getDynamicInternalList(ListRequest request){ List<LabelValueBean> dynamicInternalList = loadPrimaryQueryList(request.getDaoFilter()); //next merge in any dynamic reference lists //TODO: do we need to have distinct named parameter sets to support each distinct dynamic query? if(dynamicReferenceLists!=null){ for(BaseListConfig referenceList : dynamicReferenceLists){ dynamicInternalList = merge(dynamicInternalList,referenceList.getDynamicInternalList(request),false); } } //merge in all static reference lists if(staticReferenceLists!=null){ for(BaseListConfig referenceList : staticReferenceLists){ dynamicInternalList = merge(dynamicInternalList,referenceList.getInternalList(),false); } } // merge-replace any data specified in the configuration if(data!=null){ dynamicInternalList = merge(dynamicInternalList,data,true); } return dynamicInternalList; } /** * This is the main contruction routine for static lists upon initialization. The list construction logic is: * 1) loads the primary list for this configuration. * 2) merges in all reference lists by calling their getInternalList method (does not replace matching list items) * 3) merges in any data supplied with this list configuration (does replace matching list items...this allows the * data confugration option to be used as an override..not sure if this is really the best behavior) * 4) updates internal list properties * 5) generates default external lists properties (using default sort and format) * 5) sets the internal refreshed timestamp. * Note: this routine does not protect against access by other threads while the lists are being refreshed. * This is probably OK as the worst thing that would happen(?) is a slighly out of date or null list * */ public void refreshStaticList(){ ListRequest request = new ListRequest(this); logger.debug("refreshStaticList="+this.getName()); List<LabelValueBean> list = loadPrimaryQueryList(request.getDaoFilter()); /* Note: Static lists cannot contain dynamic reference lists, because the method signatures for * static lists do not include LavaDaoFilter parameters. */ //merge in any static reference lists if(staticReferenceLists!=null){ for(BaseListConfig referenceList : staticReferenceLists){ list = merge(list,referenceList.getInternalList(),false); } } //merge-replace any data specified in the configuration if(data!=null){ list = merge(list,data,true); } //set internal list properties internalList = list; if(!request.hasCodes()){ internalListWithCodes = internalList; }else{ //share the underlying labelvaluebeans between the internalLists...don't really need separate copies //and with really large lists this will save resources. internalListWithCodes = merge(copyList(internalList,false),defaultCodes.getInternalList(),false); } //generate default external list properties defaultExternalList = createExternalList(internalList,defaultFormat,defaultSort); if(!request.hasCodes()){ defaultExternalListWithCodes = defaultExternalList; }else{ defaultExternalListWithCodes = createExternalList(internalListWithCodes,defaultFormat,defaultSort); } clearCache(); addDefaultsToCache(); staticListRefreshed = new Date(); } /** * load the primary list by executing the supplied named query and dbListName (if configured). * * @param filter LavaDaoFilter with all the params for the named query configured. * */ protected List<LabelValueBean> loadPrimaryQueryList(LavaDaoFilter filter) { java.util.List<LabelValueBean> resultList = new ArrayList<LabelValueBean>(); if(StringUtils.isEmpty(this.query)){ return resultList;} if(query.equals(GENERIC_LIST_VALUE_QUERY) || query.equals(GENERIC_LIST_VALUE_QUERY_NULL_DESC) || query.equals(GENERIC_LIST_VALUE_QUERY_DECIMAL) || query.equals(LIST_VALUE_QUERY_DECIMAL_CDR_NO_POINT_5)){ filter.addDaoParam(filter.daoNamedParam(GENERIC_LIST_VALUE_QUERY_PARAM_NAME,dbListName)); } try { resultList = LavaList.MANAGER.findByNamedQuery(query,filter); if (resultList == null) { logger.info("resultList null in loadList query=<" + query + ">"); } } catch (DataAccessException dae) { logger.info("DataAccessException in loadList, query=<" + query + ">"); logger.info(dae.getMostSpecificCause()); logger.info(dae.getRootCause()); logger.info(dae.getStackTrace()); logger.info(dae.getMessage()); } return resultList; } /** * Create a copy of an internal formatted list. if deepCopy then create new * instances of the LabelvalueBeans in the new list. This facilitaes using the * internal lvb format for formatting and sorting without modifying the common * internal list properties of the config. * @param list * @param deepCopy TODO * @return */ protected List<LabelValueBean> copyList(List<LabelValueBean> list, boolean deepCopy){ ArrayList<LabelValueBean> copy = new ArrayList(list.size()); for(LabelValueBean lvb:list){ copy.add(new LabelValueBean(lvb)); } return copy; } /** * Convenience function...default copy is a deepCopy... * @param list * @return */ protected List<LabelValueBean> copyList(List<LabelValueBean> list){ return copyList(list,true); } /** * Merge lists. * @param mergeTo The list to merge into (in LabelValueBean format) * @param mergeFrom The list to merge from (in LabelValueBean format) * @param replace Whether to replace items in the mergeTo list with matching items in the mergeFrom list. Match is * defined by comparing Labels (ToDo: is this correct behavior?) * @return */ protected List<LabelValueBean> merge(List<LabelValueBean> mergeTo, List<LabelValueBean> mergeFrom, boolean replace) { for (LabelValueBean mergeFromLVB : mergeFrom) { int mergeToIndex = 0; boolean found = false; for (LabelValueBean mergeToLVB : mergeTo) { if (mergeFromLVB.compareTo(mergeToLVB) == 0) { found = true; break; } mergeToIndex++; } if (found && replace) { mergeTo.set(mergeToIndex, mergeFromLVB); } else { mergeTo.add(mergeFromLVB); } } return mergeTo; } /** * utility method to transfer a list from the internal list structure to the external list structure * @param list * @return */ private Map<String,String> createExternalList(List<LabelValueBean> list, String format, String sort) { List<LabelValueBean> workList = copyList(list); workList = formatList(workList,format); workList = sortList(workList,sort); Map<String,String> extList = getEmptyList(workList.size()); for(LabelValueBean lvb: workList){ extList.put(lvb.getValue(), lvb.getLabel()); } return extList; } protected List<LabelValueBean> sortList(List <LabelValueBean> list,String sort){ if (sort.equals(SORT_NONE)) { return list; }else if (sort.equals(SORT_LABEL_STRING)) { // natural sort order, i.e. by "value" field of LabelValueBean Collections.sort(list); } else if (sort.equals(SORT_VALUE_STRING)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.valueComparator); } else if (sort.equals(SORT_VALUE_NUMERIC)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.valueNumericComparator); } else if (sort.equals(SORT_VALUE_DECIMAL)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.valueDecimalComparator); } else if (sort.equals(SORT_ORDER_INDEX)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.orderIndexComparator); } else if (sort.equals(SORT_ORDER_INDEX_VALUE)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.orderIndexValueComparator); } else if (sort.equals(SORT_ORDER_INDEX_LABEL)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.orderIndexLabelComparator); } else if (sort.equals(SORT_ORDER_INDEX_VALUE_NUMERIC)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.orderIndexValueNumericComparator); } else if (sort.equals(SORT_ORDER_INDEX_VALUE_DECIMAL)) { // use a Comparator to sort Collections.sort(list, LabelValueBean.orderIndexValueDecimalComparator); } else { logger.error("Invalid sort field=<" + sort + ">"); } return list; } private List<LabelValueBean> formatList(List<LabelValueBean> list, String format){ if (format==null || list==null || format.equals(FORMAT_LABEL)) {return list;} if (format.equals(FORMAT_VALUE_IS_LABEL)) { for(LabelValueBean lvb : list){ lvb.setLabel(lvb.getValue()); } }else if (format.equals(FORMAT_LABEL_WITH_INITIAL)) { for(LabelValueBean lvb : list){ lvb.setLabel(new StringBuffer(lvb.getLabel().substring(0,1)).append(FORMAT_SEPARATOR).append(lvb.getLabel()).toString()); } }else if (format.equals(FORMAT_VALUE_CONCAT_LABEL)) { for(LabelValueBean lvb : list){ lvb.setLabel(new StringBuffer(lvb.getValue()).append(this.FORMAT_CONCATONATOR).append(lvb.getLabel()).toString()); } } return list; } public List<LabelValueBean> getData() { return data; } public void setData(List<LabelValueBean> data) { this.data = data; } public String getDbListName() { return dbListName; } public void setDbListName(String dbListName) { this.dbListName = dbListName; } public BaseListConfig getDefaultCodes() { return defaultCodes; } public void setDefaultCodes(BaseListConfig defaultCodes) { this.defaultCodes = defaultCodes; } public String getDefaultFormat() { return defaultFormat; } public void setDefaultFormat(String defaultFormat) { this.defaultFormat = defaultFormat; } public String getDefaultSort() { return defaultSort; } public void setDefaultSort(String defaultSort) { this.defaultSort = defaultSort; } public List<LabelValueBean> getInternalList() { if(internalList!=null){return internalList;} if(staticListRefreshed==null){ refreshStaticList(); } return internalList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public Boolean isDynamic() { return dynamic; } public void setDynamic(Boolean dynamic) { this.dynamic = dynamic; } public List<BaseListConfig> getDynamicReferenceLists() { return dynamicReferenceLists; } public void setDynamicReferenceLists(List<BaseListConfig> dynamicReferenceLists) { this.dynamicReferenceLists = dynamicReferenceLists; } public List<BaseListConfig> getStaticReferenceLists() { return staticReferenceLists; } public void setStaticReferenceLists(List<BaseListConfig> staticReferenceLists) { this.staticReferenceLists = staticReferenceLists; } public Date getStaticListRefreshed() { return staticListRefreshed; } public ListDefinitions getListDefinitions() { return listDefinitions; } public void setListDefinitions(ListDefinitions listDefinitions) { this.listDefinitions = listDefinitions; } public List<LavaDaoParam> getDefaultParams() { return defaultParams; } public void setDefaultParams(List<LavaDaoParam> defaultParams) { this.defaultParams = defaultParams; } }
package se.chalmers.watchme.database; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; /** * The Content Provider for the WatchMe application. * * @author lisastenberg * */ public class WatchMeContentProvider extends ContentProvider { private DatabaseHelper db; public static final String AUTHORITY = "se.chalmers.watchme.database." + "providers.WatchMeContentProvider"; private static final String BASE_PATH_MOVIES = "movies"; private static final String BASE_PATH_TAGS = "tags"; private static final String BASE_PATH_HAS_TAG = "hastag"; private static final int MOVIES = 10; private static final int MOVIES_ID = 20; private static final int TAGS = 30; private static final int TAGS_ID = 40; private static final int HAS_TAG = 50; public static final Uri CONTENT_URI_MOVIES = Uri.parse("content: + AUTHORITY + "/" + BASE_PATH_MOVIES); public static final Uri CONTENT_URI_TAGS = Uri.parse("content: + AUTHORITY + "/" + BASE_PATH_TAGS); public static final Uri CONTENT_URI_HAS_TAG = Uri.parse("content: + AUTHORITY + "/" + BASE_PATH_HAS_TAG); public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/watchme"; public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/watchme"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(AUTHORITY, BASE_PATH_MOVIES, MOVIES); sUriMatcher.addURI(AUTHORITY, BASE_PATH_MOVIES + "/#", MOVIES_ID); sUriMatcher.addURI(AUTHORITY, BASE_PATH_TAGS, TAGS); sUriMatcher.addURI(AUTHORITY, BASE_PATH_TAGS + "/#", TAGS_ID); sUriMatcher.addURI(AUTHORITY, BASE_PATH_HAS_TAG, HAS_TAG); }; @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase sqlDB = db.getWritableDatabase(); int deletedRows; switch (sUriMatcher.match(uri)) { case MOVIES: /* * movieSel is supposed to contain: " = <movieId>" */ System.out.println("CP: deleteMovie: sel " + selection); String movieSel = selection.split(MoviesTable.COLUMN_MOVIE_ID)[1]; Cursor movieCursor = sqlDB.query(HasTagTable.TABLE_HAS_TAG, null, HasTagTable.COLUMN_MOVIE_ID + movieSel, null, null, null, null); movieCursor.getCount(); deletedRows = sqlDB.delete(MoviesTable.TABLE_MOVIES, selection, selectionArgs); while (movieCursor.moveToNext()) { String tagSel = " = " + movieCursor.getString(1); Cursor tagCursor = sqlDB.query(HasTagTable.TABLE_HAS_TAG, null, HasTagTable.COLUMN_TAG_ID + tagSel, null, null, null, null); if (!tagCursor.moveToFirst()) { // If the tag isn't connected to any Movie, delete it. sqlDB.delete(TagsTable.TABLE_TAGS, TagsTable.COLUMN_TAG_ID + tagSel, null); } tagCursor.close(); } movieCursor.close(); break; case MOVIES_ID: //TODO: Need to check if selection is null? selection = selection + MoviesTable.COLUMN_MOVIE_ID + " = " + uri.getLastPathSegment(); deletedRows = sqlDB.delete(MoviesTable.TABLE_MOVIES, selection, selectionArgs); break; case TAGS: deletedRows = sqlDB.delete(TagsTable.TABLE_TAGS, selection, selectionArgs); break; case TAGS_ID: //TODO: Need to check if selection is null? selection = selection + TagsTable.COLUMN_TAG_ID + " = " + uri.getLastPathSegment(); deletedRows = sqlDB.delete(TagsTable.TABLE_TAGS, selection, selectionArgs); break; case HAS_TAG: deletedRows = sqlDB.delete(HasTagTable.TABLE_HAS_TAG, selection, selectionArgs); /* * tagSelection[0] is supposed to contain * "movieid = <movieid> AND" * * tagSelection[1] is supposed to contain: " = <tagId>" */ String tagSelection = selection.split(HasTagTable.COLUMN_TAG_ID)[1]; Cursor tagCursor = sqlDB.query(HasTagTable.TABLE_HAS_TAG, null, HasTagTable.COLUMN_TAG_ID + tagSelection, null, null, null, null); if(!tagCursor.moveToFirst()) { //If the tag isn't connected to any Movie, delete it. sqlDB.delete(TagsTable.TABLE_TAGS, TagsTable.COLUMN_TAG_ID + tagSelection, null); } break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // Notify Observers getContext().getContentResolver().notifyChange(CONTENT_URI_MOVIES, null); getContext().getContentResolver().notifyChange(CONTENT_URI_TAGS, null); getContext().getContentResolver().notifyChange(CONTENT_URI_HAS_TAG, null); return deletedRows; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase sqlDB = db.getWritableDatabase(); long id = 0; switch(sUriMatcher.match(uri)) { case MOVIES: // TODO It should not be possible to add the same movie twice String movieTitle = values.getAsString(MoviesTable.COLUMN_TITLE); Cursor movieCursor = sqlDB.query(MoviesTable.TABLE_MOVIES, null, MoviesTable.COLUMN_TITLE + " = \"" + movieTitle + "\"", null, null, null, null); if(movieCursor.moveToFirst()) { // If the Movie already exist. Get the Id. //id = Long.parseLong(movieCursor.getString(0)); } else { id = sqlDB.insert(MoviesTable.TABLE_MOVIES, null, values); } System.out.println("CP: insertMovie"); break; case HAS_TAG: // Check if the Tag exists. If it doesn't exist. insert into database String tagName = values.getAsString(TagsTable.COLUMN_NAME); Cursor tagCursor = sqlDB.query(TagsTable.TABLE_TAGS, null, TagsTable.COLUMN_NAME + " = \"" + tagName + "\"", null, null, null, null); if(tagCursor.moveToFirst()) { // If the Tag already exist. Get the Id. id = Long.parseLong(tagCursor.getString(0)); /* * Check if the tag is already attached to the movie. * Return 0 as id. */ Cursor cursor = sqlDB.query(HasTagTable.TABLE_HAS_TAG, null, HasTagTable.COLUMN_MOVIE_ID + " = " + values.getAsLong(MoviesTable.COLUMN_MOVIE_ID) + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + id , null, null, null, null); if(cursor.moveToFirst()) { id = 0; break; } } else { ContentValues tagValues = new ContentValues(); tagValues.put(TagsTable.COLUMN_NAME, tagName); id = sqlDB.insert(TagsTable.TABLE_TAGS, null, tagValues); // TODO insert(URI_TAGS, tagValues) instead? } tagCursor.close(); String sql = "INSERT INTO " + HasTagTable.TABLE_HAS_TAG + " VALUES(" + values.getAsLong(MoviesTable.COLUMN_MOVIE_ID) + ", " + id + ")"; sqlDB.execSQL(sql); break; case TAGS: throw new UnsupportedOperationException("A tag can't exist " + "without being attached to a movie"); default: throw new IllegalArgumentException("Unknown URI" + uri); } // Notify Observers getContext().getContentResolver().notifyChange(CONTENT_URI_MOVIES, null); getContext().getContentResolver().notifyChange(CONTENT_URI_TAGS, null); getContext().getContentResolver().notifyChange(CONTENT_URI_HAS_TAG, null); return Uri.parse(BASE_PATH_MOVIES + "/" + id); } @Override public boolean onCreate() { db = new DatabaseHelper(getContext()); System.out.println(" return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase sqlDB = db.getReadableDatabase(); SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); switch (sUriMatcher.match(uri)) { case MOVIES: queryBuilder.setTables(MoviesTable.TABLE_MOVIES); break; case MOVIES_ID: selection = selection + MoviesTable.COLUMN_MOVIE_ID + " = " + uri.getLastPathSegment(); queryBuilder.setTables(MoviesTable.TABLE_MOVIES); break; case TAGS: queryBuilder.setTables(TagsTable.TABLE_TAGS); break; case TAGS_ID: selection = selection + TagsTable.COLUMN_TAG_ID + " = " + uri.getLastPathSegment(); queryBuilder.setTables(TagsTable.TABLE_TAGS); break; case HAS_TAG: String tables = MoviesTable.TABLE_MOVIES + " LEFT OUTER JOIN " + HasTagTable.TABLE_HAS_TAG + " ON " + MoviesTable.TABLE_MOVIES + "." + MoviesTable.COLUMN_MOVIE_ID + " = " + HasTagTable.TABLE_HAS_TAG + "." + HasTagTable.COLUMN_MOVIE_ID + " LEFT OUTER JOIN " + TagsTable.TABLE_TAGS + " ON " + HasTagTable.TABLE_HAS_TAG + "." + HasTagTable.COLUMN_TAG_ID + " = " + TagsTable.TABLE_TAGS + "." + TagsTable.COLUMN_TAG_ID; queryBuilder.setTables(tables); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } Cursor cursor = queryBuilder.query(sqlDB, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase sqlDB = db.getWritableDatabase(); int updatedRows; switch (sUriMatcher.match(uri)) { case MOVIES: // Nothing need to be added to selection updatedRows = sqlDB.update(MoviesTable.TABLE_MOVIES, values, selection, selectionArgs); break; case MOVIES_ID: selection = selection + MoviesTable.COLUMN_MOVIE_ID + " = " + uri.getLastPathSegment(); updatedRows = sqlDB.update(MoviesTable.TABLE_MOVIES, values, selection, selectionArgs); break; case TAGS: // Nothing need to be added to selection updatedRows = sqlDB.update(TagsTable.TABLE_TAGS, values, selection, selectionArgs); break; case TAGS_ID: selection = selection + TagsTable.COLUMN_TAG_ID + " = " + uri.getLastPathSegment(); updatedRows = sqlDB.update(TagsTable.TABLE_TAGS, values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // Notify Observers getContext().getContentResolver().notifyChange(CONTENT_URI_MOVIES, null); getContext().getContentResolver().notifyChange(CONTENT_URI_TAGS, null); getContext().getContentResolver().notifyChange(CONTENT_URI_HAS_TAG, null); return updatedRows; } }
package org.mobicents.protocols.asn; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.BitSet; /** * Represents external type, should be extended to allow getting real type of * data, once External ends decoding. Decoding should be done as follows in * subclass:<br> * * <pre> * &lt;b&gt;decode(){ * super.decode(); * if(super.getType == requiredType) * this.decode(); * }else * { * //indicate error * } * &lt;/b&gt; * </pre> * . Also encode/decode methods should be extended * * @author baranowb * @author amit bhayani * */ public class External { // FIXME: makes this proper, it should be kind of universal container.... protected static final int _TAG_EXTERNAL_CLASS = Tag.CLASS_UNIVERSAL; // universal protected static final boolean _TAG_EXTERNAL_PC_PRIMITIVE = false; // isPrimitive // ENCODING TYPE protected static final int _TAG_ASN = 0x00; protected static final int _TAG_ASN_CLASS = Tag.CLASS_CONTEXT_SPECIFIC; // context // spec protected static final boolean _TAG_ASN_PC_PRIMITIVE = false; // isPrimitive // in case of Arbitrary and OctetAligned, we dont make decision if its // constructed or primitive, its done for us :) protected static final int _TAG_ARBITRARY = 0x02; // this is bit string protected static final int _TAG_ARBITRARY_CLASS = Tag.CLASS_CONTEXT_SPECIFIC; // context // spec protected static final int _TAG_OCTET_ALIGNED = 0x01; // this is bit // string protected static final int _TAG_OCTET_ALIGNED_CLASS = Tag.CLASS_CONTEXT_SPECIFIC; // context // spec protected static final int _TAG_IMPLICIT_SEQUENCE = 0x08; // some state vars // ENCODE TYPE - wtf, ASN is really mind blowing, cmon.... // If Amit reads this, he will smile. // ENCODE AS.... boom protected boolean oid = false; protected boolean integer = false; protected boolean objDescriptor = false; // actual vals protected long[] oidValue = null; protected long indirectReference = 0; protected Object objDescriptorValue = null; // ENCoDING private boolean asn = false; private boolean octet = false; private boolean arbitrary = false; // data in binary form for ASN and octet string private byte[] data; private BitSet bitDataString; //FIXME: ensure structure from file and if it does not allow more than one type of data, enforce that! public void decode(AsnInputStream ais) throws AsnException { try { // The definition of EXTERNAL is // EXTERNAL ::= [UNIVERSAL 8] IMPLICIT SEQUENCE { // direct-reference OBJECT IDENTIFIER OPTIONAL, // indirect-reference INTEGER OPTIONAL, // data-value-descriptor ObjectDescriptor OPTIONAL, // encoding CHOICE { // single-ASN1-type [0] ANY, // octet-aligned [1] IMPLICIT OCTET STRING, // arbitrary [2] IMPLICIT BIT STRING }} byte[] sequence = ais.readSequence(); AsnInputStream localAsnIS = new AsnInputStream( new ByteArrayInputStream(sequence)); int tag; int len; while (localAsnIS.available() > 0) { tag = localAsnIS.readTag(); // we can have one of if (tag == Tag.OBJECT_IDENTIFIER) { this.oidValue = localAsnIS.readObjectIdentifier(); this.setOid(true); } else if (tag == Tag.INTEGER) { this.indirectReference = localAsnIS.readInteger(); this.setInteger(true); } else if (tag == Tag.OBJECT_DESCRIPTOR) { throw new AsnException(); } else { throw new AsnException("Unrecognized tag value: " + tag); } // read encoding tag = localAsnIS.readTag(); len = localAsnIS.readLength(); if (tag == External._TAG_ASN) { setAsn(true); // this we dont decode...., we have no idea what is realy // there, might be simple type... // or app specific.... data = new byte[len]; localAsnIS.read(data); } else if (tag == External._TAG_OCTET_ALIGNED) { setOctet(true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); localAsnIS.readOctetString(bos); setEncodeType(bos.toByteArray()); } else if (tag == External._TAG_ARBITRARY) { setArbitrary(true); this.bitDataString = new BitSet(); this.setEncodeBitStringType(this.bitDataString); tag = localAsnIS.readTag(); if(tag != Tag.STRING_BIT) { throw new AsnException("Wrong tag value '"+tag+"' expected '"+Tag.STRING_BIT+"'"); } BitSet bitSet = new BitSet(); localAsnIS.readBitString(bitSet); this.setEncodeBitStringType(bitSet); } else { throw new AsnException(); } } } catch (IOException e) { throw new AsnException(e); } } public void encode(AsnOutputStream aos) throws AsnException { try { // something to do encoding AsnOutputStream localOutput = new AsnOutputStream(); if (oid) { localOutput.writeObjectIdentifier(this.oidValue); } else if (integer) { // FIXME: remove cast, now it takes only int, should take long localOutput.writeInteger((int) this.indirectReference); } else if (objDescriptor) { throw new AsnException(); } else { throw new AsnException(); } // told, you, mind blowing! if (asn) { byte[] childData = getEncodeType(); localOutput.writeTag(_TAG_ASN_CLASS, _TAG_ASN_PC_PRIMITIVE, _TAG_ASN); localOutput.writeLength(childData.length); localOutput.write(childData); // childData = localOutput.toByteArray(); // localOutput.reset(); } else if (octet) { byte[] childData = getEncodeType(); // get child class.... I think its done like that.... boolean childConstructor = ((childData[0] & 0x20) >> 5) == Tag.PC_PRIMITIVITE; localOutput.writeTag(_TAG_OCTET_ALIGNED_CLASS, childConstructor, _TAG_OCTET_ALIGNED); localOutput.writeLength(childData.length); localOutput.write(childData); // childData = localOutput.toByteArray(); // localOutput.reset(); } else if (arbitrary) { AsnOutputStream _bitStrinAos = new AsnOutputStream(); _bitStrinAos.writeStringBinary(this.bitDataString); byte[] childData = _bitStrinAos.toByteArray(); boolean childConstructor = ((childData[0] & 0x20) >> 5) == Tag.PC_PRIMITIVITE; localOutput.writeTag(_TAG_ARBITRARY_CLASS, childConstructor, _TAG_ARBITRARY); localOutput.writeLength(childData.length); localOutput.write(childData); // childData = localOutput.toByteArray(); // localOutput.reset(); } else { throw new AsnException(); } byte[] externalChildData = localOutput.toByteArray(); // Write the UserInformation Tag and length aos.writeTag(Tag.CLASS_UNIVERSAL, false, Tag.EXTERNAL); aos.writeLength(externalChildData.length); // Write the Sequence Tag and length // aos.writeTag(Tag.CLASS_UNIVERSAL, true, Tag.SEQUENCE); // aos.writeLength(externalChildData.length); // Write actual Data now aos.write(externalChildData); return; } catch (IOException e) { throw new AsnException(e); } } public byte[] getEncodeType() throws AsnException { return data; } public void setEncodeType(byte[] data) { this.data = data; } public BitSet getEncodeBitStringType() throws AsnException { return (BitSet) bitDataString.clone(); } public void setEncodeBitStringType(BitSet data) { this.bitDataString = data; this.setArbitrary(true); } /** * @return the oid */ public boolean isOid() { return oid; } /** * @param oid * the oid to set */ public void setOid(boolean oid) { this.oid = oid; if (oid) { setInteger(false); setObjDescriptor(false); } } /** * @return the integer */ public boolean isInteger() { return integer; } /** * @param integer * the integer to set */ public void setInteger(boolean integer) { this.integer = integer; if (integer) { setOid(false); setObjDescriptor(false); } } /** * @return the objDescriptor */ public boolean isObjDescriptor() { return objDescriptor; } /** * @param objDescriptor * the objDescriptor to set */ public void setObjDescriptor(boolean objDescriptor) { this.objDescriptor = objDescriptor; if (objDescriptor) { setOid(false); setInteger(false); } } /** * @return the oidValue */ public long[] getOidValue() { return oidValue; } /** * @param oidValue * the oidValue to set */ public void setOidValue(long[] oidValue) { this.oidValue = oidValue; } /** * @return the integerValue */ public long getIndirectReference() { return indirectReference; } /** * @param integerValue * the integerValue to set */ public void setIndirectReference(long indirectReference) { this.indirectReference = indirectReference; } /** * @return the objDescriptorValue */ public Object getObjDescriptorValue() { return objDescriptorValue; } /** * @param objDescriptorValue * the objDescriptorValue to set */ public void setObjDescriptorValue(Object objDescriptorValue) { this.objDescriptorValue = objDescriptorValue; } /** * @return the asn */ public boolean isAsn() { return asn; } /** * @param asn * the asn to set */ public void setAsn(boolean asn) { this.asn = asn; if (asn) { setArbitrary(false); setOctet(false); } } /** * @return the octet */ public boolean isOctet() { return octet; } /** * @param octet * the octet to set */ public void setOctet(boolean octet) { this.octet = octet; if (octet) { setArbitrary(false); setAsn(false); } } /** * @return the arbitrary */ public boolean isArbitrary() { return arbitrary; } /** * @param arbitrary * the arbitrary to set */ public void setArbitrary(boolean arbitrary) { this.arbitrary = arbitrary; if (arbitrary) { setObjDescriptor(false); setAsn(false); } } }
package org.opencms.ade.publish.client; import org.opencms.ade.publish.client.CmsPublishItemStatus.Signal; import org.opencms.ade.publish.shared.CmsPublishResource; import org.opencms.gwt.client.ui.CmsList; import org.opencms.gwt.client.ui.CmsListItemWidget; import org.opencms.gwt.client.ui.CmsPreviewDialog; import org.opencms.gwt.client.ui.CmsPushButton; import org.opencms.gwt.client.ui.CmsSimpleListItem; import org.opencms.gwt.client.ui.I_CmsButton; import org.opencms.gwt.client.ui.I_CmsButton.ButtonStyle; import org.opencms.gwt.client.ui.css.I_CmsImageBundle; import org.opencms.gwt.client.ui.css.I_CmsInputLayoutBundle; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import org.opencms.gwt.client.ui.input.CmsCheckBox; import org.opencms.gwt.client.ui.tree.CmsTreeItem; import org.opencms.gwt.client.util.CmsDomUtil; import org.opencms.gwt.client.util.CmsResourceStateUtil; import org.opencms.gwt.client.util.CmsStyleVariable; import org.opencms.gwt.shared.CmsIconUtil; import org.opencms.gwt.shared.CmsListInfoBean; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.util.List; import java.util.Map; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.dom.client.Style.Visibility; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; /** * A panel representing a single publish group.<p> * * @since 8.0.0 */ public class CmsPublishGroupPanel extends Composite { /** The CSS bundle used for this widget. */ protected static final I_CmsPublishCss CSS = I_CmsPublishLayoutBundle.INSTANCE.publishCss(); /** The number of button slits. */ private static final int NUM_BUTTON_SLOTS = 3; /** The slot for the preview button. */ private static final int SLOT_PREVIEW = 0; /** The slot for the 'remove' checkbox. */ private static final int SLOT_REMOVE = 1; /** The slot for the warning symbol. */ private static final int SLOT_WARNING = 2; /** Text metrics key. */ private static final String TM_PUBLISH_LIST = "PublishList"; /** The group index for this panel's corresponding group. */ protected int m_groupIndex; /** The data model for the publish dialog. */ protected CmsPublishDataModel m_model; /** The handler which is called when the publish item selection changes. */ protected I_CmsPublishSelectionChangeHandler m_selectionChangeHandler; /** The global map of selection controllers of *ALL* groups (to which this group's selection controllers are added). */ private Map<CmsUUID, CmsPublishItemSelectionController> m_controllersById; /** The group header (containing the label and add/remove buttons). */ private CmsSimpleListItem m_header = new CmsSimpleListItem(); /** The number of loaded publish item widgets for this group (used for scrolling).<p> */ private int m_itemIndex; /** The root panel of this widget. */ private CmsList<CmsTreeItem> m_panel = new CmsList<CmsTreeItem>(); /** The publish resources of the current group.<p>*/ private List<CmsPublishResource> m_publishResources; /** The button for selecting all resources in the group. */ private CmsPushButton m_selectAll; /** The button for deselecting all resources in the group. */ private CmsPushButton m_selectNone; /** A flag which indicates whether only resources with problems should be shown. */ private boolean m_showProblemsOnly; /** * Constructs a new instance.<p> * * @param title the title of the group * @param groupIndex the index of the group which this panel should render * @param selectionChangeHandler the handler for selection changes for publish resources * @param model the data model for the publish resources * @param controllersById the map of selection controllers to which this panel's selection controllers should be added * @param showProblemsOnly if true, sets this panel into "show resources with problems only" mode */ public CmsPublishGroupPanel( String title, int groupIndex, I_CmsPublishSelectionChangeHandler selectionChangeHandler, CmsPublishDataModel model, Map<CmsUUID, CmsPublishItemSelectionController> controllersById, boolean showProblemsOnly) { initWidget(m_panel); m_panel.add(m_header); m_model = model; m_groupIndex = groupIndex; m_publishResources = model.getGroups().get(groupIndex).getResources(); m_controllersById = controllersById; m_panel.truncate(TM_PUBLISH_LIST, CmsPublishDialog.DIALOG_WIDTH); initSelectButtons(); if (groupIndex == 0) { m_model.signalGroup(Signal.publish, 0); } if (hasOnlyProblemResources()) { m_selectAll.setEnabled(false); m_selectNone.setEnabled(false); } m_showProblemsOnly = showProblemsOnly; if (hasNoProblemResources() && showProblemsOnly) { this.setVisible(false); } HTML label = new HTML(); label.setHTML(title + CmsPublishSelectPanel.formatResourceCount(m_publishResources.size())); label.addStyleName(CSS.groupHeader()); m_header.add(label); FlowPanel clear = new FlowPanel(); clear.setStyleName(CSS.clear()); m_header.add(clear); m_selectionChangeHandler = selectionChangeHandler; } /** * Creates a basic list item widget for a given publish resource bean.<p> * * @param resourceBean the publish resource bean * * @return the list item widget representing the publish resource bean */ public static CmsListItemWidget createListItemWidget(final CmsPublishResource resourceBean) { CmsListInfoBean info = new CmsListInfoBean(); info.setTitle(getTitle(resourceBean)); info.setSubTitle(resourceBean.getName()); String stateLabel = org.opencms.gwt.client.Messages.get().key( org.opencms.gwt.client.Messages.GUI_RESOURCE_STATE_0); String stateName = CmsResourceStateUtil.getStateName(resourceBean.getState()); // this can be null for the source resources of broken relations in the 'broken links' // panel since these resources don't have to be new or deleted or changed if (stateName != null) { info.addAdditionalInfo(stateLabel, stateName, CmsResourceStateUtil.getStateStyle(resourceBean.getState())); } CmsListItemWidget itemWidget = new CmsListItemWidget(info); for (int i = 0; i < NUM_BUTTON_SLOTS; i++) { SimplePanel panel = new SimplePanel(); panel.getElement().getStyle().setWidth(20, Unit.PX); panel.getElement().getStyle().setHeight(20, Unit.PX); if (i == SLOT_WARNING) { panel.addStyleName(I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().permaVisible()); } itemWidget.addButton(panel); } if (CmsPublishDataModel.hasProblems(resourceBean)) { Image warningImage = new Image(I_CmsImageBundle.INSTANCE.warningSmallImage()); warningImage.setTitle(resourceBean.getInfo().getValue()); warningImage.addStyleName(I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().permaVisible()); fillButtonSlot(itemWidget, SLOT_WARNING, warningImage); } String noPreviewReason = resourceBean.getInfo() == null ? null : resourceBean.getInfo().getNoPreviewReason(); CmsPushButton previewButton = new CmsPushButton(); previewButton.setImageClass(I_CmsImageBundle.INSTANCE.style().previewIcon()); previewButton.setButtonStyle(ButtonStyle.TRANSPARENT, null); previewButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { CmsPushButton button = (CmsPushButton)event.getSource(); CmsDomUtil.ensureMouseOut(button.getElement()); CmsPreviewDialog.showPreviewForResource(resourceBean.getId()); } }); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(noPreviewReason)) { previewButton.disable(noPreviewReason); } fillButtonSlot(itemWidget, SLOT_PREVIEW, previewButton); itemWidget.setUnselectable(); itemWidget.setIcon(CmsIconUtil.getResourceIconClasses(resourceBean.getResourceType(), false)); return itemWidget; } /** * Fills a slot for a button in a publish list item widget.<p> * * @param listItemWidget the list item widget * @param index the slot index * @param widget the widget which should be displayed in the slot */ private static void fillButtonSlot(CmsListItemWidget listItemWidget, int index, Widget widget) { SimplePanel panel = (SimplePanel)listItemWidget.getButton(index); panel.clear(); panel.add(widget); } /** * Utility method for getting the title of a publish resource bean, or a default title * if the bean has no title.<p> * * @param resourceBean the resource bean for which the title should be retrieved * * @return the bean's title, or a default title */ private static String getTitle(CmsPublishResource resourceBean) { String title = resourceBean.getTitle(); if ((title == null) || title.equals("")) { title = Messages.get().key(Messages.GUI_NO_TITLE_0); } return title; } /** * Adds the list item for the next publish resource and returns true on success, while * also incrementing the internal item index.<p> * * @return true if an item was added */ public boolean addNextItem() { if (m_itemIndex >= m_publishResources.size()) { return false; } CmsPublishResource res = m_publishResources.get(m_itemIndex); m_itemIndex += 1; if (m_showProblemsOnly && (!CmsPublishDataModel.hasProblems(res))) { return false; } else { addItem(res); return true; } } /** * Returns true if there are more potential items to add.<p> * * @return true if there are possibly more items */ public boolean hasMoreItems() { return m_itemIndex < m_publishResources.size(); } /** * Returns true if the corresponding group has no resources with problems.<p> * * @return true if the group for this panel has no resources with problems */ protected boolean hasNoProblemResources() { return 0 == m_model.countResourcesInGroup( new CmsPublishDataModel.HasProblems(), m_model.getGroups().get(m_groupIndex).getResources()); } /** * Returns true if the corresponding group has only resources with problems.<p> * * @return true if the group for this panel has only resources with problems. */ protected boolean hasOnlyProblemResources() { return m_model.getGroups().get(m_groupIndex).getResources().size() == m_model.countResourcesInGroup( new CmsPublishDataModel.HasProblems(), m_model.getGroups().get(m_groupIndex).getResources()); } /** * Adds a resource bean to this group.<p> * * @param resourceBean the resource bean which should be added */ private void addItem(CmsPublishResource resourceBean) { CmsTreeItem row = buildItem(resourceBean, m_model.getStatus(resourceBean.getId()), false); m_panel.add(row); for (CmsPublishResource related : resourceBean.getRelated()) { row.addChild(buildItem(related, m_model.getStatus(related.getId()), true)); } } /** * Creates a widget from resource bean data.<p> * * @param resourceBean the resource bean for which a widget should be constructed * @param status the publish item status * @param isSubItem true if this is not a top-level publish item * * @return a widget representing the resource bean */ private CmsTreeItem buildItem(final CmsPublishResource resourceBean, CmsPublishItemStatus status, boolean isSubItem) { CmsListItemWidget itemWidget = createListItemWidget(resourceBean); final CmsStyleVariable styleVar = new CmsStyleVariable(itemWidget); styleVar.setValue(CSS.itemToKeep()); final CmsCheckBox checkbox = new CmsCheckBox(); CmsTreeItem row; row = new CmsTreeItem(true, checkbox, itemWidget); if (isSubItem) { checkbox.getElement().getStyle().setVisibility(Visibility.HIDDEN); } row.setOpen(false); row.addStyleName(CSS.publishRow()); // we do not need most of the interactive elements for the sub-items if (!isSubItem) { ClickHandler checkboxHandler = new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { boolean checked = checkbox.isChecked(); m_model.signal(checked ? Signal.publish : Signal.unpublish, resourceBean.getId()); } }; checkbox.addClickHandler(checkboxHandler); final boolean hasProblem = CmsPublishDataModel.hasProblems(resourceBean); if (hasProblem) { // can't select resource with problems checkbox.setChecked(false); checkbox.setEnabled(false); } final CmsCheckBox remover = new CmsCheckBox(); final CmsPublishItemSelectionController controller = new CmsPublishItemSelectionController( resourceBean.getId(), checkbox, remover, styleVar, hasProblem); m_controllersById.put(resourceBean.getId(), controller); remover.setTitle(Messages.get().key(Messages.GUI_PUBLISH_REMOVE_BUTTON_0)); remover.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent e) { boolean remove = remover.isChecked(); m_model.signal(remove ? Signal.remove : Signal.unremove, resourceBean.getId()); } }); fillButtonSlot(itemWidget, SLOT_REMOVE, remover); controller.update(status); } return row; } /** * Initializes the "select all/none" buttons, adds them to the group header and * attaches event handlers to them.<p> */ private void initSelectButtons() { m_selectAll = new CmsPushButton(); m_selectAll.setText(Messages.get().key(Messages.GUI_PUBLISH_TOP_PANEL_ALL_BUTTON_0)); m_selectAll.setImageClass(I_CmsInputLayoutBundle.INSTANCE.inputCss().checkBoxImageChecked()); m_selectAll.setSize(I_CmsButton.Size.small); m_selectAll.setUseMinWidth(true); m_selectAll.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { m_model.signalGroup(Signal.publish, m_groupIndex); } }); m_selectNone = new CmsPushButton(); m_selectNone.setText(Messages.get().key(Messages.GUI_PUBLISH_TOP_PANEL_NONE_BUTTON_0)); m_selectNone.setImageClass(I_CmsInputLayoutBundle.INSTANCE.inputCss().checkBoxImageUnchecked()); m_selectNone.setSize(I_CmsButton.Size.small); m_selectNone.setUseMinWidth(true); m_selectNone.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { m_model.signalGroup(Signal.unpublish, m_groupIndex); } }); FlowPanel selectButtons = new FlowPanel(); selectButtons.add(m_selectAll); selectButtons.add(m_selectNone); selectButtons.setStyleName(CSS.selectButtons()); m_header.add(selectButtons); } }
package com.imagepicker; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import android.widget.ArrayAdapter; import android.webkit.MimeTypeMap; import android.content.pm.PackageManager; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.WritableMap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ImagePickerModule extends ReactContextBaseJavaModule implements ActivityEventListener { static final int REQUEST_LAUNCH_IMAGE_CAPTURE = 1; static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 2; static final int REQUEST_LAUNCH_VIDEO_LIBRARY = 3; static final int REQUEST_LAUNCH_VIDEO_CAPTURE = 4; private final ReactApplicationContext mReactContext; private Uri mCameraCaptureURI; private Uri mCropImagedUri; private Callback mCallback; private Boolean noData = false; private Boolean tmpImage; private Boolean allowEditing = false; private Boolean pickVideo = false; private int maxWidth = 0; private int maxHeight = 0; private int aspectX = 0; private int aspectY = 0; private int quality = 100; private int angle = 0; private Boolean forceAngle = false; private int videoQuality = 1; private int videoDurationLimit = 0; WritableMap response; public ImagePickerModule(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(this); mReactContext = reactContext; } @Override public String getName() { return "ImagePickerManager"; } @ReactMethod public void showImagePicker(final ReadableMap options, final Callback callback) { Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { response = Arguments.createMap(); response.putString("error", "can't find current Activity"); callback.invoke(response); return; } final List<String> titles = new ArrayList<String>(); final List<String> actions = new ArrayList<String>(); String cancelButtonTitle = getReactApplicationContext().getString(android.R.string.cancel); if (options.hasKey("takePhotoButtonTitle") && options.getString("takePhotoButtonTitle") != null && !options.getString("takePhotoButtonTitle").isEmpty() && isCameraAvailable()) { titles.add(options.getString("takePhotoButtonTitle")); actions.add("photo"); } if (options.hasKey("chooseFromLibraryButtonTitle") && options.getString("chooseFromLibraryButtonTitle") != null && !options.getString("chooseFromLibraryButtonTitle").isEmpty()) { titles.add(options.getString("chooseFromLibraryButtonTitle")); actions.add("library"); } if (options.hasKey("cancelButtonTitle") && !options.getString("cancelButtonTitle").isEmpty()) { cancelButtonTitle = options.getString("cancelButtonTitle"); } if (options.hasKey("customButtons")) { ReadableMap buttons = options.getMap("customButtons"); ReadableMapKeySetIterator it = buttons.keySetIterator(); // Keep the current size as the iterator returns the keys in the reverse order they are defined int currentIndex = titles.size(); while (it.hasNextKey()) { String key = it.nextKey(); titles.add(currentIndex, key); actions.add(currentIndex, buttons.getString(key)); } } titles.add(cancelButtonTitle); actions.add("cancel"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(currentActivity, android.R.layout.select_dialog_item, titles); AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity); if (options.hasKey("title") && options.getString("title") != null && !options.getString("title").isEmpty()) { builder.setTitle(options.getString("title")); } builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int index) { String action = actions.get(index); response = Arguments.createMap(); switch (action) { case "photo": launchCamera(options, callback); break; case "library": launchImageLibrary(options, callback); break; case "cancel": response.putBoolean("didCancel", true); callback.invoke(response); break; default: // custom button response.putString("customButton", action); callback.invoke(response); } } }); final AlertDialog dialog = builder.create(); /** * override onCancel method to callback cancel in case of a touch outside of * the dialog or the BACK key pressed */ dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { response = Arguments.createMap(); dialog.dismiss(); response.putBoolean("didCancel", true); callback.invoke(response); } }); dialog.show(); } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchCamera(final ReadableMap options, final Callback callback) { int requestCode; Intent cameraIntent; response = Arguments.createMap(); if (!isCameraAvailable()) { response.putString("error", "Camera not available"); callback.invoke(response); return; } Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { response.putString("error", "can't find current Activity"); callback.invoke(response); return; } parseOptions(options); if (pickVideo == true) { requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE; cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, videoQuality); if (videoDurationLimit > 0) { cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, videoDurationLimit); } } else { requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE; cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // we create a tmp file to save the result File imageFile = createNewFile(true); mCameraCaptureURI = Uri.fromFile(imageFile); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile)); if (allowEditing == true) { cameraIntent.putExtra("crop", "true"); cameraIntent.putExtra("aspectX", aspectX); cameraIntent.putExtra("aspectY", aspectY); } } if (cameraIntent.resolveActivity(mReactContext.getPackageManager()) == null) { response.putString("error", "Cannot launch camera"); callback.invoke(response); return; } mCallback = callback; try { currentActivity.startActivityForResult(cameraIntent, requestCode); } catch (ActivityNotFoundException e) { e.printStackTrace(); response = Arguments.createMap(); response.putString("error", "Cannot launch camera"); callback.invoke(response); } } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchImageLibrary(final ReadableMap options, final Callback callback) { int requestCode; Intent libraryIntent; Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { response = Arguments.createMap(); response.putString("error", "can't find current Activity"); callback.invoke(response); return; } parseOptions(options); if (pickVideo == true) { requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK); private File createFileFromURI(Uri uri) throws Exception { File file = new File(mReactContext.getCacheDir(), "photo-" + uri.getLastPathSegment()); InputStream input = mReactContext.getContentResolver().openInputStream(uri); OutputStream output = new FileOutputStream(file); try { byte[] buffer = new byte[4 * 1024]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); input.close(); } return file; } private String getBase64StringFromFile(String absoluteFilePath) { InputStream inputStream = null; try { inputStream = new FileInputStream(absoluteFilePath); } catch (FileNotFoundException e) { e.printStackTrace(); } byte[] bytes; byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } bytes = output.toByteArray(); return Base64.encodeToString(bytes, Base64.NO_WRAP); } /** * Create a resized image to fill the maxWidth/maxHeight values,the quality * value and the angle value * * @param realPath * @param initialWidth * @param initialHeight * @return resized file */ private File getResizedImage(final String realPath, final int initialWidth, final int initialHeight) { Bitmap photo = BitmapFactory.decodeFile(realPath); if (photo == null) { return null; } Bitmap scaledphoto = null; if (maxWidth == 0) { maxWidth = initialWidth; } if (maxHeight == 0) { maxHeight = initialHeight; } double widthRatio = (double) maxWidth / initialWidth; double heightRatio = (double) maxHeight / initialHeight; double ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio; Matrix matrix = new Matrix(); matrix.postRotate(angle); matrix.postScale((float) ratio, (float) ratio); ExifInterface exif; try { exif = new ExifInterface(realPath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); if (orientation == 6) { matrix.postRotate(90); } else if (orientation == 3) { matrix.postRotate(180); } else if (orientation == 8) { matrix.postRotate(270); } } catch (IOException e) { e.printStackTrace(); } scaledphoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); scaledphoto.compress(Bitmap.CompressFormat.JPEG, quality, bytes); File f = createNewFile(false); FileOutputStream fo; try { fo = new FileOutputStream(f); try { fo.write(bytes.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } // recycle to avoid java.lang.OutOfMemoryError if (photo != null) { scaledphoto.recycle(); photo.recycle(); scaledphoto = null; photo = null; } return f; } /** * Create a new file * * @return an empty file */ private File createNewFile(final boolean forcePictureDirectory) { String filename = "image-" + UUID.randomUUID().toString() + ".jpg"; if (tmpImage && forcePictureDirectory != true) { return new File(mReactContext.getCacheDir(), filename); } else { File path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File f = new File(path, filename); try { path.mkdirs(); f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } return f; } } private void putExtraFileInfo(final String path, WritableMap response) { // size && filename try { File f = new File(path); response.putDouble("fileSize", f.length()); response.putString("fileName", f.getName()); } catch (Exception e) { e.printStackTrace(); } // type String extension = MimeTypeMap.getFileExtensionFromUrl(path); if (extension != null) { response.putString("type", MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)); } } private void parseOptions(final ReadableMap options) { noData = false; if (options.hasKey("noData")) { noData = options.getBoolean("noData"); } maxWidth = 0; if (options.hasKey("maxWidth")) { maxWidth = options.getInt("maxWidth"); } maxHeight = 0; if (options.hasKey("maxHeight")) { maxHeight = options.getInt("maxHeight"); } aspectX = 0; if (options.hasKey("aspectX")) { aspectX = options.getInt("aspectX"); } aspectY = 0; if (options.hasKey("aspectY")) { aspectY = options.getInt("aspectY"); } quality = 100; if (options.hasKey("quality")) { quality = (int) (options.getDouble("quality") * 100); } tmpImage = true; if (options.hasKey("storageOptions")) { tmpImage = false; } allowEditing = false; if (options.hasKey("allowsEditing")) { allowEditing = options.getBoolean("allowsEditing"); } forceAngle = false; angle = 0; if (options.hasKey("angle")) { forceAngle = true; angle = options.getInt("angle"); } pickVideo = false; if (options.hasKey("mediaType") && options.getString("mediaType").equals("video")) { pickVideo = true; } videoQuality = 1; if (options.hasKey("videoQuality") && options.getString("videoQuality").equals("low")) { videoQuality = 0; } videoDurationLimit = 0; if (options.hasKey("durationLimit")) { videoDurationLimit = options.getInt("durationLimit"); } } }
package fr.o80.sample.lib.core.ui; import android.app.Fragment; import android.app.FragmentManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import butterknife.BindView; import butterknife.ButterKnife; import fr.o80.sample.lib.core.Feature; import sample.o80.fr.lib.R; import sample.o80.fr.lib.R2; /** * @author Olivier Perez */ public abstract class BaseDrawerActivity extends AppCompatActivity implements LibNavigationView.Listener { @BindView(R2.id.navigation_view) protected LibNavigationView libNavigationView; @BindView(R2.id.drawer_layout) protected DrawerLayout drawer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); ButterKnife.bind(this); initDagger(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); libNavigationView.setListener(this); FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager.findFragmentById(R.id.main_container) == null) { Fragment initFragment = getInitFragment(); if (initFragment != null) { fragmentManager .beginTransaction() .replace(R.id.main_container, initFragment) .commit(); } } } @Override public void onFeatureClicked(Feature feature) { drawer.closeDrawers(); feature.open(this); } protected abstract Fragment getInitFragment(); protected void initDagger() { } }
package com.github.hisaichi5518.kise; public interface UnitActions<ACTION_PARAM> { void customAction(ACTION_PARAM actionParam) throws Exception; void defaultAction(ACTION_PARAM actionParam); }
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.model.Poll; import com.pengrad.telegrambot.model.request.ParseMode; /** * Stas Parshin * 17 April 2019 */ public class SendPoll extends AbstractSendRequest<SendPoll> { public SendPoll(Object chatId, String question, String... options) { super(chatId); add("question", question); add("options", serialize(options)); } public SendPoll isAnonymous(boolean isAnonymous) { return add("is_anonymous", isAnonymous); } public SendPoll type(String type) { return add("type", type); } public SendPoll type(Poll.Type type) { return add("type", type.name()); } public SendPoll allowsMultipleAnswers(boolean allowsMultipleAnswers) { return add("allows_multiple_answers", allowsMultipleAnswers); } public SendPoll correctOptionId(int correctOptionId) { return add("correct_option_id", correctOptionId); } public SendPoll explanation(String explanation) { return add("explanation", explanation); } public SendPoll explanationParseMode(ParseMode parseMode) { return add("explanation_parse_mode", parseMode.name()); } public SendPoll openPeriod(int openPeriod) { return add("open_period", openPeriod); } public SendPoll closeDate(long closeDate) { return add("close_date", closeDate); } public SendPoll isClosed(boolean isClosed) { return add("is_closed", isClosed); } }
package liquibase.datatype.core; import java.util.Arrays; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; import liquibase.util.StringUtils; @DataTypeInfo(name="float", aliases = {"java.sql.Types.FLOAT", "java.lang.Float", "real", "java.sql.Types.REAL"}, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class FloatType extends LiquibaseDataType { @Override public DatabaseDataType toDatabaseDataType(Database database) { String originalDefinition = StringUtils.trimToEmpty(getRawDefinition()); if (database instanceof MSSQLDatabase) { if ("real".equalsIgnoreCase(originalDefinition) || "[real]".equals(originalDefinition) || "java.lang.Float".equals(originalDefinition) || "java.sql.Types.REAL".equals(originalDefinition)) { return new DatabaseDataType(database.escapeDataTypeName("real")); } Object[] parameters = getParameters(); if (parameters.length == 0) { parameters = new Object[] { 53 }; } else if (parameters.length > 1) { parameters = Arrays.copyOfRange(parameters, 0, 1); } return new DatabaseDataType(database.escapeDataTypeName("float"), parameters); } if (database instanceof MySQLDatabase || database instanceof DB2Database || database instanceof H2Database) { if (originalDefinition.equalsIgnoreCase("REAL")) { return new DatabaseDataType("REAL"); } } if (database instanceof FirebirdDatabase || database instanceof InformixDatabase) { return new DatabaseDataType("FLOAT"); } else if (database instanceof PostgresDatabase) { if (originalDefinition.equalsIgnoreCase("real")) { return new DatabaseDataType("REAL"); } } return super.toDatabaseDataType(database); } //sqlite // } else if (columnTypeString.equals("REAL") || // columnTypeString.toLowerCase(Locale.ENGLISH).contains("float")) { // type = new FloatType("REAL"); //postgres // } else if (type.toDatabaseDataType().toLowerCase().startsWith("float8")) { // type.setDataTypeName("FLOAT8"); // } else if (type.toDatabaseDataType().toLowerCase().startsWith("float4")) { // type.setDataTypeName("FLOAT4"); }
package io.spine.client; import io.spine.core.UserId; import io.spine.server.BoundedContextBuilder; import io.spine.server.Server; import io.spine.test.client.UserAccount; import io.spine.test.client.event.UserLoggedIn; import io.spine.test.client.event.UserLoggedOut; import io.spine.testing.TestValues; import io.spine.testing.core.given.GivenUserId; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import static com.google.common.truth.Truth.assertThat; import static io.spine.client.Filters.eq; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @DisplayName("`Client` should") class ClientTest { @SuppressWarnings("StaticVariableMayNotBeInitialized") private static Server server; @SuppressWarnings("StaticVariableMayNotBeInitialized") private static int port; @BeforeAll static void createServer() throws IOException { port = TestValues.random(64000, 65000); server = Server.newBuilder() .setPort(port) .add(BoundedContextBuilder.assumingTests()) .build(); server.start(); } @AfterAll @SuppressWarnings("StaticVariableUsedBeforeInitialization") // see createServer(). static void shutdownServer() { server.shutdown(); } private Client client; @BeforeEach void createClient() { client = Client.connectTo("localhost", port) .build(); } @AfterEach void closeClient() { client.close(); } @Test @DisplayName("be opened upon creation") void opened() { assertTrue(client.isOpen()); } @Test @DisplayName("close upon request") void closing() { client.close(); assertFalse(client.isOpen()); } @Test @DisplayName("have `shutdown()` alias method") void shutdown() { client.shutdown(); assertFalse(client.isOpen()); } @Test @DisplayName("create requests on behalf of a user") void onBehalf() { UserId expected = GivenUserId.generated(); ClientRequest request = client.onBehalfOf(expected); assertThat(request.user()) .isEqualTo(expected); } @Test @DisplayName("create requests for a guest user") void guestRequest() { ClientRequest request = client.asGuest(); assertThat(request.user()) .isEqualTo(Client.DEFAULT_GUEST_ID); } @Nested @DisplayName("manage subscriptions") class Subscriptions { private List<Subscription> subscriptions; @BeforeEach void createSubscriptions() { UserId currentUser = GivenUserId.generated(); String userField = "user"; Subscription userLoggedIn = client.onBehalfOf(currentUser) .subscribeToEvent(UserLoggedIn.class) .where(eq(userField, currentUser)) .observe((e) -> {}) .post(); Subscription userLoggedOut = client.onBehalfOf(currentUser) .subscribeToEvent(UserLoggedOut.class) .where(eq(userField, currentUser)) .observe((e) -> {}) .post(); Subscription userProfile = client.onBehalfOf(currentUser) .subscribeTo(UserAccount.class) .where(eq(userField, currentUser)) .post(); subscriptions.add(userLoggedIn); subscriptions.add(userLoggedOut); subscriptions.add(userProfile); } @Test @DisplayName("remembering them until cancelled") void remembering() { ActiveSubscriptions remembered = client.subscriptions(); subscriptions.forEach( (s) -> assertTrue(remembered.contains(s)) ); subscriptions.forEach( (s) -> { client.cancel(s); assertFalse(remembered.contains(s)); } ); } } }
package org.teiid.translator; import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.ConnectionFactory; import org.teiid.connector.DataPlugin; import org.teiid.core.TeiidException; import org.teiid.core.util.PropertiesUtils; import org.teiid.core.util.ReflectionHelper; import org.teiid.language.*; import org.teiid.logging.LogConstants; import org.teiid.logging.LogManager; import org.teiid.metadata.FunctionMethod; import org.teiid.metadata.FunctionParameter; import org.teiid.metadata.MetadataFactory; import org.teiid.metadata.RuntimeMetadata; import org.teiid.translator.CacheDirective.Scope; import org.teiid.translator.TypeFacility.RUNTIME_CODES; import org.teiid.translator.TypeFacility.RUNTIME_NAMES; /** * <p>The primary entry point for a Translator. This class should be extended by the custom translator writer.</p> * * The deployer instantiates this class through reflection. So it is important to have no-arg constructor. Once constructed * the "start" method is called. This class represents the basic capabilities of the translator. */ public class ExecutionFactory<F, C> { public enum SupportedJoinCriteria { /** * Indicates that any supported criteria is allowed. */ ANY, /** * Indicates that any simple comparison of elements is allowed. */ THETA, /** * Indicates that only equality predicates of elements are allowed. */ EQUI, /** * Indicates that only equality predicates between * exactly one primary and foreign key is allowed per join. */ KEY } public enum NullOrder { HIGH, LOW, FIRST, LAST, UNKNOWN } public static final int DEFAULT_MAX_FROM_GROUPS = -1; public static final int DEFAULT_MAX_IN_CRITERIA_SIZE = -1; private static final TypeFacility TYPE_FACILITY = new TypeFacility(); /* * Managed execution properties */ private boolean immutable; private boolean sourceRequired = true; private Boolean sourceRequiredForMetadata; private boolean threadBound; /* * Support properties */ private boolean supportsSelectDistinct; private boolean supportsOuterJoins; private SupportedJoinCriteria supportedJoinCriteria = SupportedJoinCriteria.ANY; private boolean supportsOrderBy; private boolean supportsInnerJoins; private boolean supportsFullOuterJoins; private boolean requiresCriteria; private int maxInSize = DEFAULT_MAX_IN_CRITERIA_SIZE; private int maxDependentInPredicates = DEFAULT_MAX_IN_CRITERIA_SIZE; private boolean copyLobs; private boolean supportsNativeQueries; private LinkedList<FunctionMethod> pushdownFunctionMethods = new LinkedList<FunctionMethod>(); private String nativeProcedureName = "native"; //$NON-NLS-1$ /** * Initialize the connector with supplied configuration */ @SuppressWarnings("unused") public void start() throws TranslatorException { } /** * Defines if the Connector is read-only connector * @return */ @TranslatorProperty(display="Is Immutable",description="Is Immutable, True if the source never changes.",advanced=true) public boolean isImmutable() { return immutable; } public void setImmutable(boolean arg0) { this.immutable = arg0; } @TranslatorProperty(display="Copy LOBs",description="If true, returned LOBs will be copied, rather than streamed from the source",advanced=true) public boolean isCopyLobs() { return copyLobs; } public void setCopyLobs(boolean copyLobs) { this.copyLobs = copyLobs; } /** * Return a connection object from the given connection factory. * * The default implementation assumes a JCA {@link ConnectionFactory}. Subclasses should override, if they use * another type of connection factory. * * @deprecated * @see #getConnection(Object, ExecutionContext) * @param factory * @return a connection * @throws TranslatorException */ @Deprecated @SuppressWarnings("unchecked") public C getConnection(F factory) throws TranslatorException { if (factory == null) { return null; } if (factory instanceof ConnectionFactory) { try { return (C) ((ConnectionFactory)factory).getConnection(); } catch (ResourceException e) { throw new TranslatorException(DataPlugin.Event.TEIID60000, e); } } throw new AssertionError(factory.getClass().getName() + " is was not a ConnectionFactory implementation"); //$NON-NLS-1$ } /** * Return a connection object from the given connection factory. * * The default implementation assumes a JCA {@link ConnectionFactory}. Subclasses should override, if they use * another type of connection factory or wish to use the {@link ExecutionContext}. By default calls {@link #getConnection(Object)} * * @param factory * @param executionContext null if this is a system request for a connection * @return a connection * @throws TranslatorException */ public C getConnection(F factory, ExecutionContext executionContext) throws TranslatorException { return getConnection(factory); } /** * Closes a connection object from the given connection factory. * * The default implementation assumes a JCA {@link Connection}. Subclasses should override, if they use * another type of connection. * * @param connection * @param factory */ public void closeConnection(C connection, F factory) { if (connection == null) { return; } if (connection instanceof Connection) { try { ((Connection)connection).close(); } catch (ResourceException e) { LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Error closing"); //$NON-NLS-1$ } return; } throw new AssertionError("A connection was created, but no implementation provided for closeConnection"); //$NON-NLS-1$ } /** * Flag that indicates if a underlying source connection required for this execution factory to work * @return */ public boolean isSourceRequired() { return sourceRequired; } public void setSourceRequired(boolean value) { this.sourceRequired = value; } /** * Flag that indicates if a underlying source connection required for this execution factory to return metadata * @return true if required */ public boolean isSourceRequiredForMetadata() { if (sourceRequiredForMetadata == null) { //matches pre 8.1 behavior return sourceRequired; } //TODO we could also consider making this an annotation of the getMetadata call return sourceRequiredForMetadata; } /** * If true, the {@link #initCapabilities(Object)} method will be consulted prior * to deteremining the capabilites * @return */ public boolean isSourceRequiredForCapabilities() { return false; } /** * Invoked if {@link #isSourceRequiredForCapabilities()} returns true * @param connection * @throws TranslatorException */ public void initCapabilities(C connection) throws TranslatorException { } public void setSourceRequiredForMetadata(boolean sourceRequiredForMetadata) { this.sourceRequiredForMetadata = sourceRequiredForMetadata; } /** * Obtain a reference to the default LanguageFactory that can be used to construct * new language interface objects. This is typically needed when modifying the language * objects passed to the connector or for testing when objects need to be created. */ public LanguageFactory getLanguageFactory() { return LanguageFactory.INSTANCE; } /** * Obtain a reference to the type facility, which can be used to perform many type * conversions supplied by the Connector API. */ public TypeFacility getTypeFacility() { return TYPE_FACILITY; } /** * Create an execution object for the specified command * @param command the command * @param executionContext Provides information about the context that this command is * executing within, such as the identifiers for the command being executed * @param metadata Access to runtime metadata if needed to translate the command * @param connection connection factory object to the data source * @return An execution object that can use to execute the command */ public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException { if (command instanceof Call) { Call obj = (Call)command; //TODO: our extension property support in designer makes ad-hoc properties impossible, so //we just match based upon name. it would be better to have the metadatarepository/tooling add a teiid property //to explicitly set this proc as direct. //the other approach would be to addd a native system stored procedure, but that would require //special security semantics, whereas this proc can be secured on a schema basis if (supportsDirectQueryProcedure() && obj.getMetadataObject().getName().equals(getDirectQueryProcedureName())) { List<Argument> arguments = obj.getArguments(); return createDirectExecution(arguments, command, executionContext, metadata, connection); } } if (command instanceof QueryExpression) { return createResultSetExecution((QueryExpression)command, executionContext, metadata, connection); } if (command instanceof Call) { return createProcedureExecution((Call)command, executionContext, metadata, connection); } return createUpdateExecution(command, executionContext, metadata, connection); } @SuppressWarnings("unused") public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException { throw new TranslatorException(DataPlugin.Event.TEIID60001, DataPlugin.Util.gs(DataPlugin.Event.TEIID60001, "createResultSetExecution")); //$NON-NLS-1$ } @SuppressWarnings("unused") public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException { throw new TranslatorException(DataPlugin.Event.TEIID60001, DataPlugin.Util.gs(DataPlugin.Event.TEIID60001, "createProcedureExecution")); //$NON-NLS-1$ } @SuppressWarnings("unused") public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException { throw new TranslatorException(DataPlugin.Event.TEIID60001, DataPlugin.Util.gs(DataPlugin.Event.TEIID60001, "createUpdateExecution")); //$NON-NLS-1$ } @SuppressWarnings("unused") public ProcedureExecution createDirectExecution(List<Argument> arguments, Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException { throw new TranslatorException(DataPlugin.Event.TEIID60001, DataPlugin.Util.gs(DataPlugin.Event.TEIID60001, "createDirectExecution")); //$NON-NLS-1$ } /** * Get Metadata Processor for the translator to read the metadata * @return */ public MetadataProcessor<C> getMetadataProcessor() { return null; } /** * Support indicates connector can accept queries with SELECT DISTINCT * @since 3.1 SP2 */ @TranslatorProperty(display="Supports Select Distinct", description="True, if this connector supports SELECT DISTINCT", advanced=true) public boolean supportsSelectDistinct() { return supportsSelectDistinct; } public void setSupportsSelectDistinct(boolean supportsSelectDistinct) { this.supportsSelectDistinct = supportsSelectDistinct; } /** * Support indicates connector can accept expressions other than element * symbols in the SELECT clause. Specific supports for the expression * type are still checked. * @since 6.1.0 */ public boolean supportsSelectExpression() { return false; } /** * Support indicates connector can accept groups with aliases * @since 3.1 SP2 */ public boolean supportsAliasedTable() { return false; } /** * Get the supported join criteria. A null return value will be treated * as {@link SupportedJoinCriteria#ANY} * @since 6.1.0 */ @TranslatorProperty(display="Supported Join Criteria", description="Returns one of any, theta, equi, or key", advanced=true) public SupportedJoinCriteria getSupportedJoinCriteria() { return supportedJoinCriteria; } public void setSupportedJoinCriteria( SupportedJoinCriteria supportedJoinCriteria) { this.supportedJoinCriteria = supportedJoinCriteria; } /** * Support indicates connector can accept inner or cross joins * @since 6.1.0 */ @TranslatorProperty(display="Supports Inner Joins", description="True, if this connector supports inner joins", advanced=true) public boolean supportsInnerJoins() { return supportsInnerJoins; } public void setSupportsInnerJoins(boolean supportsInnerJoins) { this.supportsInnerJoins = supportsInnerJoins; } /** * Support indicates connector can accept self-joins where a * group is joined to itself with aliases. Connector must also support * {@link #supportsAliasedTable()}. * @since 3.1 SP2 */ public boolean supportsSelfJoins() { return false; } /** * Support indicates connector can accept left outer joins * @since 3.1 SP2 */ @TranslatorProperty(display="Supports Outer Joins", description="True, if this connector supports outer joins", advanced=true) public boolean supportsOuterJoins() { return supportsOuterJoins; } public void setSupportsOuterJoins(boolean supportsOuterJoins) { this.supportsOuterJoins = supportsOuterJoins; } /** * Support indicates connector can accept full outer joins * @since 3.1 SP2 */ @TranslatorProperty(display="Supports Full Outer Joins", description="True, if this connector supports full outer joins", advanced=true) public boolean supportsFullOuterJoins() { return supportsFullOuterJoins; } public void setSupportsFullOuterJoins(boolean supportsFullOuterJoins) { this.supportsFullOuterJoins = supportsFullOuterJoins; } /** * Support indicates connector can accept inline views (subqueries * in the FROM clause). * @since 4.1 */ public boolean supportsInlineViews() { return false; } /** * Support indicates connector accepts criteria of form (element = constant) * @since 3.1 SP2 */ public boolean supportsCompareCriteriaEquals() { return false; } /** * Support indicates connector accepts criteria of form (element &lt;=|&gt;= constant) * <br>The query engine will may pushdown queries containing &lt; or &gt; if NOT is also * supported. * @since 3.1 SP2 */ public boolean supportsCompareCriteriaOrdered() { return false; } /** * Support indicates connector accepts criteria of form (element LIKE constant) * @since 3.1 SP2 */ public boolean supportsLikeCriteria() { return false; } /** * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char) * @since 3.1 SP2 */ public boolean supportsLikeCriteriaEscapeCharacter() { return false; } /** * Support indicates connector accepts criteria of form (element IN set) * @since 3.1 SP2 */ public boolean supportsInCriteria() { return false; } /** * Support indicates connector accepts IN criteria with a subquery on the right side * @since 4.0 */ public boolean supportsInCriteriaSubquery() { return false; } /** * Support indicates connector accepts criteria of form (element IS NULL) * @since 3.1 SP2 */ public boolean supportsIsNullCriteria() { return false; } /** * Support indicates connector accepts logical criteria connected by OR * @since 3.1 SP2 */ public boolean supportsOrCriteria() { return false; } /** * Support indicates connector accepts logical criteria NOT * @since 3.1 SP2 */ public boolean supportsNotCriteria() { return false; } /** * Support indicates connector accepts the EXISTS criteria * @since 4.0 */ public boolean supportsExistsCriteria() { return false; } /** * Support indicates connector accepts the quantified comparison criteria that * use SOME * @since 4.0 */ public boolean supportsQuantifiedCompareCriteriaSome() { return false; } /** * Support indicates connector accepts the quantified comparison criteria that * use ALL * @since 4.0 */ public boolean supportsQuantifiedCompareCriteriaAll() { return false; } /** * Support indicates connector accepts ORDER BY clause, including multiple elements * and ascending and descending sorts. * @since 3.1 SP2 */ @TranslatorProperty(display="Supports ORDER BY", description="True, if this connector supports ORDER BY", advanced=true) public boolean supportsOrderBy() { return supportsOrderBy; } public void setSupportsOrderBy(boolean supportsOrderBy) { this.supportsOrderBy = supportsOrderBy; } /** * Support indicates connector accepts ORDER BY clause with columns not from the select * @since 6.2 * @return */ public boolean supportsOrderByUnrelated() { return false; } /** * Returns the default null ordering * @since 7.1 * @return the {@link NullOrder} */ public NullOrder getDefaultNullOrder() { return NullOrder.UNKNOWN; } /** * Returns whether the database supports explicit null ordering. * @since 7.1 * @return true if nulls first/last can be specified */ public boolean supportsOrderByNullOrdering() { return false; } /** * Whether the source supports an explicit GROUP BY clause * @since 6.1 */ public boolean supportsGroupBy() { return false; } /** * Whether the source supports grouping only over a single table * @return */ public boolean supportsOnlySingleTableGroupBy() { return false; } /** * Whether the source supports the HAVING clause * @since 6.1 */ public boolean supportsHaving() { return false; } /** * Support indicates connector can accept the SUM aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesSum() { return false; } /** * Support indicates connector can accept the AVG aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesAvg() { return false; } /** * Support indicates connector can accept the MIN aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesMin() { return false; } /** * Support indicates connector can accept the MAX aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesMax() { return false; } /** * Support indicates connector can accept the COUNT aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesCount() { return false; } /** * Support indicates connector can accept the COUNT(*) aggregate function * @since 3.1 SP2 */ public boolean supportsAggregatesCountStar() { return false; } /** * Support indicates connector can accept DISTINCT within aggregate functions * @since 3.1 SP2 */ public boolean supportsAggregatesDistinct() { return false; } /** * Support indicates connector can accept STDDEV_POP, STDDEV_VAR, VAR_POP, VAR_SAMP * @since 7.1 */ public boolean supportsAggregatesEnhancedNumeric() { return false; } /** * @return true if string_agg is supported * @since 8.4 */ public boolean supportsStringAgg() { return false; } /** * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and * HAVING clauses * @since 4.0 */ public boolean supportsScalarSubqueries() { return false; } /** * Support indicates connector can accept correlated subqueries wherever subqueries * are accepted * @since 4.0 */ public boolean supportsCorrelatedSubqueries() { return false; } /** * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END * @since 4.0 */ public boolean supportsSearchedCaseExpressions() { return false; } /** * Support indicates that the connector supports the UNION of two queries. * @since 4.2 */ public boolean supportsUnions() { return false; } /** * Support indicates that the connector supports an ORDER BY on a SetQuery. * @since 5.6 */ public boolean supportsSetQueryOrderBy() { return false; } /** * Support indicates that the connector supports the INTERSECT of two queries. * @since 5.6 */ public boolean supportsIntersect() { return false; } /** * Support indicates that the connector supports the EXCEPT of two queries. * @since 5.6 */ public boolean supportsExcept() { return false; } /** * Get list of all supported function names. Arithmetic functions have names like * &quot;+&quot;. * @see SourceSystemFunctions for a listing of system pushdown functions. Note that * not all system functions are listed as some functions will use a common name * such as CONCAT vs. the || operator, and other functions will be rewritten and * not pushed down, such as SPACE. * <br><b>Note:</b> User defined functions should be specified fully qualified. * @since 3.1 SP3 */ public List<String> getSupportedFunctions() { return null; } /** * Get a list of {@link FunctionMethod}s that will be contributed to the SYS schema. * To avoid conflicts with system functions, the function name should contain a * qualifier - typically &lt;translator name&gt;.&lt;function name&gt; * @see ExecutionFactory#addPushDownFunction(String, String, FunctionParameter, FunctionParameter...) * @return */ public List<FunctionMethod> getPushDownFunctions(){ return pushdownFunctionMethods; } /** * Adds a pushdown function. * @param qualifier will be pre-pended to the name * @param name * @param returnType see {@link RUNTIME_NAMES} for type names * @param paramTypes see {@link RUNTIME_NAMES} for type names * @return the FunctionMethod created. */ protected FunctionMethod addPushDownFunction(String qualifier, String name, String returnType, String...paramTypes) { FunctionMethod method = FunctionMethod.createFunctionMethod(qualifier + '.' + name, name, qualifier, returnType, paramTypes); method.setNameInSource(name); pushdownFunctionMethods.add(method); return method; } /** * Get the integer value representing the number of values allowed in an IN criteria * in the WHERE clause of a query * @since 5.0 */ @TranslatorProperty(display="Max number of IN predicate entries", advanced=true) public int getMaxInCriteriaSize() { return maxInSize; } public void setMaxInCriteriaSize(int maxInSize) { this.maxInSize = maxInSize; } /** * Get the integer value representing the max number of dependent IN predicates. * This may be used to split a single dependent value via OR, or multiple dependent values * via AND. */ @TranslatorProperty(display="Max number of dependent IN predicates", advanced=true) public int getMaxDependentInPredicates() { return maxDependentInPredicates; } public void setMaxDependentInPredicates(int maxDependentInPredicates) { this.maxDependentInPredicates = maxDependentInPredicates; } /** * <p>Support indicates that the connector supports non-column expressions in GROUP BY, such as: * <code>SELECT dayofmonth(theDate), COUNT(*) FROM table GROUP BY dayofmonth(theDate)</code></p> * @since 5.0 */ public boolean supportsFunctionsInGroupBy() { return false; } /** * Gets whether the connector can limit the number of rows returned by a query. * @since 5.0 SP1 */ public boolean supportsRowLimit() { return false; } /** * Gets whether the connector supports a SQL clause (similar to the LIMIT with an offset) that can return * result sets that start in the middle of the resulting rows returned by a query * @since 5.0 SP1 */ public boolean supportsRowOffset() { return false; } /** * The number of groups supported in the from clause. Added for a Sybase limitation. * @since 5.6 * @return the number of groups supported in the from clause, or -1 if there is no limit */ public int getMaxFromGroups() { return DEFAULT_MAX_FROM_GROUPS; } /** * Whether the source prefers to use ANSI style joins. * @since 6.0 */ public boolean useAnsiJoin() { return false; } /** * Whether the source supports queries without criteria. * @since 6.0 */ @TranslatorProperty(display="Requries Criteria", description="True, if this connector requires criteria on source queries", advanced=true) public boolean requiresCriteria() { return requiresCriteria; } public void setRequiresCriteria(boolean requiresCriteria) { this.requiresCriteria = requiresCriteria; } /** * Whether the source supports {@link BatchedUpdates} * @since 6.0 */ public boolean supportsBatchedUpdates() { return false; } /** * Whether the source supports updates with multiple value sets * @since 6.0 */ public boolean supportsBulkUpdate() { return false; } /** * Support indicates that the connector can accept INSERTs with * values specified by a {@link SetQuery} or {@link Select} * @since 6.1 */ public boolean supportsInsertWithQueryExpression() { return false; } public static <T> T getInstance(Class<T> expectedType, String className, Collection<?> ctorObjs, Class<? extends T> defaultClass) throws TranslatorException { try { if (className == null) { if (defaultClass == null) { throw new TranslatorException(DataPlugin.Event.TEIID60004, DataPlugin.Util.gs(DataPlugin.Event.TEIID60004)); } return expectedType.cast(defaultClass.newInstance()); } return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader())); } catch (TeiidException e) { throw new TranslatorException(DataPlugin.Event.TEIID60005, e); } catch (IllegalAccessException e) { throw new TranslatorException(DataPlugin.Event.TEIID60005, e); } catch(InstantiationException e) { throw new TranslatorException(DataPlugin.Event.TEIID60005, e); } } /** * Implement to provide metadata to the metadata for use by the engine. This is the * primary method of creating metadata for dynamic VDBs. * @param metadataFactory * @param conn may be null if the source is not required * @throws TranslatorException to indicate a recoverable error, otherwise a RuntimeException * @see #isSourceRequiredForMetadata() */ public void getMetadata(MetadataFactory metadataFactory, C conn) throws TranslatorException { MetadataProcessor mp = getMetadataProcessor(); if (mp != null) { PropertiesUtils.setBeanProperties(mp, metadataFactory.getModelProperties(), "importer"); //$NON-NLS-1$ mp.process(metadataFactory, conn); } } /** * Indicates if LOBs are usable after the execution is closed. * @return true if LOBs can be used after close * @since 7.2 */ public boolean areLobsUsableAfterClose() { return false; } /** * @return true if the WITH clause is supported * @since 7.2 */ public boolean supportsCommonTableExpressions() { return false; } /** * @return true if Advanced OLAP operations are supported * including the aggregate function filter clause. * @since 7.5 */ public boolean supportsAdvancedOlapOperations() { return false; } /** * @return true if Elementary OLAP operations are supported * including window functions and inline window specifications that include * simple expressions in partitioning and ordering * @since 7.5 */ public boolean supportsElementaryOlapOperations() { return false; } /** * @return true if all aggregates can have window function order by clauses. * @since 7.5 */ public boolean supportsWindowOrderByWithAggregates() { return supportsElementaryOlapOperations(); } /** * @return true if distinct aggregates can be windowed function. * @since 7.6 */ public boolean supportsWindowDistinctAggregates() { return supportsElementaryOlapOperations(); } /** * @return true if array_agg is supported * @since 7.5 */ public boolean supportsArrayAgg() { return false; } /** * @return true if the SIMILAR TO predicate is supported * @since 7.5 */ public boolean supportsSimilarTo() { return false; } /** * @return true if the LIKE_REGEX predicate is supported * @since 7.4 */ public boolean supportsLikeRegex() { return false; } /** * Used for fine grained control of convert/cast pushdown. The {@link #getSupportedFunctions()} should * contain {@link SourceSystemFunctions#CONVERT}. This method can then return false to indicate * a lack of specific support. The engine will does not care about an unnecessary conversion * where fromType == toType. * * By default lob conversion is disabled. * * @param fromType @see RUNTIME_CODES * @param toType @see RUNTIME_CODES * @return true if the given conversion is supported. * @since 8.0 */ public boolean supportsConvert(int fromType, int toType) { if (fromType == RUNTIME_CODES.OBJECT || fromType == RUNTIME_CODES.CLOB || fromType == RUNTIME_CODES.XML || fromType == RUNTIME_CODES.BLOB || toType == RUNTIME_CODES.CLOB || toType == RUNTIME_CODES.XML || toType == RUNTIME_CODES.BLOB) { return false; } return true; } /** * @return true if only Literal comparisons (equality, ordered, like, etc.) are supported for non-join conditions. * @since 8.0 */ public boolean supportsOnlyLiteralComparison() { return false; } /** * NOTE: The pushed independent tuples will not have been * converted to a unique set and may contain duplicates. * @return true if dependent join key pushdown is supported * @since 8.0 */ public boolean supportsDependentJoins() { return false; } /** * @return true if full dependent join pushdown is supported * @since 8.5 * @return */ public boolean supportsFullDependentJoins() { return false; } public enum Format { NUMBER, DATE } /** * See also {@link #supportsFormatLiteral(String, Format)} * @return true if only literal formats are supports. */ public boolean supportsOnlyFormatLiterals() { return false; } /** * * @param literal * @param format * @return true if the given Java format string is supported */ public boolean supportsFormatLiteral(String literal, Format format) { return false; } /** * Refines subquery support. * @return true if subqueries are supported in the on clause. */ public boolean supportsSubqueryInOn() { return true; } /** * Get the {@link CacheDirective} to control command caching. * <p>Use {@link Scope#NONE} to indicate to the engine that no caching should be performed by the engine.</p> * <p>If cache parameters on the {@link CacheDirective} will be changed by the {@link Execution}, then * a new instance of a {@link CacheDirective} should be set each time.</p> * @param command * @param executionContext * @param metadata * @throws TranslatorException */ public CacheDirective getCacheDirective(Command command, ExecutionContext executionContext, RuntimeMetadata metadata) throws TranslatorException { return null; } /** * When forkable the engine may use a separate thread to interact with returned {@link Execution}. * @return true if {@link Execution}s can be called in separate threads from the processing thread */ public boolean isForkable() { return true; } /** * @return True, if this translator's executions must complete in a single thread. */ @TranslatorProperty(display="Thread Bound", description="True, if this translator's executions must complete in a single thread.", advanced=true) public boolean isThreadBound() { return threadBound; } /** * The engine currently uses array types for dependent joins. * @return true if an array type is supported. */ public boolean supportsArrayType() { return false; } /** * True, if this translator supports execution of source specific commands unaltered through a direct procedure. * @deprecated * @see #supportsDirectQueryProcedure() * @return */ @Deprecated @TranslatorProperty(display="Deprecated Property:Supports Direct Query Procedure", description="Deprecated Property, Use Supports Direct Query Procedure instead", advanced=true) final public boolean supportsNativeQueries() { return this.supportsNativeQueries; } /** * @deprecated * @see #setSupportsDirectQueryProcedure(boolean) */ @Deprecated final public void setSupportsNativeQueries(boolean state) { this.supportsNativeQueries = state; } /** * True, if this translator supports execution of source specific commands unaltered through a direct procedure. * @return */ @TranslatorProperty(display="Supports Direct Query Procedure", description="True, if this translator supports execution of source specific commands unaltered through a direct procedure", advanced=true) public boolean supportsDirectQueryProcedure() { return this.supportsNativeQueries; } public void setSupportsDirectQueryProcedure(boolean state) { this.supportsNativeQueries = state; } /** * Defines the name of the direct processing procedure. This metadata or signature * of the procedure is defined automatically. * @deprecated * @see #getDirectQueryProcedureName() * @return */ @Deprecated @TranslatorProperty(display="Deprecated Property:Direct Query Procedure Name", description="Deprecated Property, use Direct Query Procedure Name", advanced=true) final public String getNativeQueryProcedureName() { return this.nativeProcedureName; } /** * @deprecated * @see #setDirectQueryProcedureName(String) */ @Deprecated final public void setNativeQueryProcedureName(String name) { this.nativeProcedureName = name; } /** * Defines the name of the direct processing procedure. This metadata or signature * of the procedure is defined automatically. * @return */ @TranslatorProperty(display="Direct Query Procedure Name", description="The name of the direct query procedure", advanced=true) public String getDirectQueryProcedureName() { return this.nativeProcedureName; } public void setDirectQueryProcedureName(String name) { this.nativeProcedureName = name; } /** * @return true if only correlated subqueries are supported. */ public boolean supportsOnlyCorrelatedSubqueries() { return false; } /** * @return true if the translator support SELECT without a FROM clause */ public boolean supportsSelectWithoutFrom() { return false; } /** * @return true if the translator support GROUP BY ROLLUP */ public boolean supportsGroupByRollup() { return false; } /** * @return true if order by is supported over a grouping with a rollup, cube, etc. */ public boolean supportsOrderByWithExtendedGrouping() { return supportsOrderBy(); } public void setThreadBound(boolean threadBound) { this.threadBound = threadBound; } }
package org.jtrim.collections; import java.util.*; /** * Defines a list whose elements can be referenced independently. These * {@link RefList.ElementRef element references} remain valid even * after the list was modified. * <P> * The references can be used for various purposes, like inserting a new element * after or before a given element, incrementing or decrementing the position * of the element is the list. * <P> * Unlike general {@link List} implementations, implementations of this * interface in general are not allowed to have more than * {@link Integer#MAX_VALUE} elements. Some implementations may ignore this * restriction but there is no general rule how methods should work when * the size of such lists exceed {@code Integer#MAX_VALUE}. * * <h3>Thread safety</h3> * Implementations of this interface are not required to be thread-safe and * in general cannot be modified concurrently by multiple concurrent threads. * However reading by multiple concurrent threads are allowed. Note that * accessing the element references of a {@code RefList} is equivalent to * accessing the collection itself regarding thread safety. * * <h4>Synchronization transparency</h4> * The methods of this interface are required to be * <I>synchronization transparent</I>, so they can be called in any context * (e.g.: while holding a lock). * * @param <E> the type of the elements in this list * * @see RefLinkedList * @author Kelemen Attila */ public interface RefList<E> extends List<E>, RefCollection<E> { /** * Defines a reference to an element of a {@code RefList}. The * reference remains valid no matter how the underlying list was * modified. * * <h3>Thread safety</h3> * Instances of this class derive their thread-safety properties from the * underlying collection. * * @param <E> the type of the referenced element */ public static interface ElementRef<E> extends RefCollection.ElementRef<E> { public int getIndex(); public ListIterator<E> getIterator(); /** * Returns the next {@code step}th element of the underlying list. That * is, this method returns the element with an {@link #getIndex() index} * larger by {@code step} than the index of this element. * <P> * This method is allowed to be called with a negative {@code step} * argument, this is effectively calling * {@link #getPrevious(int) getPrevious(Math.abs(step))} except when * {@code step == Integer.MIN_VALUE} where it is the element one step * before {@code getPrevious(Integer.MAX_VALUE)}. * <P> * Notice that {@code getNext(0)} always returns this reference. * <P> * This method can be called after this referenced element was removed * from the underlying list. In this case this method is defined to * return {@code null}. * <P> * <B>Note to implementors</B>: Don't forget that * {@code Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE}. * * @param step the number of elements to skip forward (including this * reference). This argument can be any integer and negative values * are effectively stepping backward with the absolute {@code step} * value. * @return the next element of the underlying list after skipping * {@code step} number of elements (including this reference) or * {@code null} if no such element exists (either because there is no * such element in the underlying list or this element was already * removed from the list) */ public ElementRef<E> getNext(int step); /** * Returns the previous {@code step}th element of the underlying list. * That is, this method returns the element with an * {@link #getIndex() index} lower by {@code step} than the index of * this element. * <P> * This method is allowed to be called with a negative {@code step} * argument, this is effectively calling * {@link #getNext(int) getNext(Math.abs(step))} except when * {@code step == Integer.MIN_VALUE} where it is the element one step * after {@code getNext(Integer.MAX_VALUE)}. * <P> * Notice that {@code getPrevious(0)} always returns this reference. * <P> * This method can be called after this referenced element was removed * from the underlying list. In this case this method is defined to * return {@code null}. * <P> * <B>Note to implementors</B>: Don't forget that * {@code Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE}. * * @param step the number of elements to skip backward (including this * reference). This argument can be any integer and negative values * are effectively stepping forward with the absolute {@code step} * value. * @return the previous element of the underlying list after skipping * {@code step} number of elements (including this reference) or * {@code null} if no such element exists (either because there is no * such element in the underlying list or this element was already * removed from the list) */ public ElementRef<E> getPrevious(int step); public void moveLast(); public void moveFirst(); public int moveBackward(int count); public int moveForward(int count); public ElementRef<E> addAfter(E newElement); public ElementRef<E> addBefore(E newElement); } /** * Returns the reference to the element equivalent (based on the * {@code equals} method) to the given element with the lowest index. * * @param element the element to be looked for in this list. This argument * can be {@code null} if this collection permits {@code null} elements. * In case this implementation does not permit {@code null} elements but * accept {@code null} for this argument, it must return {@code null} if * {@code null} is passed for this argument. * @return the reference to the element equivalent to the given element * with the lowest index or {@code null} if no such element was found * * @throws NullPointerException implementations may throw this exception * if this collection does not permit {@code null} elements. However even * in this case, an implementation is not required to raise this * exception. */ public ElementRef<E> findFirstReference(E element); /** * Returns the reference to the element equivalent (based on the * {@code equals} method) to the given element with the highest index. * * @param element the element to be looked for in this list. This argument * can be {@code null} if this collection permits {@code null} elements. * In case this implementation does not permit {@code null} elements but * accept {@code null} for this argument, it must return {@code null} if * {@code null} is passed for this argument. * @return the reference to the element equivalent to the given element * with the highest index or {@code null} if no such element was found * * @throws NullPointerException implementations may throw this exception * if this collection does not permit {@code null} elements. However even * in this case, an implementation is not required to raise this * exception. */ public ElementRef<E> findLastReferece(E element); /** * Returns the reference to the first element of this list or {@code null} * if this list is empty. * * @return the reference to the first element of this list or {@code null} * if this list is empty */ public ElementRef<E> getFirstReference(); /** * Returns the reference to the last element of this list or {@code null} * if this list is empty. * * @return the reference to the last element of this list or {@code null} * if this list is empty */ public ElementRef<E> getLastReference(); /** * Returns the reference to the element at the given index. * * @param index the index of the requested element. This argument must * be greater than or equal to zero and lesser than the size of this list. * @return the reference to the element at the given index. This method may * never return {@code null}. * * @throws IndexOutOfBoundsException thrown if the specified index points * to an element outside of this list */ public ElementRef<E> getReference(int index); public ElementRef<E> addFirstGetReference(E element); public ElementRef<E> addLastGetReference(E element); public ElementRef<E> addGetReference(int index, E element); }
package com.github.fmonniot.mailbox; import org.glassfish.jersey.jackson.JacksonFeature; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; public class Scenario { public static final String GREEN = "\033[32m"; public static final String RED = "\033[31m"; public static final String DEFAULT_COLOR = "\033[0m"; private static final String VIOLET = "\033[35m"; private final String title; private final List<Step> steps = new ArrayList<>(); private final WebTarget target; public Scenario(String title, String targetUrl) { this.title = title; Client client = ClientBuilder.newClient().register(JacksonFeature.class); target = client.target(targetUrl); } public static String expectActual(Object expected, Object actual) { return String.format("expected=%s, actual=%s", expected, actual); } public Scenario step(Step step) { steps.add(step); return this; } public void play() { System.out.println("Begin Scenario: " + title); if (steps.size() < 1) { System.out.println(VIOLET + "No step defined in this scenario" + DEFAULT_COLOR); return; } for (Step step : steps) { System.out.println("\tStep " + (steps.indexOf(step) + 1) + ":\t" + step.description()); Response response = step.action(target); Result result = step.verify(response); System.out.println("\t" + (result.isOk() ? GREEN : RED) + result.getReason() + DEFAULT_COLOR); } } public static abstract class Step { abstract String description(); abstract Response action(WebTarget target); abstract Result verify(Response response); } public static class Result { private final String reasonNok; private boolean ok; private String reasonOk; public Result(boolean ok, String reasonOk, String reasonNok) { this.ok = ok; this.reasonOk = reasonOk; this.reasonNok = reasonNok; } public boolean isOk() { return ok; } public String getReason() { return ok ? reasonOk : reasonNok; } } }
package com.creactiviti.piper.core; import java.io.File; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.creactiviti.piper.core.messagebroker.Queues; import com.creactiviti.piper.core.messagebroker.SyncMessageBroker; import com.creactiviti.piper.core.task.SimpleTaskExecution; import com.creactiviti.piper.core.task.TaskExecution; import com.creactiviti.piper.core.uuid.UUIDGenerator; public class WorkerTests { @Test public void test1 () { Worker worker = new Worker(); SyncMessageBroker messageBroker = new SyncMessageBroker(); messageBroker.receive(Queues.COMPLETIONS, (t)-> Assertions.assertTrue(((TaskExecution)t).getOutput().equals("done")) ); messageBroker.receive(Queues.EVENTS, (t)-> {} ); worker.setMessageBroker(messageBroker); worker.setEventPublisher((e)->{}); worker.setTaskHandlerResolver((jt) -> (t) -> "done"); SimpleTaskExecution task = new SimpleTaskExecution(); task.setId("1234"); task.setJobId("4567"); worker.handle(task); } @Test public void test2 () { Worker worker = new Worker(); SyncMessageBroker messageBroker = new SyncMessageBroker(); messageBroker.receive(Queues.ERRORS, (t)-> Assertions.assertTrue( ((TaskExecution)t).getError().getMessage().equals("bad input") ) ); messageBroker.receive(Queues.EVENTS, (t)-> {} ); worker.setMessageBroker(messageBroker); worker.setEventPublisher((e)->{}); worker.setTaskHandlerResolver((jt) -> (t) -> { throw new IllegalArgumentException("bad input"); }); SimpleTaskExecution task = new SimpleTaskExecution(); task.setId("1234"); task.setJobId("4567"); worker.handle(task); } @Test public void test3 () { Worker worker = new Worker(); SyncMessageBroker messageBroker = new SyncMessageBroker(); messageBroker.receive(Queues.COMPLETIONS, (t)-> Assertions.assertEquals("done",(((TaskExecution)t).getOutput()))); messageBroker.receive(Queues.EVENTS, (t)-> {} ); worker.setMessageBroker(messageBroker); worker.setEventPublisher((e)->{}); worker.setTaskHandlerResolver((t1) -> { String type = t1.getType(); if("var".equals(type)) { return (t2)->t2.getRequired("value"); } else { throw new IllegalArgumentException("unknown type: " + type); } }); SimpleTaskExecution task = new SimpleTaskExecution(); task.setId("1234"); task.setJobId("4567"); task.set(DSL.TYPE, "var"); task.set("value", "${myVar}"); task.set("pre", List.of(Map.of("name","myVar","type","var","value","done"))); worker.handle(task); } @Test public void test4 () { String tempDir = new File (new File(System.getProperty("java.io.tmpdir")),UUIDGenerator.generate()).getAbsolutePath(); Worker worker = new Worker(); SyncMessageBroker messageBroker = new SyncMessageBroker(); messageBroker.receive(Queues.COMPLETIONS, (t)-> { Assertions.assertFalse(new File(tempDir).exists()); }); messageBroker.receive(Queues.EVENTS, (t)-> {} ); worker.setMessageBroker(messageBroker); worker.setEventPublisher((e)->{}); worker.setTaskHandlerResolver((t1) -> { String type = t1.getType(); if("var".equals(type)) { return (t2)->t2.getRequired("value"); } else if("mkdir".equals(type)) { return (t2)->(new File (t2.getString("path")).mkdirs()); } else if("rm".equals(type)) { return (t2)-> FileUtils.deleteQuietly((new File (t2.getString("path")))); } else if("pass".equals(type)) { Assertions.assertTrue(new File(tempDir).exists()); return (t2)->null; } else { throw new IllegalArgumentException("unknown type: " + type); } }); SimpleTaskExecution task = new SimpleTaskExecution(); task.setId("1234"); task.setJobId("4567"); task.set("type", "pass"); task.set("pre", List.of( Map.of("type","mkdir","path",tempDir) )); task.set("post", List.of( Map.of("type","rm","path",tempDir) )); worker.handle(task); } @Test public void test5 () { String tempDir = new File (new File(System.getProperty("java.io.tmpdir")),UUIDGenerator.generate()).getAbsolutePath(); Worker worker = new Worker(); SyncMessageBroker messageBroker = new SyncMessageBroker(); messageBroker.receive(Queues.ERRORS, (t)-> { Assertions.assertFalse(new File(tempDir).exists()); }); messageBroker.receive(Queues.EVENTS, (t)-> {} ); worker.setMessageBroker(messageBroker); worker.setEventPublisher((e)->{}); worker.setTaskHandlerResolver((t1) -> { String type = t1.getType(); if("var".equals(type)) { return (t2)->t2.getRequired("value"); } else if("mkdir".equals(type)) { return (t2)->(new File (t2.getString("path")).mkdirs()); } else if("rm".equals(type)) { return (t2)-> FileUtils.deleteQuietly((new File (t2.getString("path")))); } else if("rogue".equals(type)) { Assertions.assertTrue(new File(tempDir).exists()); return (t2)->{throw new RuntimeException("rogue");}; } else { throw new IllegalArgumentException("unknown type: " + type); } }); SimpleTaskExecution task = new SimpleTaskExecution(); task.setId("1234"); task.setJobId("4567"); task.set("type", "rogue"); task.set("pre", List.of( Map.of("type","mkdir","path",tempDir) )); task.set("finalize", List.of( Map.of("type","rm","path",tempDir) )); worker.handle(task); } }
/* * $Log: IXAEnabled.java,v $ * Revision 1.2 2004-03-23 17:20:11 L190409 * one little puntkomma * * Revision 1.1 2004/03/23 16:52:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.core; /** * Indicates a Pipe, Sender or Listener to be capable of supporting XA-transactions. * When isTransacted() returns true, alternative XA enabled versions of resources like * connectionfactories should be used by implementing classes. * <p>$Id: IXAEnabled.java,v 1.2 2004-03-23 17:20:11 L190409 Exp $</p> * @author Gerrit van Brakel * @since 4.1 */ public interface IXAEnabled { public static final String version="$Id: IXAEnabled.java,v 1.2 2004-03-23 17:20:11 L190409 Exp $"; /** * indicates implementing object is under transaction control, using XA-transactions */ public boolean isTransacted(); }
package org.jetel.graph; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.apache.commons.io.filefilter.AbstractFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.graph.runtime.EngineInitializer; import org.jetel.graph.runtime.GraphRuntimeContext; import org.jetel.main.runGraph; import org.jetel.test.CloverTestCase; import org.jetel.util.file.FileUtils; import org.jetel.util.string.StringUtils; import junit.framework.Test; import junit.framework.TestSuite; public class ResetTest extends CloverTestCase { private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/"; private final static String[] EXAMPLE_PATH = { "../cloveretl.examples/SimpleExamples/", "../cloveretl.examples/AdvancedExamples/", "../cloveretl.examples/CTL2FunctionsTutorial/", "../cloveretl.examples/DataProfiling/", "../cloveretl.examples/DataSampling/", "../cloveretl.examples/ExtExamples/", "../cloveretl.examples.community/RealWorldExamples/", "../cloveretl.examples.community/WebSiteExamples/", "../cloveretl.examples/BasicExamples/", "../cloveretl.test.scenarios/", "../cloveretl.examples.commercial/CommercialExamples/", "../cloveretl.examples.commercial/DataQualityExamples/" //"../cloveretl.examples/CompanyTransactionsTutorial/" // runs too long }; private final static String[] NEEDS_SCENARIOS_CONNECTION = { "graphRevenues.grf", "graphDBExecuteMsSql.grf", "graphDBExecuteMySql.grf", "graphDBExecuteOracle.grf", "graphDBExecutePostgre.grf", "graphDBExecuteSybase.grf", "graphInfobrightDataWriterRemote.grf", "graphLdapReaderWriter.grf" }; private final static String[] NEEDS_SCENARIOS_LIB = { "graphDBExecuteOracle.grf", "graphDBExecuteSybase.grf", "graphLdapReaderWriter.grf" }; private final static Map<String, List<String>> CLASSPATHS = new HashMap<String, List<String>>(); static { CLASSPATHS.put("rpc-literal-service-test.grf", Collections.singletonList("lib/rpc-literal-test.jar")); CLASSPATHS.put("3rdPartyCode_CLO-8964.grf", Collections.singletonList("lib/Classloading_CLO-9137.jar")); } private final static String GRAPHS_DIR = "graph"; private final static String TRANS_DIR = "trans"; private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"}; private final String basePath; private final File graphFile; private final boolean batchMode; private boolean cleanUp = true; private static Log logger = LogFactory.getLog(ResetTest.class); public static Test suite() { final TestSuite suite = new TestSuite(); for (int i = 0; i < EXAMPLE_PATH.length; i++) { logger.info("Testing graphs in " + EXAMPLE_PATH[i]); final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR); if(!graphsDir.exists()){ throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found"); } IOFileFilter fileFilter = new AbstractFileFilter() { @Override public boolean accept(File file) { return file.getName().endsWith(".grf") && !file.getName().startsWith("TPCH")// ok, performance tests - last very long && !file.getName().startsWith("Subgraph") // need server && !file.getName().startsWith("clusterDictionary") // cluster tests && !file.getName().contains("Performance")// ok, performance tests - last very long && !file.getName().equals("graphJoinData.grf") // ok, uses class file that is not created && !file.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created && !file.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created && !file.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created && !file.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created && !file.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created && !file.getName().equals("conversionNum2num.grf") // ok, should fail && !file.getName().equals("outPortWriting.grf") // ok, should fail && !file.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client && !file.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client && !file.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client && !file.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client && !file.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client && !file.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server && !file.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server && !file.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows && !file.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server && !file.getName().equals("graphSequenceChecker.grf") // ok, is to fail && !file.getName().equals("FixedData.grf") // ok, is to fail && !file.getName().equals("xpathReaderStates.grf") // ok, is to fail && !file.getName().equals("graphDataPolicy.grf") // ok, is to fail && !file.getName().equals("conversionDecimal2integer.grf") // ok, is to fail && !file.getName().equals("conversionDecimal2long.grf") // ok, is to fail && !file.getName().equals("conversionDouble2integer.grf") // ok, is to fail && !file.getName().equals("conversionDouble2long.grf") // ok, is to fail && !file.getName().equals("conversionLong2integer.grf") // ok, is to fail && !file.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths && !file.getName().equals("mountainsInformix.grf") // see issue 2550 && !file.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows && !file.getName().equals("XLSEncryptedFail.grf") // ok, is to fail && !file.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail && !file.getName().equals("XLSInvalidFile.grf") // ok, is to fail && !file.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail && !file.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail && !file.getName().equals("XLSWildcardStrict.grf") // ok, is to fail && !file.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail && !file.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail && !file.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail && !file.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail && !file.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail && !file.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts && !file.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts && !file.getName().equals("SSW_stringOutputField.grf") // ok, is to fail && !file.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail && !file.getName().equals("FailingGraph.grf") // ok, is to fail && !file.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts && !file.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail && !file.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail && !file.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail && !file.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines && !file.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved && !file.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate) && !file.getName().equals("EmailValidation.grf") // runs too long && !file.getName().equals("EmailFilterGreylistingExample.grf") // runs too long && !file.getName().equals("EmailFilterSimpleExample.grf") // runs too long && !file.getName().equals("graphEmailFilterTestSmtp.grf") // runs too long && !file.getName().contains("firebird") // remove after CL-2170 solved && !file.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved && !file.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved && !file.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved && !file.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved && !file.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved && !file.getName().equals("manyRecords.grf") // remove after CL-1292 implemented && !file.getName().equals("packedDecimal.grf") // remove after CL-1811 solved && !file.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately && !file.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf && !file.getName().equals("XMLWriter-CL-2404-CNO_OTF_ITSS.grf") // runs too long && !file.getName().equals("WebAccessLog.grf") // runs too long && !file.getName().equals("graphXLSReadWrite.grf") // runs too long && !file.getName().equals("JoiningAggregating.grf") // runs too long && !file.getName().equals("UDW_sortedInput_manyFiles.grf") // runs too long && !file.getName().equals("dataWriting.grf") // runs too long && !file.getName().equals("FSClosingTest-longRunning.grf") // runs too long && !file.getName().equals("CDW_sortedInput_manyFiles_CLO-5060.grf") // runs too long && !file.getName().equals("CreditCards.grf") // runs too long && !file.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail && !file.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved && !file.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail && !file.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail && !file.getName().equals("HTTPConnector_retry_CLO-1251.grf") // runs too long && !file.getName().equals("HTTPConnector_timeout_CLO-1251.grf") // runs too long && !file.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail && !file.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail && !file.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail && !file.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail && !file.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail && !file.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail && !file.getName().equals("LUTPersistent_wrong_metadata.grf") // ok, is to fail && !file.getName().equals("UDW_nonExistingDir_fail_CL-2478.grf") // ok, is to fail && !file.getName().equals("CTL_lookup_put_fail.grf") // ok, is to fail && !file.getName().equals("PersistentLookupTable_keyDuplicates_incompatibility.grf") // ok, is to fail && !file.getName().equals("SystemExecute_printBatchFile.grf") // ok, is to fail && !file.getName().equals("JoinMergeIssue_FailWhenMasterUnsorted.grf") // ok, is to fail && !file.getName().equals("UDW_remoteZipPartitioning_fail_CL-2564.grf") // ok, is to fail && !file.getName().equals("checkConfigTest.grf") // ok, is to fail && !file.getName().equals("DebuggingGraph.grf") // ok, is to fail && !file.getName().equals("graphDebuggingGraph.grf") // ok, is to fail && !file.getName().equals("CLO-404-recordCountsInErrorMessage.grf") // ok, is to fail && !file.getName().equals("TreeReader_CLO-4699.grf") // ok, is to fail && !file.getName().matches("Locale_.*_default.grf") // server only && !file.getName().equals("CompanyChecks.grf") // an example that needs embedded derby && !file.getName().equals("DatabaseAccess.grf") // an example that needs embedded derby && !file.getName().equals("graphDatabaseAccess.grf") // an example that needs embedded derby && !file.getName().equals("Twitter.grf") // an example that needs credentials && !file.getName().equals("XMLReader_no_output_port.grf") // ok, is to fail && !file.getName().startsWith("Proxy_") // allowed to run only on virt-cyan as proxy tests && !file.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server && !file.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately && !file.getName().equals("SimpleSequence_longValue.grf") // needs the sequence to be reset on start && !file.getName().equals("BeanWriterReader_employees.grf") // remove after CL-2474 solved && !file.getName().equals("GraphParameters_secure.grf") // server test && !file.getName().equals("GraphParameters_secureOverriden.grf") // server test && !file.getName().equals("GraphParameters_secureOverriden_subgraph.grf") // subgraph of server test && !file.getName().equals("SSR_CloseOnError.grf") // subgraph of server test && !file.getName().equals("TypedProperties_CLO-1997.grf") // server test && !file.getName().equals("EmptySubGraph.grf") // server test && !file.getName().equals("ParallelReader_HDFS.grf") // cluster test && !file.getName().equals("SubgraphsReuse.grf") // contains subgraphs && !file.getName().startsWith("Issues") // contains subgraphs && !file.getName().equals("SubgraphsSimplifyingGraph.grf") // contains subgraphs && !file.getName().equals("GEOCoding.grf") // contains subgraphs && !file.getName().equals("RandomDataGenerator.grf") // contains subgraphs && !file.getName().equals("graphHTTPConnector.grf") // external service is unstable && !file.getName().equals("WSC_Soap12_CLO-3349.grf") // external service is unstable (see CLO-9877) && !file.getName().equals("WebServiceClient.grf") // external service is unstable && !file.getName().equals("WebServiceClient1.grf") // external service is unstable && !file.getName().equals("WebServiceClientWithNS.grf") // external service is unstable && !file.getName().equals("WebServiceClient_HttpHeaders_invalid_field.grf") // negative test && !file.getName().equals("CLO-2214_pre_post_execute_race_condition.grf") // ok, is to fail && !file.getName().equals("EmptyGraph.grf") // ok, is to fail && !file.getName().equals("informix.grf") // remove after CLO-2793 solved && !file.getName().equals("EmailReader_BadDataFormatException.grf") // ok, is to fail && !file.getName().equals("PhaseOrderCheck.grf") // ok, is to fail && !file.getName().equals("JoinApproximative_invalid_join_key_CLO-4748.grf") // ok, is to fail && !file.getName().equals("ExtSort_missing_sort_key_CLO-4741.grf") // ok, is to fail && !file.getName().equals("Transformations_invalid_language.grf") // ok, is to fail && !file.getName().equals("graphCloverData.grf") // remove after CLO-4360 fixed && !file.getName().equals("MetadataWriting.grf") // server test && !file.getName().equals("WSC_ThrowException.grf") // negative test && !file.getName().startsWith("DBInputTable_query_error_logging_") // negative tests && !file.getName().startsWith("DBExecute_query_error_logging_") // negative tests && !file.getName().equals("EclipseClasspathParsing_CLO-6013.grf") // server test && !file.getName().equals("CDR_corruptFile_CLO-5329.grf") // negative test && !file.getName().equals("CDR_metadataPropagation_CLO-2850.grf") // negative test && !file.getName().equals("CDW_append_CLO-5217.grf") // negative test && !file.getName().equals("CDW_autofilling_CLO-6311.grf") // server test && !file.getName().equals("CTL_getComponentProperty_dynamicParam_fail_CLO-3838.grf") // negative test && !file.getName().equals("CTL_isSubgraphInputPortConnected_1_negative.grf") // negative test && !file.getName().equals("CTL_isSubgraphInputPortConnected_2_negative.grf") // negative test && !file.getName().equals("CTL_isSubgraphOutputPortConnected_1_negative.grf") // negative test && !file.getName().equals("CTL_isSubgraphOutputPortConnected_2_negative.grf") // negative test && !file.getName().equals("CTL_raiseError_CLO-4084.grf") // negative test && !file.getName().equals("CoDR_missingFields_CLO-2838.grf") // negative test && !file.getName().equals("CoDR_parsingError_CLO-5703.grf") // negative test && !file.getName().equals("CoDR_prematureFinish_CLO-5610.grf") // negative test && !file.getName().equals("CoDR_tooManyFields_CLO-2838.grf") // negative test && !file.getName().equals("CopyFiles_emptyUrl_CLO-5114.grf") // negative test && !file.getName().equals("CopyFiles_maskPassword_CLO-6064.grf") // negative test && !file.getName().equals("CopyFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test && !file.getName().equals("CopyFiles_nativePath_Windows.grf") // windows test && !file.getName().equals("CreateFiles_createDir_fail.grf") // negative test && !file.getName().equals("CreateFiles_emptyUrl_CLO-5114.grf") // negative test && !file.getName().equals("CreateFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test && !file.getName().equals("DBExecute_external_sql_resolve_CLO-3641.grf") // negative test && !file.getName().equals("DBJoin_checkConfig_CLO-4826.grf") // negative test && !file.getName().equals("DeleteFiles_emptyUrl_CLO-5114.grf") // negative test && !file.getName().equals("DeleteFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test && !file.getName().startsWith("Denormalizer_incompleteGroupAllowed_fail") // negative test && !file.getName().equals("Divider_fail.grf") // negative test && !file.getName().startsWith("EOF_as_delimiter_onRecord_fail_") // negative test && !file.getName().equals("KeyValuesToRecord_WrongSortOrder.grf") // negative test && !file.getName().equals("ListFiles_emptyUrl_CLO-5114.grf") // negative test && !file.getName().equals("ListFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test && !file.getName().equals("LoopInGraph3.grf") // negative test && !file.getName().startsWith("LoopWithSubgraph_") // negative and server tests && !file.getName().equals("MoveFiles_emptyUrl_CLO-5114.grf") // negative test && !file.getName().equals("MoveFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test && !file.getName().equals("NonExistingSandbox.grf") // negative test && !file.getName().equals("NotNullableFieldWithDefaultValueInNullValues_CLO-4569.grf") // negative test && !file.getName().equals("ParameterDynamicValue_circular_reference_fail.grf") // negative test && !file.getName().equals("Pivot_CLO-4726_nameMissing.grf") // negative test && !file.getName().equals("Pivot_CLO-4726_valueMissing.grf") // negative test && !file.getName().equals("Pivot_NPE_CLO-4739.grf") // negative test && !file.getName().equals("ProfilerProbe_metadata_mismatch_active.grf") // negative test && !file.getName().equals("ProfilerProbe_no_output_port_no_persist.grf") // negative test && !file.getName().startsWith("RedundantPort_CLO-6774") // negative test && !file.getName().equals("RunGraph_recursion_detection_CLO-4586.grf") // negative test && !file.getName().equals("SFTP_missingPrivateKey_CLO-5770.grf") // negative test && !file.getName().equals("Tableau-TerminateIfTableExists.grf") // negative test && !file.getName().startsWith("Tableau-Unsupported") // negative test && !file.getName().equals("UDR_fixedLengthMetadata_errorReporting_CLO-3955.grf") // negative test && !file.getName().equals("UDR_invalidDataPolicy.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_CharByteDataParser_controlled_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_CharByteDataParser_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_CharByteDataParser_skip_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_DataParser_controlled_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_DataParser_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_DataParser_skip_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_SimpleDataParser_controlled_fail.grf") // negative test && !file.getName().equals("UDR_unmappable_characters_SimpleDataParser_fail.grf") // negative test && !file.getName().equals("UDR_checkConfig_missingFile_CLO-9584.grf") // negative test && !file.getName().equals("WildcardsInDirPath.grf") // negative test && !file.getName().equals("dataGenerator.grf") // negative test && !file.getName().equals("BuiltInGraphParameters_parent.grf") // server test && !file.getName().startsWith("CTL_getSubgraphInputPortsCount_") // server test && !file.getName().startsWith("CTL_getSubgraphOutputPortsCount_") // server test && !file.getName().equals("CTL_isSubgraphInputPortConnected_1.grf") // server test && !file.getName().equals("CTL_isSubgraphInputPortConnected_2.grf") // server test && !file.getName().equals("CTL_isSubgraphOutputPortConnected_1.grf") // server test && !file.getName().equals("CTL_isSubgraphOutputPortConnected_2.grf") // server test && !file.getName().startsWith("ConditionalExecution_0") // server test && !file.getName().equals("Denormalizer_groupBySize_earlyRecordRelease.grf") // server test && !file.getName().equals("DisableAsTrash_metadata_propagation_CLO-6749.grf") // server test && !file.getName().equals("ExecuteProfilerJob_executionLabel.grf") // server test && !file.getName().equals("MetadataPropagation_CLO-6057.grf") // server test && !file.getName().equals("MoreFilesMatchPattern.grf") // server test && !file.getName().equals("NoFileMatchesPattern.grf") // server test && !file.getName().equals("OneFileMatchesPattern.grf") // server test && !file.getName().startsWith("OptionalPorts_0") // server test && !file.getName().equals("ParameterDynamicValue_dictionary_use.grf") // server test && !file.getName().equals("ParameterDynamicValue_disable_component.grf") // server test && !file.getName().equals("ParameterDynamicValue_override_dynamic_value_from_parent.grf") // server test && !file.getName().equals("ParameterDynamicValue_subgraph_simple_usage.grf") // server test && !file.getName().equals("ParameterEmptyValue_secure_CLO-4615.grf") // server test && !file.getName().equals("ProfilerProbe_no_output_port.grf") // server test && !file.getName().equals("ProfilerProbe_persisting_results.grf") // server test && !file.getName().equals("SimpleSequence_concurrent.grf") // server test && !file.getName().equals("UDW_escapeSequences_CLO-5660.grf") // server test && !file.getName().equals("SetJobOutput_dictionary_CLO-3007.grf") // server test && !file.getName().equals("ValidationDefaultLanguageSettings.grf") // server test && !file.getName().equals("DB_rollback_CLO-4878.grf") // server test && !file.getName().equals("InvalidFileUrl_CLO-11790.grf") // server test && !file.getName().equals("ValidationTransformLifeCycle.grf") // have to be run only once && !file.getName().equals("Tableau-ThreadSafe.grf") // disabled test && !file.getName().equals("SalesforceMigration.grf") // Salesforce example && !file.getName().equals("SalesforceRead.grf") // Salesforce example && (!file.getParentFile().getName().equals("Salesforce") || file.getName().equals("SalesforceBulkReaderWriter_allDataTypes.grf")) // CLO-9285, run 1 salesforce test && !file.getParentFile().getName().equals("Wave") // Salesfore Wave && !file.getName().startsWith("JSONExtract_employees_invalid_") // negative test && !file.getName().equals("JSONExtract_AllTypes_invalid_field.grf") // negative test && !file.getName().equals("SetTrustStore.grf") // env set-up graph && !file.getName().equals("check-logs.grf") // graph for checking logs from server tests && !file.getName().equals("UDR_zip_nonExistingEntry_CLO-11350.grf") // negative test && !file.getName().equals("MongoDBW_bulk_insertOne_id_fail_graph.grf") // negative test && !file.getName().equals("MongoDBReader_readConcern_connection_CLO-11986.grf") // negative test ; } }; IOFileFilter dirFilter = new AbstractFileFilter() { @Override public boolean accept(File file) { return file.isDirectory() && !file.getName().equals("bigRecords") // runs too long && !file.getName().equals("cluster") // cluster tests && !file.getName().equals("DataService") // no need to run on engine && !file.getName().equals("S3") && !file.getName().equals("Redshift") // redshift tests && !file.getName().equals("email") && !file.getName().equals("performance") && !file.getName().equals("dataPolicy") // negative tests && !file.getName().equals("metadataPropagation") // mostly server tests && !file.getName().equals("ExecuteGraph") // jobflows && !file.getName().equals("RecordToKeyValues") // CLO-7086: temporarily removed tests && !file.getName().equals("KeyValuesToRecord") // CLO-7086: temporarily removed tests && !file.getName().equals("DB2DataWriter") // can only work with db2 client && !file.getName().equals("hadoop") // removed temporarily - see CLO-8574 && !file.getName().equals("windows"); // wokna only tests } }; Collection<File> filesCollection = org.apache.commons.io.FileUtils.listFiles(graphsDir, fileFilter, dirFilter); File[] graphFiles = filesCollection.toArray(new File[0]); Arrays.sort(graphFiles); for(int j = 0; j < graphFiles.length; j++){ suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false)); suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false)); } } return suite; } @Override protected void setUp() throws Exception { super.setUp(); initEngine(); } protected static String getTestName(String basePath, File graphFile, boolean batchMode) { final StringBuilder ret = new StringBuilder(); final String n = graphFile.getName(); int lastDot = n.lastIndexOf('.'); if (lastDot == -1) { ret.append(n); } else { ret.append(n.substring(0, lastDot)); } if (batchMode) { ret.append("-batch"); } else { ret.append("-nobatch"); } return ret.toString(); } protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) { super(getTestName(basePath, graphFile, batchMode)); this.basePath = basePath; this.graphFile = graphFile; this.batchMode = batchMode; this.cleanUp = cleanup; } @Override protected void runTest() throws Throwable { final String baseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/'); logger.info("Project dir: " + baseAbsolutePath); logger.info("Analyzing graph " + graphFile.getPath()); logger.info("Batch mode: " + batchMode); final GraphRuntimeContext runtimeContext = new GraphRuntimeContext(); runtimeContext.setUseJMX(false); runtimeContext.setContextURL(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath))); // context URL should be absolute runtimeContext.setJobUrl(FileUtils.getFileURL(runtimeContext.getContextURL(), graphFile.getPath()).toString()); // absolute path in PROJECT parameter is required for graphs using Derby database runtimeContext.addAdditionalProperty("PROJECT", baseAbsolutePath); if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) { final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath(); runtimeContext.addAdditionalProperty("CONN_DIR", connDir); logger.info("CONN_DIR set to " + connDir); } if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath(); runtimeContext.addAdditionalProperty("LIB_DIR", libDir); logger.info("LIB_DIR set to " + libDir); } // for scenarios graphs, add the TRANS dir to the classpath if (basePath.contains("cloveretl.test.scenarios")) { List<URL> classpath = new ArrayList<URL>(); classpath.add(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath) + TRANS_DIR + "/")); if (CLASSPATHS.containsKey(graphFile.getName())) { for (String path : CLASSPATHS.get(graphFile.getName())) { classpath.add(FileUtils.getFileURL(runtimeContext.getContextURL(), path)); } } runtimeContext.setRuntimeClassPath(classpath.toArray(new URL[classpath.size()])); runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath()); } runtimeContext.setBatchMode(batchMode); final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext); try { graph.setDebugMode(false); EngineInitializer.initGraph(graph); for (int i = 0; i < 2; i++) { final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext); Result result = Result.N_A; result = futureResult.get(); switch (result) { case FINISHED_OK: // everything O.K. logger.info("Execution of graph successful !"); break; case ABORTED: // execution was ABORTED !! logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); break; default: logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); } } } catch (Throwable e) { throw new IllegalStateException("Error executing graph " + graphFile, e); } finally { if (cleanUp) { cleanupData(); } logger.info("Transformation graph is freeing.\n"); graph.free(); } } private void cleanupData() { for (String outDir : OUT_DIRS) { File outDirFile = new File(basePath, outDir); File[] file = outDirFile.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile(); } }); for (int i = 0; i < file.length; i++) { final boolean drt = file[i].delete(); if (drt) { logger.info("Cleanup: deleted file " + file[i].getAbsolutePath()); } else { logger.info("Cleanup: error delete file " + file[i].getAbsolutePath()); } } } } }
package com.eboot; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.Random; import static junit.framework.TestCase.fail; @RunWith(SpringRunner.class) @SpringBootTest public class EmployeebootApplicationTests { @Test public void contextLoads() { whatToDoInTest(); } @Test public void contextLoads2() { whatToDoInTest(); } @Test public void contextLoads3() { whatToDoInTest(); } @Test public void contextLoads4() { whatToDoInTest(); } @Test public void contextLoads5() { whatToDoInTest(); } @Test public void contextLoads6() { whatToDoInTest(); } @Test public void contextLoads7() { whatToDoInTest(); } @Test public void contextLoads8() { whatToDoInTest(); } @Test public void contextLoads9() { whatToDoInTest(); } @Test public void contextLoads10() { whatToDoInTest(); } private boolean getRandomBoolean() { Random random = new Random(); return random.nextBoolean(); } private void whatToDoInTest() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } boolean condition = getRandomBoolean(); if (condition) { fail(); } } @Rule public TestRule listen = new TestWatcher() { @Override public void failed(Throwable t, Description description) { final String endpoint = "https://hooks.slack.com/services/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"; String text = "Test Failed" + " \n" //+ Arrays.toString(t.getStackTrace()) + System.getenv() + "\n" + System.getProperties().toString() + "\n"; System.getProperties(); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(endpoint, "{\"text\": \"" + text + "\"}", String.class); } }; }
package com.codahale.metrics; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; /** * A registry of metric instances. */ public class MetricRegistry implements MetricSet { /** * Concatenates elements to form a dotted name, eliding any null values or empty strings. * * @param name the first element of the name * @param names the remaining elements of the name * @return {@code name} and {@code names} concatenated by periods */ public static String name(String name, String... names) { final StringBuilder builder = new StringBuilder(); append(builder, name); if (names != null) { for (String s : names) { append(builder, s); } } return builder.toString(); } /** * Concatenates a class name and elements to form a dotted name, eliding any null values or * empty strings. * * @param klass the first element of the name * @param names the remaining elements of the name * @return {@code klass} and {@code names} concatenated by periods */ public static String name(Class<?> klass, String... names) { return name(klass.getName(), names); } private static void append(StringBuilder builder, String part) { if (part != null && !part.isEmpty()) { if (builder.length() > 0) { builder.append('.'); } builder.append(part); } } private final ConcurrentMap<String, Metric> metrics; private final List<MetricRegistryListener> listeners; private final MetricPrefixStrategy prefixStrategy; public MetricRegistry(){ this(null); } /** * Creates a new {@link MetricRegistry}. */ public MetricRegistry(MetricPrefixStrategy prefixStrategy) { this.metrics = buildMap(); this.listeners = new CopyOnWriteArrayList<MetricRegistryListener>(); this.prefixStrategy = prefixStrategy; } /** * Creates a new {@link ConcurrentMap} implementation for use inside the registry. Override this * to create a {@link MetricRegistry} with space- or time-bounded metric lifecycles, for * example. * * @return a new {@link ConcurrentMap} */ protected ConcurrentMap<String, Metric> buildMap() { return new ConcurrentHashMap<String, Metric>(); } @SuppressWarnings("unchecked") public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric instanceof MetricSet) { registerAll(name, (MetricSet) metric); } else { name = getFullName(name); final Metric existing = metrics.putIfAbsent(name, metric); if (existing == null) { onMetricAdded(name, metric); } else { throw new IllegalArgumentException("A metric named " + name + " already exists"); } } return metric; } public void registerAll(MetricSet metrics) throws IllegalArgumentException { registerAll(null, metrics); } /** * Creates a new {@link Counter} and registers it under the given name. * * @param name the name of the metric * @return a new {@link Counter} */ public Counter counter(String name) { return getOrAdd(name, MetricBuilder.COUNTERS); } /** * Creates a new {@link Histogram} and registers it under the given name. * * @param name the name of the metric * @return a new {@link Histogram} */ public Histogram histogram(String name) { return getOrAdd(name, MetricBuilder.HISTOGRAMS); } /** * Creates a new {@link Meter} and registers it under the given name. * * @param name the name of the metric * @return a new {@link Meter} */ public Meter meter(String name) { return getOrAdd(name, MetricBuilder.METERS); } /** * Creates a new {@link Timer} and registers it under the given name. * * @param name the name of the metric * @return a new {@link Timer} */ public Timer timer(String name) { return getOrAdd(name, MetricBuilder.TIMERS); } /** * Removes the metric with the given name. * * @param name the name of the metric * @return whether or not the metric was removed */ public boolean remove(String name) { name = getFullName(name); final Metric metric = metrics.remove(name); if (metric != null) { onMetricRemoved(name, metric); return true; } return false; } /** * Removes all metrics which match the given filter. * * @param filter a filter */ public void removeMatching(MetricFilter filter) { for (Map.Entry<String, Metric> entry : metrics.entrySet()) { if (filter.matches(entry.getKey(), entry.getValue())) { remove(entry.getKey()); } } } /** * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on * metric creation. Listeners will be notified in the order in which they are added. * <p/> * <b>N.B.:</b> The listener will be notified of all existing metrics when it first registers. * * @param listener the listener that will be notified */ public void addListener(MetricRegistryListener listener) { listeners.add(listener); for (Map.Entry<String, Metric> entry : metrics.entrySet()) { notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); } } /** * Removes a {@link MetricRegistryListener} from this registry's collection of listeners. * * @param listener the listener that will be removed */ public void removeListener(MetricRegistryListener listener) { listeners.remove(listener); } /** * Returns a set of the names of all the metrics in the registry. * * @return the names of all the metrics */ public SortedSet<String> getNames() { return Collections.unmodifiableSortedSet(new TreeSet<String>(metrics.keySet())); } /** * Returns a map of all the gauges in the registry and their names. * * @return all the gauges in the registry */ public SortedMap<String, Gauge> getGauges() { return getGauges(MetricFilter.ALL); } /** * Returns a map of all the gauges in the registry and their names which match the given filter. * * @param filter the metric filter to match * @return all the gauges in the registry */ public SortedMap<String, Gauge> getGauges(MetricFilter filter) { return getMetrics(Gauge.class, filter); } /** * Returns a map of all the counters in the registry and their names. * * @return all the counters in the registry */ public SortedMap<String, Counter> getCounters() { return getCounters(MetricFilter.ALL); } /** * Returns a map of all the counters in the registry and their names which match the given * filter. * * @param filter the metric filter to match * @return all the counters in the registry */ public SortedMap<String, Counter> getCounters(MetricFilter filter) { return getMetrics(Counter.class, filter); } /** * Returns a map of all the histograms in the registry and their names. * * @return all the histograms in the registry */ public SortedMap<String, Histogram> getHistograms() { return getHistograms(MetricFilter.ALL); } /** * Returns a map of all the histograms in the registry and their names which match the given * filter. * * @param filter the metric filter to match * @return all the histograms in the registry */ public SortedMap<String, Histogram> getHistograms(MetricFilter filter) { return getMetrics(Histogram.class, filter); } /** * Returns a map of all the meters in the registry and their names. * * @return all the meters in the registry */ public SortedMap<String, Meter> getMeters() { return getMeters(MetricFilter.ALL); } /** * Returns a map of all the meters in the registry and their names which match the given filter. * * @param filter the metric filter to match * @return all the meters in the registry */ public SortedMap<String, Meter> getMeters(MetricFilter filter) { return getMetrics(Meter.class, filter); } /** * Returns a map of all the timers in the registry and their names. * * @return all the timers in the registry */ public SortedMap<String, Timer> getTimers() { return getTimers(MetricFilter.ALL); } /** * Returns a map of all the timers in the registry and their names which match the given filter. * * @param filter the metric filter to match * @return all the timers in the registry */ public SortedMap<String, Timer> getTimers(MetricFilter filter) { return getMetrics(Timer.class, filter); } @SuppressWarnings("unchecked") private <T extends Metric> T getOrAdd(String name, MetricBuilder<T> builder) { final String fullName = getFullName(name); final Metric metric = metrics.get(fullName); final Metric added; if (builder.isInstance(metric)) { return (T) metric; } else if (metric == null) { try { return register(name, builder.newMetric()); } catch (IllegalArgumentException e) { added = metrics.get(fullName); if (builder.isInstance(added)) { return (T) added; } } } else { added = null; } throw new IllegalArgumentException(name + " is already used for a different type of metric: " + metric + ", added: " + added); } @SuppressWarnings("unchecked") private <T extends Metric> SortedMap<String, T> getMetrics(Class<T> klass, MetricFilter filter) { final TreeMap<String, T> timers = new TreeMap<String, T>(); for (Map.Entry<String, Metric> entry : metrics.entrySet()) { if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(), entry.getValue())) { timers.put(entry.getKey(), (T) entry.getValue()); } } return Collections.unmodifiableSortedMap(timers); } private void onMetricAdded(String name, Metric metric) { for (MetricRegistryListener listener : listeners) { notifyListenerOfAddedMetric(listener, metric, name); } } private void notifyListenerOfAddedMetric(MetricRegistryListener listener, Metric metric, String name) { if (metric instanceof Gauge) { listener.onGaugeAdded(name, (Gauge<?>) metric); } else if (metric instanceof Counter) { listener.onCounterAdded(name, (Counter) metric); } else if (metric instanceof Histogram) { listener.onHistogramAdded(name, (Histogram) metric); } else if (metric instanceof Meter) { listener.onMeterAdded(name, (Meter) metric); } else if (metric instanceof Timer) { listener.onTimerAdded(name, (Timer) metric); } else { throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); } } private void onMetricRemoved(String name, Metric metric) { for (MetricRegistryListener listener : listeners) { notifyListenerOfRemovedMetric(name, metric, listener); } } private void notifyListenerOfRemovedMetric(String name, Metric metric, MetricRegistryListener listener) { if (metric instanceof Gauge) { listener.onGaugeRemoved(name); } else if (metric instanceof Counter) { listener.onCounterRemoved(name); } else if (metric instanceof Histogram) { listener.onHistogramRemoved(name); } else if (metric instanceof Meter) { listener.onMeterRemoved(name); } else if (metric instanceof Timer) { listener.onTimerRemoved(name); } else { throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); } } public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException { for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { register(name(prefix, entry.getKey()), entry.getValue()); } } } private String getFullName(String name){ final String fullName; if(prefixStrategy == null){ fullName = name; } else { fullName = name(prefixStrategy.getMetricPrefix(), name); } return fullName; } @Override public Map<String, Metric> getMetrics() { return Collections.unmodifiableMap(metrics); } /** * A quick and easy way of capturing the notion of default metrics. */ private interface MetricBuilder<T extends Metric> { MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { @Override public Counter newMetric() { return new Counter(); } @Override public boolean isInstance(Metric metric) { return Counter.class.isInstance(metric); } }; MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { @Override public Histogram newMetric() { return new Histogram(new ExponentiallyDecayingReservoir()); } @Override public boolean isInstance(Metric metric) { return Histogram.class.isInstance(metric); } }; MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { @Override public Meter newMetric() { return new Meter(); } @Override public boolean isInstance(Metric metric) { return Meter.class.isInstance(metric); } }; MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { @Override public Timer newMetric() { return new Timer(); } @Override public boolean isInstance(Metric metric) { return Timer.class.isInstance(metric); } }; T newMetric(); boolean isInstance(Metric metric); } }
package lex.fa; import lex.ReParser; import lex.fa.node.FaNode; import lex.fa.node.NfaNode; import java.util.*; class Nfa { private static int indexes = 0; private static Map<String, String> escapeChars = null; private LinkedList<NfaNode> nodes; Nfa() { initializeEscapeChars(); } private void initializeEscapeChars() { if (escapeChars == null) { escapeChars = new HashMap<>(); String[] source = {"\\(", "\\)", "\\[", "\\]", "\\*", "\\+", "\\.", "\\-", "\\|", "\\@", "\\?", "\\!"}; int[] target = {'(', ')', '[', ']', '*', '+', '.', '-', '|', '@', '?', '!'}; for (int i = 0; i < source.length; i++) { escapeChars.put(source[i], String.valueOf((char) target[i])); } escapeChars.put(ReParser.epsilon, ""); } } private Nfa(String operand) { nodes = new LinkedList<>(); int begin = getNextIndex(), end = getNextIndex(); nodes.add(new NfaNode(begin, operand, end)); nodes.add(new NfaNode(end)); } private int getNextIndex() { return indexes++; } public static void main(String[] args) { Nfa nfa = new Nfa(); nfa.initializeEscapeChars(); for (String s : escapeChars.keySet()) { System.out.println(s + " " + escapeChars.get(s)); } } ArrayList<FaNode<Set<Integer>>> construct(Map<Integer, String[]> postfixRes) { nodes = new LinkedList<>(); indexes = 0; nodes.add(new NfaNode(getNextIndex())); for (Map.Entry<Integer, String[]> entry : postfixRes.entrySet()) { Nfa nfa = reToNfa(entry.getValue(), entry.getKey()); nodes.getFirst().addTransition("", nfa.nodes.getFirst().getIndex()); nodes.addAll(nfa.nodes); } ArrayList<FaNode<Set<Integer>>> nfa = new ArrayList<>(getIndexUpperBound()); for (int i = 0; i < getIndexUpperBound(); i++) { nfa.add(null); } for (NfaNode node : nodes) { if (nfa.get(node.getIndex()) == null) { nfa.set(node.getIndex(), node); } else { System.err.println("error"); } } return nfa; } private Nfa reToNfa(String[] postfixRe, int action) { Deque<Nfa> stack = new LinkedList<>(); for (String s : postfixRe) { switch (s.charAt(0)) { case '*': stack.push(stack.pop().closure()); break; case '|': Nfa nfa = stack.pop(); stack.push(stack.pop().union(nfa)); break; case '@': nfa = stack.pop(); stack.push(stack.pop().concatenation(nfa)); break; default: stack.push(new Nfa(processOperand(s))); break; } } Nfa nfa = stack.pop(); nfa.nodes.getLast().setAccepting(action); return nfa; } private int getIndexUpperBound() { return indexes; } private Nfa closure() { int oldBegin = nodes.getFirst().getIndex(); int newEnd = getNextIndex(); nodes.getLast().addTransition("", oldBegin); nodes.getLast().addTransition("", newEnd); nodes.addFirst(new NfaNode(getNextIndex())); nodes.addLast(new NfaNode(newEnd)); nodes.getFirst().addTransition("", oldBegin); nodes.getFirst().addTransition("", nodes.getLast().getIndex()); return this; } private Nfa union(Nfa nfa) { NfaNode newFirst = new NfaNode(getNextIndex(), "", this.nodes.getFirst().getIndex()); newFirst.addTransition("", nfa.nodes.getFirst().getIndex()); NfaNode newLast = new NfaNode(getNextIndex()); this.nodes.getLast().addTransition("", newLast.getIndex()); nfa.nodes.getLast().addTransition("", newLast.getIndex()); this.nodes.addAll(nfa.nodes); this.nodes.addFirst(newFirst); this.nodes.addLast(newLast); return this; } private Nfa concatenation(Nfa nfa) { NfaNode node = nfa.nodes.removeFirst(); this.nodes.getLast().addAllTransitions(node.getAllTransitions()); this.nodes.addAll(nfa.nodes); return this; } private String processOperand(String operand) { if (escapeChars.containsKey(operand)) { operand = escapeChars.get(operand); } return operand; } }
package client; import java.io.InvalidClassException; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.io.StreamCorruptedException; import java.lang.Math; import java.lang.ClassNotFoundException; import java.lang.IllegalArgumentException; import java.lang.NullPointerException; import java.lang.NumberFormatException; import java.lang.Thread; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Random; import utils.Log; import utils.Matrix; import utils.NetworkNode; import utils.RandomGenerator; import utils.Request; /** This class contains the implementation of a Client that can send matrices to a server in order to calculate a function on it. */ public class Client extends NetworkNode { private Socket socket = null; private int requestID = 0; private InetAddress serverAddress = null; private ObjectInputStream inputStream = null; private ObjectOutputStream outputStream = null; private double RATE = 3d; private boolean allResponsesReceived = false; private int NUMBER_REQUESTS = 50; /* Thread that handles responses from the server */ private Thread receiverThread = new Thread(new Runnable() { public void run() { int i = 1; inputStream = getSocketInputStream(socket); while (i < NUMBER_REQUESTS) { Request response = receive(inputStream); if (response == null) { allResponsesReceived = true; break; } System.out.println("Received Reponse from server for request " + response.getId()); i++; } } }); /** Constructor @addr : The address of the server @port : The port of the server */ public Client(String addr, String port) { this.setPort(port); this.setServerAddress(addr); } public void initializeSocket(InetAddress address, int port) { try { this.socket = new Socket(address, port); } catch (IOException e) { Log.error("Client initializeSocket() - I/O error occured when creating the socket."); } catch (IllegalArgumentException e) { Log.error("Client initializeSocket() - The port is outside the range of valid port values (0-65535)"); } catch (NullPointerException e) { Log.error("Client initializeSocket() - The address is null"); } } public void start() { Log.print("Client - start"); this.initializeSocket(this.serverAddress, this.getPort()); outputStream = getSocketOutputStream(socket); receiverThread.start(); int i = 0; Log.print("Beginning sending request"); while ( i < NUMBER_REQUESTS ) { loadGenerator(); Log.print("Sending Request number #" + requestID); i++; } flushOutput(outputStream); /* We should not stop until all responses are received */ while (! allResponsesReceived) { Log.print("All responses not yet received... waiting."); threadSleep(1); } receiverThread.interrupt(); } //FIXME Move in an other class public void loadGenerator(){ Random gen = new Random(); double d = gen.nextDouble(); double interTime = Math.log(1d-d)/(-RATE); System.out.println("Waiting for "+interTime+" seconds"); this.threadSleep((long)interTime); this.send( createRequest() , this.outputStream ); } @Override /** This function releases the resources linked to a client and stop all his action. */ public void stop() { try { socket.close(); } catch (IOException e ) { System.err.println("IOException - Client.stop()"); e.printStackTrace(); } } /** Generates a randomly-sized Request */ public Request createRequest(){ int i = 5; //Use RandomGenerator(int s) to force the size of the generated matrix RandomGenerator builder = new RandomGenerator(); builder.fillMatrix(); Matrix matrix = builder.generate(); return new Request(requestID++, i, matrix); } /** Set the server address from a String */ public void setServerAddress(String address) { try { this.serverAddress = InetAddress.getByName(address); } catch (UnknownHostException e) { System.err.println("Error - Client setServerAddress() - no IP address for the host could be found. Exiting..."); System.exit(-1); } } }
package com.github.tminglei.bind; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.ResourceBundle; import static org.testng.Assert.*; import static com.github.tminglei.bind.Constraints.*; import static com.github.tminglei.bind.FrameworkUtils.*; import static com.github.tminglei.bind.Mappings.*; import static com.github.tminglei.bind.Processors.*; import static com.github.tminglei.bind.Simple.*; import static com.github.tminglei.bind.Transformers.*; public class TransformTest { private ResourceBundle bundle = ResourceBundle.getBundle("bind-messages"); private Messages messages = (key) -> "xx".equals(key) ? "haha" : bundle.getString(key); private Mapping<?> mapping = mapping( field("id", vLong()), field("data", attach(expandJson()).to(mapping( field("email", attach(required("%s is required")).to(text(maxLength(20, "%s: length > %s"), email("%s: invalid email")))), field("price", attach(omitLeft("$")).to(vFloat())), field("count", vInt().verifying(min(3), max(10))) )).label("xx").verifying((label, vObj, messages1) -> { float price = vObj.get("price"); int count = vObj.get("count"); if (price * count > 1000) { return Arrays.asList(label + ": total cost too much!"); } else return Collections.EMPTY_LIST; })) ).map(transTo(Bean2.class)); @BeforeClass public void start() { System.out.println(Utils.cyan("test bean transform")); } @Test public void testTransform() { Map<String, String> data = newmap( entry("id", "133"), entry("data", "{\"email\":\"etttt@example.com\", \"price\":\"$137.5\", \"count\":5}") ); BindObject bindObj = new FormBinder(messages).bind(mapping, data); Bean2 expected = new Bean2(133, new Bean1("etttt@example.com", 137.5f, 5)); assertEquals(bindObj.get(), expected); } static class Bean1 { private String email; private float price; private int count; public Bean1() {} public Bean1(String email, float price, int count) { this.email = email; this.price = price; this.count = count; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public int hashCode() { int emailHash = email == null ? 0 : email.hashCode(); return emailHash * 37 + Float.hashCode(price) * 17 + count; } @Override public boolean equals(Object object) { if (object instanceof Bean1) { Bean1 other = (Bean1) object; return price == other.price && count == other.count && (email == null ? other.email == null : email.equals(other.email)); } else return false; } @Override public String toString() { StringBuilder bf = new StringBuilder(); bf.append("{"); bf.append("email=").append(email); bf.append(", "); bf.append("price=").append(price); bf.append(", "); bf.append("count=").append(count); bf.append("}"); return bf.toString(); } } static class Bean2 { private long id; private Bean1 data; public Bean2() {} public Bean2(long id, Bean1 data) { this.id = id; this.data = data; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Bean1 getData() { return data; } public void setData(Bean1 data) { this.data = data; } @Override public int hashCode() { return Long.hashCode(id) * 17 + (data == null ? 0 : data.hashCode()); } @Override public boolean equals(Object object) { if (object instanceof Bean2) { Bean2 other = (Bean2) object; return id == other.id && (data == null ? other.data == null : data.equals(other.data)); } else return false; } @Override public String toString() { StringBuilder bf = new StringBuilder(); bf.append("{"); bf.append("id=").append(id); bf.append(", "); bf.append("data=").append(data); bf.append("}"); return bf.toString(); } } }